C + + dynamic Array simple analog two-yuan heap #include<iostream>using namespace Std;class binaryheap{private:int cap; The maximum capacity of the array is int size; The current number of elements int* datas; Array first address public:explicit binaryheap (int cap_): Cap (CAP_), size (0) {datas = new Int[cap];} ~binaryheap () {delete datas;} void Insert (int); int deletemin ();};/ /The tree represented by an array, when the current label starts from 0, I is the present node, I*2+1 is the left subtree node of I, i*2+2 is the right subtree node of I, I/2 is the parent of I, void Binaryheap::insert (int data) {int i;for (i = size; I/2 >= 0 && DATAS[I/2] > data; I/= 2)//on filter {datas[i] = DATAS[I/2];} Datas[i] = data;size++;} int binaryheap::D eletemin () {int i = 0, child = 0;int Lastdata = Datas[--size];int Mindata = datas[0];for (i = 0; I * 2 + 1) <= size-1; i = child)//down filter {child = i * 2 + 1;if (Child < size-1 && Datas[child + 1] < Datas[child]) {child++;} if (Lastdata > Datas[child]) {datas[i] = Datas[child];} Else{break;}} Datas[i] = Lastdata;return mindata;} int main () {Binaryheap T (+), for (int i = 0; i <; i++) T.insert (i), for (int i = n, i > i--) t.insert (i); for (int i = 0; I < 200; i++) cout << t.deletemin () << endl;cin.get (); return 0;}
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
C + + dynamic Array simple analog two-yuan heap