static void add2Heap(Heap* heap, int newVal) { if (heap->size < heap->capacity) { heap->h[heap->size++] = newVal; if (heap->size == heap->capacity) { int i; for (i = ((heap->size - 1) >> 1); i >= 0; i--) { fixHeap(heap->h, i, heap->size); } }
//////////////////////////////////////////////////////////////////// // Iteratively fixes the heap from bottom-up, starting with the // parent of the last leaf node //////////////////////////////////////////////////////////////////// void HeapSort::heapify() { if (size <= 1) return; // start from the parent of the last leaf and // fix all the way up int i = size / 2 - 1; for (; i >= 0; i--) { fixHeap(i, size - 1); } }
//////////////////////////////////////////////////////////////////// // Performs the heapsort //////////////////////////////////////////////////////////////////// int* HeapSort::sort() { cloneOver(); // reset resArr // construct a heap heapify(); // perform the sort int i, temp; for (i = size - 1; i > 0; i--) { // swap node 0 (root) with the node (i) swap(&resArr[0], &resArr[i]); // fix the heap up until immediately before node (i) fixHeap(0, i-1); } return resArr; }