1
+ public class HeapSort {
2
+ public void sort (int arr [])
3
+ {
4
+ int N = arr .length ;
5
+
6
+ // Build heap (rearrange array)
7
+ for (int i = N / 2 - 1 ; i >= 0 ; i --)
8
+ heapify (arr , N , i );
9
+
10
+ // One by one extract an element from heap
11
+ for (int i = N - 1 ; i > 0 ; i --) {
12
+ // Move current root to end
13
+ int temp = arr [0 ];
14
+ arr [0 ] = arr [i ];
15
+ arr [i ] = temp ;
16
+
17
+ // call max heapify on the reduced heap
18
+ heapify (arr , i , 0 );
19
+ }
20
+ }
21
+
22
+ // To heapify a subtree rooted with node i which is
23
+ // an index in arr[]. n is size of heap
24
+ void heapify (int arr [], int N , int i )
25
+ {
26
+ int largest = i ; // Initialize largest as root
27
+ int l = 2 * i + 1 ; // left = 2*i + 1
28
+ int r = 2 * i + 2 ; // right = 2*i + 2
29
+
30
+ // If left child is larger than root
31
+ if (l < N && arr [l ] > arr [largest ])
32
+ largest = l ;
33
+
34
+ // If right child is larger than largest so far
35
+ if (r < N && arr [r ] > arr [largest ])
36
+ largest = r ;
37
+
38
+ // If largest is not root
39
+ if (largest != i ) {
40
+ int swap = arr [i ];
41
+ arr [i ] = arr [largest ];
42
+ arr [largest ] = swap ;
43
+
44
+ // Recursively heapify the affected sub-tree
45
+ heapify (arr , N , largest );
46
+ }
47
+ }
48
+
49
+ /* A utility function to print array of size n */
50
+ static void printArray (int arr [])
51
+ {
52
+ int N = arr .length ;
53
+
54
+ for (int i = 0 ; i < N ; ++i )
55
+ System .out .print (arr [i ] + " " );
56
+ System .out .println ();
57
+ }
58
+
59
+ // Driver's code
60
+ public static void main (String args [])
61
+ {
62
+ int arr [] = { 12 , 11 , 13 , 5 , 6 , 7 };
63
+ int N = arr .length ;
64
+
65
+ // Function call
66
+ HeapSort ob = new HeapSort ();
67
+ ob .sort (arr );
68
+
69
+ System .out .println ("Sorted array is" );
70
+ printArray (arr );
71
+ }
72
+ }
0 commit comments