94 lines
1.7 KiB
C++
94 lines
1.7 KiB
C++
#include <iostream>
|
|
#include <iomanip>
|
|
|
|
using string = std::string;
|
|
|
|
//Place in header!
|
|
template <typename T>
|
|
void printm(T m){
|
|
std::cout << m;
|
|
}
|
|
|
|
template <typename T>
|
|
void printlm(T m){
|
|
printm(m);
|
|
printm("\n");
|
|
}
|
|
|
|
class Heap {
|
|
int pos {0};
|
|
int length {0};
|
|
int size;
|
|
int* storage;
|
|
public:
|
|
Heap(int sz) {
|
|
size = sz;
|
|
storage = new int[sz];
|
|
}
|
|
~Heap() {
|
|
delete[] storage;
|
|
}
|
|
bool isEmpty() {
|
|
return length == 0;
|
|
}
|
|
void add(int item) {
|
|
if (length + 1 > size) return;
|
|
pos = length;
|
|
while (pos > 0 && storage[(pos-1)/2] < item) {
|
|
storage[pos] = storage[(pos-1)/2];
|
|
pos = (pos-1)/2;
|
|
}
|
|
storage[pos] = item;
|
|
++length;
|
|
}
|
|
int extractMax() {
|
|
int max {storage[0]};
|
|
storage[0] = storage[--length];
|
|
int first {0};
|
|
while ((2*first)+1 <= length - 1) {
|
|
int largest {(2*first)+1};
|
|
if ((2*first)+2 <= length - 1 && storage[largest] < storage[(2*first)+2]) largest = (2*first)+2;
|
|
if (storage[first] >= storage[largest]) break;
|
|
int swap = storage[first];
|
|
storage[first] = storage[largest];
|
|
storage[largest] = swap;
|
|
first = largest;
|
|
}
|
|
return max;
|
|
}
|
|
};
|
|
|
|
int prompti(string,bool*);
|
|
|
|
int main() {
|
|
printlm("Create Heap:");
|
|
Heap h{16};
|
|
bool s {};
|
|
int i {0};
|
|
do {
|
|
auto d = prompti("Enter a number: ",&s);
|
|
if (s) {
|
|
h.add(d);
|
|
++i;
|
|
}
|
|
}
|
|
while(s && i < 16);
|
|
printlm("Output Heap:");
|
|
while (!h.isEmpty()) printlm(h.extractMax());
|
|
return 0;
|
|
}
|
|
|
|
int prompti(string message, bool *status) {
|
|
int tr {};
|
|
*status = false;
|
|
std::cout << message;
|
|
if (!(std::cin >> tr)){
|
|
std::cin.clear();
|
|
std::cin.ignore();
|
|
return 0;
|
|
}
|
|
*status = true;
|
|
return tr;
|
|
}
|
|
|