C ++ dynamic array: simple binary heap simulation, array binary

Source: Internet
Author: User

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 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.