C + + dynamic Array simple analog two-yuan heap

Source: Internet
Author: User

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

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.