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:
parent
0ca7ce28fd
commit
eb1cf4176f
@ -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]);
|
||||
|
@ -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.
|
||||
*/
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user