#ifndef _HEAP_H #define _HEAP_H #include "Array.h" template class Heap { struct Pair { DATA d; KEY k; }; Array heap; int n; int parent(int i) { return (i+1)/2 - 1; } int left_child(int i) { return 2*i + 1; }; int right_child(int i) { return 2*i + 2; }; void swap(int i, int j) { if (i == j) return; Pair tmp = heap[i]; heap[i] = heap[j]; heap[j] = tmp; } public: Heap() : n(0) {}; ~Heap() {}; bool empty() { return n==0; } bool size() { return n; } void insert(DATA D, KEY K) { int i = n++; heap[i].d = D; heap[i].k = K; while (i != 0 && heap[i].k < heap[parent(i)].k) { swap(i, parent(i)); i = parent(i); } } void delete_min(DATA&D, KEY& K) { if (empty()) die("Heap::delete_min called on empty heap"); D = heap[0].d; K = heap[0].k; --n; swap(0, n); int i = 0; while (1) { int left = left_child(i); int right = right_child(i); int min = i; if (left < n && heap[left].k < heap[min].k) { min = left; } if (right < n && heap[right].k < heap[min].k) { min = right; } if (min == i) break; swap(i, min); i = min; } } void clear() { heap.clear(); n = 0; } }; #endif