做online judge的时候用到了最大堆,自己实现了一个。主要参考算法导论中的设计思路。
#include <iostream> using namespace std; const int MAX_LEN = 100; class MaxHeap { private: int heap[MAX_LEN]; int len; inline int parent(int i){ return i / 2; }; inline int left(int i){ return i * 2; }; inline int right(int i){ return i * 2 + 1; }; void heapify(int i); void build(int *arr, int n); public: MaxHeap(); MaxHeap(int *arr, int n); inline int length(){ return len; }; inline int max(){ return heap[1]; }; void print(); int extractMax(); void increaseKey(int i, int key); void insert(int key); }; MaxHeap::MaxHeap(){ len = 0; memset(heap, 0, MAX_LEN); } MaxHeap::MaxHeap(int *arr, int n){ len = n; memset(heap, 0, MAX_LEN); build(arr, n); } void MaxHeap::heapify(int i){ int l = left(i); int r = right(i); int largest = i; if (l <= len&&heap[l] > heap[largest]) largest = l; if (r <= len&&heap[r] > heap[largest]) largest = r; if (largest != i){ swap(heap[i], heap[largest]); heapify(largest); } } void MaxHeap::build(int *arr, int n){ for (int i = 0; i < n; i++) heap[i + 1] = arr[i]; for (int i = len / 2; i >= 1; i--) heapify(i); } int MaxHeap::extractMax(){ if (len < 1){ cout << "Error. Returning -1." << endl; return -1; } int max = heap[1]; heap[1] = heap[len]; len--; heapify(1); return max; } void MaxHeap::print(){ for (int i = 1; i <= len; i++) cout << heap[i] << endl; } void MaxHeap::increaseKey(int i, int key){ if (key < heap[i]){ cout << "New key is smaller than current key." << endl; return; } heap[i] = key; while (i > 1 && heap[parent(i)] < heap[i]){ swap(heap[parent(i)], heap[i]); i = parent(i); } } void MaxHeap::insert(int key){ len++; heap[len] = INT_MIN; increaseKey(len, key); } int main() { int num[10] = { 4, 1, 6, 2, 9, 7, 3, 8, 5, 0 }; MaxHeap max_heap(num, 10); max_heap.print(); return 0; }