10.7 Lab: Heap - Build a min-heap (of integers)

Change the previous lab to work with a min-heap instead of a max-heap.
This commit is contained in:
Iurii Tatishchev 2024-05-28 18:41:58 -07:00
parent 0ca7ce28fd
commit eb1cf4176f
Signed by: CaZzzer
GPG Key ID: 9A156B7DA6398968
2 changed files with 7 additions and 7 deletions

View File

@ -18,8 +18,8 @@ void Heap::_reHeapUp(int lastndx) {
if (lastndx == 0) return;
int parentIndex = _findParent(lastndx);
// base case, newElement satisfies heap property (child not greater than parent)
if (heapAry[lastndx] <= heapAry[parentIndex]) return;
// base case, newElement satisfies heap property (child not less than parent)
if (heapAry[lastndx] >= heapAry[parentIndex]) return;
// swap and continue recursing
std::swap(heapAry[lastndx], heapAry[parentIndex]);
@ -38,13 +38,13 @@ void Heap::_reHeapDown(int rootdex) {
// if there is a left child
if (left != -1) {
// if there is a right child that is greater than the left child
if (right != -1 && heapAry[right] > heapAry[left]) maxChildIndex = right;
// if there is a right child that is less than the left child
if (right != -1 && heapAry[right] < heapAry[left]) maxChildIndex = right;
else maxChildIndex = left;
}
// base case, heap property satisfied (children less than parent)
if (maxChildIndex == -1 || heapAry[rootdex] > heapAry[maxChildIndex]) return;
// base case, heap property satisfied (children greater than parent)
if (maxChildIndex == -1 || heapAry[rootdex] < heapAry[maxChildIndex]) return;
// swap and continue recursing
std::swap(heapAry[rootdex], heapAry[maxChildIndex]);

View File

@ -1,6 +1,6 @@
/*
This program will read integers from the keyboard,
insert them into a max-heap, and display them as
insert them into a min-heap, and display them as
they are deleted from the heap.
*/