/* DemoHeapSort.java CIS 260 David Klick 2016-03-24 This program demonstrates heapsort for an array of ints. */ public class DemoHeapSort { // Notes: // left child index = parent index * 2 + 1 // right child index = parent index * 2 + 2 private static void heapsort(int[] ar) { // Max-heapify array int len = ar.length; int lastHeapElement = len - 1; int lastElementWithAChild = (lastHeapElement - 1) / 2; for (int i=lastElementWithAChild; i>=0; i--) siftDown(ar, i, lastHeapElement); // Sort the array do { // Swap the largest item (root) with last item in heap swap(ar, 0, lastHeapElement); // Reduce the size of the heap by one lastHeapElement--; // Re-max-heapify what remains of the heap siftDown(ar, 0, lastHeapElement); } while (lastHeapElement > 0); } private static void swap(int[] ar, int pos1, int pos2) { // Swaps two array elements int temp = ar[pos1]; ar[pos1] = ar[pos2]; ar[pos2] = temp; } private static void siftDown(int[] ar, int parentNdx, int endOfHeap) { if (parentNdx == endOfHeap) return; // The max heap rule is that a parent must not be smaller // in value than either of its children. while (parentNdx <= (endOfHeap-1)/2) { // The parent has at least one child if we got here int leftChildNdx = parentNdx * 2 + 1; int rightChildNdx = parentNdx * 2 + 2; // Assume the left child is the largest child int largestChildNdx = leftChildNdx; // If there is a right child and it is larger, change largestChildNdx if (rightChildNdx <= endOfHeap && ar[rightChildNdx] > ar[leftChildNdx]) { largestChildNdx = rightChildNdx; } // Now see if parent is larger than largest child if (ar[largestChildNdx] > ar[parentNdx]) { // Child was larger, so swap and continue sifting swap(ar, parentNdx, largestChildNdx); parentNdx = largestChildNdx; } else { // Parent was the largest value, so sifting is done break; } } } private static void display(int[] ar) { // Displays an int array with 8 columns per number for (int n : ar) System.out.printf("%8d", n); System.out.println(); } private static boolean isSorted(int[] ar) { // Returns true if array is in ascending order // Returns false if array is not in ascending order for (int pos=0; pos ar[pos+1]) return false; } return true; } public static void main(String[] args) { // Create an array of random integers java.util.Random rnd = new java.util.Random(); int[] a = new int[10000000]; for (int i=0; i