#include <iostream>
#include <time.h>
#include <random>
using namespace std;
//Binary Heap; Max Heap;
class BinaryHeap
{
public:
BinaryHeap();
BinaryHeap(int capacity);
~BinaryHeap();
int insert(int value);
int getIndex(int value);
int removeRoot();
void print();
bool isEmpty();
private:
void sortUp(int start);
void sortDown(int start, int end);
int *heap;
int capacity;
int size ;
};
BinaryHeap::BinaryHeap()
{
this->size = ;
this->capacity = ;
heap = new int[this->capacity];
}
BinaryHeap::BinaryHeap(int capacity)
{
this->size = ;
this->capacity = capacity;
heap = new int[this->capacity];
}
BinaryHeap::~BinaryHeap()
{
this->size = ;
this->capacity = ;
delete[] heap;
}
int BinaryHeap::insert(int value)
{
if (this->size==this->capacity) //The heap is full
{
return -;
}
heap[this->size] = value;
this->sortUp(this->size);
this->size++;
return ;
}
int BinaryHeap::getIndex(int value)
{
for (int i = ; i < this->size; i++)
{
if (value==this->heap[i])
{
return i;
}
}
return -;
}
int BinaryHeap::removeRoot()
{
int index = ;
if (this->size==)
{
return ;//The heap is empty
}
this->heap[index] = this->heap[--this->size];
this->sortDown(index, this->size - );
return ;
}
void BinaryHeap::print()
{
for (int i = ; i < this->size; i++)
{
cout << "No." << i + << " : " << heap[i] << " " << endl;;
}
}
bool BinaryHeap::isEmpty()
{
if (this->size == )
{
return true;
}
else
{
return false;
}
}
void BinaryHeap::sortUp(int start)
{
int c = start; //The location of current node
int p = (c - ) / ; //The location of parent node
int temp = heap[c]; //The value of current node
while (c>)
{
if (heap[p] > temp)
{
break;
}
else
{
heap[c] = heap[p];
c = p;
p = (p - ) / ;
}
}
heap[c] = temp;
}
void BinaryHeap::sortDown(int start, int end)
{
int c=start; //the location of current node
int l = *c + ; //The location of left child
int temp = heap[c]; //The value of current node
while (l <= end)
{
if (l<end && heap[l]<heap[l+])
{
l++; //Choose the bigger one between left child and right child
}
if (temp>=heap[l])
{
break;
}
else
{
heap[c] = heap[l];
c = l;
l = * l + ;
}
}
heap[c] = temp;
}
int main()
{
BinaryHeap *b = new BinaryHeap();
default_random_engine random(time(NULL)); //C++ 11
uniform_int_distribution<int> num(, );//C++ 11
cout << "Insert 50 randon number which between 0~999 " << endl ;
for (int i = ; i <; i++)
{
b->insert(num(random));
}
cout << "Print: " << endl;
b->print();
cout << endl << endl;
cout << "Is the heap empty? " << endl;
cout << boolalpha << b->isEmpty() << endl << endl;
cout << "Remove" << endl;
switch (int n=b->removeRoot())
{
case :
cout << "Success! The root node has been removed!" << endl; break;
case :
cout << "Heap is empty! " << endl; break;
}
cout << endl;
cout << "Print: " << endl;
b->print();
system("pause");
return ;
}