/***************************** Complexity:
***************************/ #include <iostream> #include <assert.h> #include < vector> #include <stdlib.h> #include <time.h>using namespace std; #define N 1000 #define k 100void adjustdown (Int *a, size_t root, size_t size) { //down adjustment small heap size_t parent = root; size_t child = parent * 2 + 1; while (child < size) { if (Child + 1 < size && a[child] > a[child &NBSP;+&NBSP;1]) { ++child; } if&nBSP; (A[parent] > a[child]) { swap (A[parent], a[child]); parent = child; child = parent * 2 + 1; } else//pay attention to not meet the exchange conditions when jumping out of this cycle { &NBSP;BREAK;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;}}VOID&NBSP;GETTOPK (const &NBSP;VECTOR<INT>&&NBSP;VNUMBER,&NBSP;INT&NBSP;N,&NBSP;INT&NBSP;K) The maximum number of//n in the number of first K--small heap implementation { assert (n>k); int *topkarray = new int[k];// Build a heap with k elements through the first k elements for (size_t i = 0; i < k; i++) { topkarray[i] = vnumber[i]; } for (int i = (k - 2) / 2; i >= &NBSP;0;&NBSP;--I)//Build small heap { adjustdown ( topkarray, i, k); } //from the beginning of the K element to the nth element, respectively, compared to the top element of the heap, Large data into the heap top, and then down the entire heap, so that the top of the heap to store the smallest elements (small heap) for (size_t i = k; i < n; ++i) { if (Vnumber[i] > topkarray[0]) { TopkArray[0] = Vnumber[i]; &Nbsp; adjustdown (topkarray, 0, k); } } size_t count = 0; for ( size_t i = 0; i < k; ++i)//print K maximum data, that is, all elements in the heap { cout << TopkArray[i] << " "; ++count; if (count % 10 == 0) { cout << endl; } } cout << endl; delete[] topkarray;//pay attention to releasing Topkarray memory topkarray = null;} Void createVnumber (Vector<int>& vnumber)//create n number { srand (unsigned int) Time (NULL ); //srand (Time (0)); vnumber.reserve (N); for (size_t i = 0; i<n; i++) { vnumber.push_back (rand () % 1000);//generates n random values } for (size_t i = k; i < n; ++i) { Vnumber[i] *= 100; }}int main () { vector<int> vnumber; Createvnumber (Vnumber); &NBSP;&NBSP;&NBSP;&NBSP;GETTOPK (vnumber, n, k); //int length = vnumber.size (); //for (int i=0;i<length;i++) //{ // cout<<vnumber[i]<< " "; // } return 0;}
Small code looking for K-max number