日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ 实现堆

發布時間:2023/12/4 c/c++ 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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++ 实现堆的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。