I have written this program to sort an array using heap sort. Please review it for further improvements.
public static void main(String[] args) {
int arr[] = {14, 70, 51, 16};
System.out.println("Input Array : " + Arrays.toString(arr));
buildMaxHeap(arr, arr.length);
System.out.println("Max Heap Order : " + Arrays.toString(arr));
heapSort(arr);
System.out.println("Sorted Array : " + Arrays.toString(arr));
}
private static void buildMaxHeap(int[] arr, int len) {
// any nodes after n/2 are leaves node and could be without children
for (int i = (len) / 2; i >= 0; i--) {
// bubble up to build max heap
bubbleUp(arr, i, len - 1);
}
}
private static void heapSort(int[] arr) {
// now run the sort process
for (int j = arr.length - 1; j >= 0;) {
// bubble up the nodes so that tree can satisfy the max heap
// property
// i.e any Node B <= to its Parent Node A.
// This swap method will shift lower to down and higher to up.
swap(arr, j, 0);
// decrement the size of heap so that previous max value stays in
// place
j = j - 1;
// now bubble up again from 0 to (heap -1) j
// means put the heap back.
bubbleUp(arr, 0, j);
System.out.println("Sorted Array : " + Arrays.toString(arr));
}
}
private static void bubbleUp(int[] arr, int start, int end) {
// set the root to start
int root = start;
while ((root * 2) + 1 <= end) { // root should have atleast one child
int child = (root * 2 + 1); // point to left child
// if child has siblings and left child is less than sibling
if (child + 1 <= end && arr[child] <= arr[child + 1]) {
child = child + 1; // make this child right child
}
// if root is less than child (could be left | right) then bubble up
if (arr[root] < arr[child]) {
// swap the node with max value child node
swap(arr, root, child);
// set the root to the child level, so that subtrees if any
// could be shift
root = child;
} else {
root++; // make it bigger to exit out the loop
// return; // return if root node is greator than child node.
}
}
}
private static void swap(int[] arr, int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}