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;
|
if (lastndx == 0) return;
|
||||||
|
|
||||||
int parentIndex = _findParent(lastndx);
|
int parentIndex = _findParent(lastndx);
|
||||||
// base case, newElement satisfies heap property (child not greater than parent)
|
// base case, newElement satisfies heap property (child not less than parent)
|
||||||
if (heapAry[lastndx] <= heapAry[parentIndex]) return;
|
if (heapAry[lastndx] >= heapAry[parentIndex]) return;
|
||||||
|
|
||||||
// swap and continue recursing
|
// swap and continue recursing
|
||||||
std::swap(heapAry[lastndx], heapAry[parentIndex]);
|
std::swap(heapAry[lastndx], heapAry[parentIndex]);
|
||||||
@ -38,13 +38,13 @@ void Heap::_reHeapDown(int rootdex) {
|
|||||||
|
|
||||||
// if there is a left child
|
// if there is a left child
|
||||||
if (left != -1) {
|
if (left != -1) {
|
||||||
// if there is a right child that is greater than the left child
|
// if there is a right child that is less than the left child
|
||||||
if (right != -1 && heapAry[right] > heapAry[left]) maxChildIndex = right;
|
if (right != -1 && heapAry[right] < heapAry[left]) maxChildIndex = right;
|
||||||
else maxChildIndex = left;
|
else maxChildIndex = left;
|
||||||
}
|
}
|
||||||
|
|
||||||
// base case, heap property satisfied (children less than parent)
|
// base case, heap property satisfied (children greater than parent)
|
||||||
if (maxChildIndex == -1 || heapAry[rootdex] > heapAry[maxChildIndex]) return;
|
if (maxChildIndex == -1 || heapAry[rootdex] < heapAry[maxChildIndex]) return;
|
||||||
|
|
||||||
// swap and continue recursing
|
// swap and continue recursing
|
||||||
std::swap(heapAry[rootdex], heapAry[maxChildIndex]);
|
std::swap(heapAry[rootdex], heapAry[maxChildIndex]);
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
/*
|
/*
|
||||||
This program will read integers from the keyboard,
|
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.
|
they are deleted from the heap.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user