|
| 1 | + |
| 2 | + |
| 3 | +public class HeapSort { |
| 4 | + |
| 5 | + |
| 6 | + void heapify(int arr[], int n, int i) { |
| 7 | + int max = i; //Initialize max as root |
| 8 | + int leftChild = 2 * i + 1; |
| 9 | + int rightChild = 2 * i + 2; |
| 10 | + |
| 11 | + //If left child is greater than root |
| 12 | + if (leftChild < n && arr[leftChild] > arr[max]) |
| 13 | + max = leftChild; |
| 14 | + |
| 15 | + //If right child is greater than max |
| 16 | + if (rightChild < n && arr[rightChild] > arr[max]) |
| 17 | + max = rightChild; |
| 18 | + |
| 19 | + //If max is not root |
| 20 | + if (max != i) { |
| 21 | + int swap = arr[i]; |
| 22 | + arr[i] = arr[max]; |
| 23 | + arr[max] = swap; |
| 24 | + |
| 25 | + //heapify the affected sub-tree recursively |
| 26 | + heapify(arr, n, max); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public void sort(int arr[]) { |
| 31 | + int n = arr.length; |
| 32 | + |
| 33 | + //Rearrange array (building heap) |
| 34 | + for (int i = n / 2 - 1; i >= 0; i--) { |
| 35 | + heapify(arr, n, i); |
| 36 | + } |
| 37 | + |
| 38 | + //Extract elements from heap one by one |
| 39 | + for (int i = n - 1; i >= 0; i--) { |
| 40 | + //Current root moved to the end |
| 41 | + int tmp = arr[0]; |
| 42 | + arr[0] = arr[i]; |
| 43 | + arr[i] = tmp; |
| 44 | + //calling max heapify on the heap reduced |
| 45 | + heapify(arr, i, 0); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + |
| 50 | + //print size of array n using utility function |
| 51 | + static void display(int arr[]) { |
| 52 | + int n = arr.length; |
| 53 | + for (int i = 0; i < n; ++i) |
| 54 | + System.out.print(arr[i] + " "); |
| 55 | + System.out.println(); |
| 56 | + } |
| 57 | + |
| 58 | + //Driver code |
| 59 | + public static void main(String args[]) { |
| 60 | + int arr[] = {11, 34, 9, 5, 16, 10}; |
| 61 | + |
| 62 | + HeapSort hs = new HeapSort(); |
| 63 | + System.out.println("Original array:"); |
| 64 | + display(arr); |
| 65 | + hs.sort(arr); |
| 66 | + |
| 67 | + System.out.println("Sorted array:"); |
| 68 | + display(arr); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + |
0 commit comments