标签:
D叉堆不同的地方就是父节点和孩子节点在数组中的索引,C++代码,希望不要误人子弟。
#include <iostream> #include <vector> #include <algorithm> using namespace std; template <int D> //D叉堆 class Heap_t{ public: Heap_t(vector<int> &ptr, int hs); int Parent(int i){ return (i - 1) / D; } int Child(int i, int k){ return D*i + k + 1; } void Insert(int key); void Heap_Sort(); ~Heap_t() {} private: vector<int> &vp; //引用,进行原址操作 int heap_size; void Max_Heapify(int i); void Build_Heapify(){ for (int i = 1; i < heap_size;) } void Increase_Key(int i, int key); }; template <int D> Heap_t<D>::Heap_t(vector<int> &ptr, int hs) :vp(ptr){ heap_size = 0; if (hs >(int) ptr.size()) exit(0); for (int i = 0; i < hs; ++i) Insert(vp[i]); } template <int D> void Heap_t<D>::Max_Heapify(int i){ int largest = i; for (int k = 0; k < D; ++k){ int child = Child(i, k); if (child<heap_size&&vp[child]>vp[largest]){ largest = child; } } if (largest != i){ vp[i] = vp[i] ^ vp[largest]; vp[largest] = vp[i] ^ vp[largest]; vp[i] = vp[i] ^ vp[largest]; Max_Heapify(largest); } } template <int D> void Heap_t<D>::Increase_Key(int i, int key){ if (key < vp[i]) { cout << "new key is smaller than current key"; return; } while (i > 0 && vp[Parent(i)] < key){ vp[i] = vp[Parent(i)]; i = Parent(i); } vp[i] = key; } template <int D> void Heap_t<D>::Insert(int key){ if (heap_size == vp.size()) vp.push_back(INT_MIN); else vp[heap_size] = INT_MIN; Increase_Key(heap_size, key); ++heap_size; } template <int D> void Heap_t<D>::Heap_Sort(){ for (; heap_size > 0; ){ swap(vp[0], vp[heap_size-1]); --heap_size; Max_Heapify(0); } } int main(){ vector<int> vec = { 1, 12, 8, 11, 5, 4, 3, 5, 66, 2, 1, 1, 3, 4, 45, 2 }; Heap_t<5> maxh(vec,vec.size()); for (auto r : vec) cout << r<<" "; cout << endl; maxh.Heap_Sort(); for (auto r : vec) cout << r << " "; }
标签:
原文地址:http://www.cnblogs.com/Nastukashii/p/4394640.html