diff --git a/05-labHeapSort/Assignment.java b/05-labHeapSort/Assignment.java index 13af5ec..cc28b5c 100644 --- a/05-labHeapSort/Assignment.java +++ b/05-labHeapSort/Assignment.java @@ -4,20 +4,43 @@ import java.io.*; import java.util.*; public class Assignment { - public static int[] heapify(int[] heap, int sizeA, int index) { - // Fill in here + // check parent and children to find the largest node + int largest = index; + int left = 2 * index + 1; + int right = 2 * index + 2; + + if (left < sizeA && heap[left] > heap[largest]) largest = left; + if (right < sizeA && heap[right] > heap[largest]) largest = right; + + // if largest isn't the parent, swap with the largest child and recursively heapify + if (largest != index) { + final int tmp = heap[index]; + heap[index] = heap[largest]; + heap[largest] = tmp; + return heapify(heap, sizeA, largest); + } return heap; } public static int[] buildHeap(int[] arr, int sizeA) { - // Fill in here - return heapify(arr, sizeA, 1); + for (int i = sizeA / 2; i > 0; i--) { + heapify(arr, sizeA, i); + } + return heapify(arr, sizeA, 0); } public static int[] heapSort(int[] arr, int sizeA) { - // Fill in here - return buildHeap(arr, sizeA); + arr = buildHeap(arr, sizeA); + // for each element + for (int i = 1; i < sizeA; i++) { + // swap heap top (largest element) with the last array element and reheapify + int top = arr[0]; + arr[0] = arr[sizeA - i]; + arr[sizeA - i] = top; + arr = heapify(arr, sizeA - i, 0); + } + return arr; } public static void run(String inputPath) {