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