C++ 实现堆
代碼如下(小根堆):
#include <iostream> #include <assert.h> using namespace std;//小根堆,堆排序從大到小排 class Heap { public:Heap():data(nullptr), size(0), capacity(0) {}~Heap(){delete[] data;data = nullptr;size = 0;capacity = 0;}/*void Swap(int *a, int *b){int tmp = *a;*a = *b;*b = tmp;}*/void ShiftDown(int n, int cur);void ShiftUp(int n, int cur);void CreateHeap(int *arr, int n);void CheckCapacity();void HeapSort();void HeapInsert(int value);void HeapPop();void HeapDestory(){delete[] data;data = nullptr;size = 0;capacity = 0;}int GetTop();bool HeapEmpty();void PrintHeap();private:int *data;int size;int capacity; };void Heap::ShiftDown(int n, int cur) {int child = 2 * cur + 1;while (child < n){if (child + 1 < n && data[child + 1] < data[child]) child++;if (data[child] < data[cur]){swap(data[child], data[cur]);cur = child;child = 2 * cur + 1;}else break;} }void Heap::ShiftUp(int n, int cur) {int parent = (cur - 1) / 2;while (cur > 0){if (data[parent] > data[cur]){swap(data[parent], data[cur]);cur = parent;parent = (cur - 1) / 2;}else break;} }void Heap::CheckCapacity() {if (capacity == size){int newC = capacity == 0 ? 1 : 2 * capacity;int *tmp = new int[newC];assert(tmp);for (int i = 0; i < size; i++) tmp[i] = data[i];delete[] data;data = tmp;tmp = nullptr;capacity = newC;} }void Heap::CreateHeap(int *arr, int n) {data = new int[n];for (int i = 0; i < n; i++) data[i] = arr[i];size = n;capacity = n;for (int i = (n - 2) / 2; i >= 0; i--)ShiftDown(n, i); }void Heap::HeapSort() {int end = size - 1;while (end > 0){swap(data[0], data[end]);ShiftDown(end, 0);end--;} }void Heap::HeapInsert(int value) {if (data != nullptr){CheckCapacity();data[size++] = value;ShiftUp(size, size - 1);} }void Heap::HeapPop() {if (data != nullptr &&size > 0){data[0] = data[--size];ShiftDown(size, 0);} }int Heap::GetTop() {return data[0]; }bool Heap::HeapEmpty() {if (data == nullptr || size == 0) return true;return false; }void Heap::PrintHeap() {if (data != nullptr){for (int i = 0; i < size; i++) cout << data[i] << " ";cout << endl;} }int main() {Heap h;int a[10] = { 23,445,1312,46,3252,12,42,12,53,13 };h.CreateHeap(a,10);h.HeapSort();h.PrintHeap();cout << h.GetTop() << endl;h.HeapPop();cout << h.GetTop() << endl;h.HeapInsert(1);cout << h.GetTop() << endl;h.HeapDestory();if (h.HeapEmpty()) cout << "empty" << endl;else cout << "not empty" << endl;return 0;}測試結果:
總結
- 上一篇: 儿童敏感期的各个阶段
- 下一篇: C++泛型编程实现二叉搜索树BST