File tree Expand file tree Collapse file tree 1 file changed +91
-0
lines changed Expand file tree Collapse file tree 1 file changed +91
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .Scanner ;
2+
3+ public class HeapSort {
4+ public static void heapify (int a [],int i ,int n )
5+ {
6+
7+ int l =2 *i +1 ;
8+ int r =2 *i +2 ;
9+
10+
11+ int temp ,largest ;
12+
13+ if (l <n && a [l ]>a [i ])
14+ largest =l ;
15+ else
16+ largest =i ;
17+
18+ if (r <n && a [r ]>a [largest ])
19+ largest =r ;
20+
21+ if (largest !=i )
22+ {
23+ temp =a [largest ];
24+ a [largest ]=a [i ];
25+ a [i ]=temp ;
26+
27+ heapify (a ,largest ,n );
28+ }
29+
30+
31+ }
32+
33+ public static void bheap (int a [])
34+ {
35+
36+ for (int i =(a .length /2 )-1 ;i >=0 ;i --)
37+ {
38+
39+ heapify (a ,i ,a .length );
40+
41+ }
42+
43+ }
44+
45+ public static void Sort (int a [])
46+ {
47+ int temp ,j ,i ;
48+
49+ bheap (a );
50+
51+ for ( i =(a .length )-1 ; i >0 ;)
52+ {
53+ temp =a [0 ];
54+ a [0 ]=a [i ];
55+ a [i ]=temp ;
56+ heapify (a ,0 ,i --) ;
57+
58+ }
59+
60+ }
61+
62+ public static void printarray (int a [])
63+ {
64+ System .out .println ();
65+ for (int j : a ) {
66+
67+ System .out .print (j + " " );
68+ }
69+
70+ }
71+ public static void main (String [] args )
72+ {
73+ int n , res ,i ;
74+ Scanner s = new Scanner (System .in );
75+ System .out .print ("Enter number of elements in the array:" );
76+ n = s .nextInt ();
77+ int [] a = new int [n ];
78+ System .out .println ("Enter " +n +" elements " );
79+ for ( i =0 ; i < n ; i ++)
80+ {
81+ a [i ] = s .nextInt ();
82+ }
83+
84+ System .out .println ( "elements in array " );
85+ printarray (a );
86+ Sort (a );
87+ System .out .println ( "\n elements after sorting" );
88+ printarray (a );
89+
90+ }
91+ }
You can’t perform that action at this time.
0 commit comments