C ++ dynamic array: simple binary heap simulation, array binary
// The C ++ dynamic array simulates binary heap # include <iostream> using namespace std; class BinaryHeap {private: int cap; // The maximum size of the array int size; // The number of current elements int * datas; // The first address of the array public: explicit BinaryHeap (int cap _): cap (cap _), size (0) {datas = new int [cap] ;}~ BinaryHeap () {delete datas;} void Insert (int); int DeleteMin () ;}; // Tree represented by an array. When the subscript starts from 0, I is the current node, I * 2 + 1 is the left subtree node of I, And I * 2 + 2 is the right subtree node of I, void BinaryHeap: Insert (int data) {int I; for (I = size; i/2> = 0 & datas [I/2]> data; I/= 2) // filter {datas [I] = datas [I/2];} datas [I] = data; size ++;} int BinaryHeap: DeleteMin () {int I = 0, child = 0; int lastdata = datas [-- size]; int mindata = datas [0]; for (I = 0; I * 2 + 1 <= size-1; I = child) // downstream 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 (400); for (int I = 0; I <100; I ++) t. insert (I); for (int I = 200; I> 100; I --) t. insert (I); for (int I = 0; I <200; I ++) cout <t. deleteMin () <endl; cin. get (); return 0 ;}