Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Heap
- {
- static const int SIZE = 100;
- int* h;
- int HeapSize;
- public:
- Heap();
- void siftup();
- void siftdown(int);
- void add(int);
- void delete_vertex(int);
- bool isempty();
- int* get_head();
- void out();
- };
- Heap::Heap()
- {
- h = new int[SIZE];
- HeapSize = 0;
- }
- int* Heap::get_head()
- {
- return &h[0];
- }
- bool Heap::isempty()
- {
- if (HeapSize == 0)
- return true;
- return false;
- }
- void Heap::siftup()
- {
- int curr, parent;
- curr = HeapSize - 1;
- parent = (curr - 1) / 2;
- while (parent >= 0 && curr > 0)
- {
- if (h[parent] < h[curr])
- {
- int buff = h[curr];
- h[curr] = h[parent];
- h[parent] = buff;
- }
- curr = parent;
- parent = (curr - 1) / 2;
- }
- }
- void Heap::siftdown(int position)
- {
- int parent, max_child;
- int curr = position;
- int child_l = 2 * curr + 1;
- int child_r = 2 * curr + 2;
- if (h[child_r] < h[child_l])
- max_child = child_l;
- else
- max_child = child_r;
- while (child_l < HeapSize)
- {
- if (child_l == HeapSize - 1)
- max_child = child_l;
- else if (h[child_r] < h[child_l])
- max_child = child_l;
- else
- max_child = child_r;
- if (h[curr] < h[max_child])
- {
- int buff = h[curr];
- h[curr] = h[max_child];
- h[max_child] = buff;
- }
- curr = max_child;
- child_l = 2 * curr + 1;
- child_r = 2 * curr + 2;
- }
- }
- void Heap::add(int vertex)
- {
- h[HeapSize] = vertex;
- HeapSize++;
- siftup();
- }
- void Heap::delete_vertex(int position)
- {
- h[position] = h[HeapSize - 1];
- HeapSize--;
- siftdown(position);
- }
- void Heap::out(void)
- {
- for (int i = 0; i < HeapSize; i++)
- {
- std::cout <<<< h[i] << "" ";
- }
- std::cout << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment