cis22c/07-heaps/main.cpp
Iurii Tatishchev 0789614ef1
10.9 Lab: Heap - Build min/max-heaps (of integers)
Generalize one of the previous labs to build a min-heap or a max-heap using the same heap functions. In main() pass either compareMin or compareMax to the insertHeap function:

- minHeap.insertHeap(num, compareMin);
- maxHeap.insertHeap(num, compareMax);

You also have to update the following functions of the Heap class:

- bool insertHeap(int itemIn);
- bool deleteHeap(int &itemOut);
- void _reHeapUp(int lastndx);
- void _reHeapDown(int rootndx);

This program will:

- read integers from the keyboard and insert them into a min-heap and a max-heap
- display the integers as they are deleted from the min-heap.
- display the integers as they are deleted from the max-heap.
2024-05-28 19:21:43 -07:00

75 lines
1.6 KiB
C++

/*
This program will
- read integers from the keyboard and insert them into a min-heap and a max-heap
- display the integers as they are deleted from the min-heap.
- display the integers as they are deleted from the max-heap.
Written By: Iurii Tatishchev
Changed by: Iurii Tatishchev
IDE: CLion
*/
#include <iostream>
#include "Heap.h"
using namespace std;
int compareMin(int, int);
int compareMax(int, int);
int main() {
Heap minHeap(32);
Heap maxHeap(32);
// build min- and max-heaps
int num;
cout << "Enter integers [0 - to stop]" << endl;
cin >> num;
while (num != 0) {
minHeap.insertHeap(num, compareMin);
maxHeap.insertHeap(num, compareMax);
cin >> num;
}
// print items as they are deleted from the min-heap (sorted in ascending order)
cout << "Min-Heap: ";
while (!minHeap.isEmpty()) {
minHeap.deleteHeap(num, compareMin);
cout << num << " ";
}
cout << endl;
// print items as they are deleted from the heap (sorted in descending order)
cout << "Max-Heap: ";
while (!maxHeap.isEmpty()) {
maxHeap.deleteHeap(num, compareMax);
cout << num << " ";
}
cout << endl;
return 0;
}
/*
compare two data items: needed to build a min-heap
*/
int compareMin(int x, int y) {
if (x < y)
return -1;
if (x == y)
return 0;
return 1;
}
/*
compare two data items: needed to build a max-heap
*/
int compareMax(int x, int y) {
if (x > y)
return -1;
if (x == y)
return 0;
return 1;
}