1. Calculate the maximum K number for an array without order 1) Stupid method. First, sort the array in quick order before finding the first K; 2) use a heap to create a K-small top heap first, scan the entire array and set the heap to the minimum number of K;
/************************************/// Find the maximum number of K in the array // insert void constructheap (int A [], int N, int value) {A [n] = value; Int J, temp = value; j = (n-1)/2; while (j> = 0 & n! = 0) {if (a [J] <= temp) break; A [n] = A [J]; n = J; j = (n-1)/2 ;} A [n] = temp;} // heap update void updataheap (int A [], int index, int N) {Int J, temp = A [Index]; j = 2 * index + 1; while (j <n) {If (J + 1 <n & A [J + 1] <A [J]) + + J; if (A [J]> = temp) break; A [Index] = A [J]; Index = J; j = Index * 2 + 1 ;} A [Index] = temp;} void maxk (int A [], int N, int K) {int I; int * temp = new int [k]; for (I = 0; I <n; ++ I) {if (I <k) constructheap (temp, I, a [I]); // first construct K heap else {If (temp [0] <A [I]) {temp [0] = A [I]; updataheap (temp, 0, k ); // update the K heap. }}for (I = 0; I <K; ++ I) {cout <temp [I] <"";} delete [] temp ;}
2. Calculate the K maximum number http://www.cnblogs.com/ywl925/p/3794852.html of N descending Arrays
1. Create a large top heap with the number of arrays in the dimension. Here it is 20 (the first inserted is the maximum value in each array, that is, the first element ).
2. Delete the maximum heap top, save it to an array or stack, and insert the next element of the array where the deleted element is located to the maximum heap.
3. Repeat Step 1 and Step 2 until the maximum number of K Records is deleted, which is 500.
/************************************/// N descending arrays, find the maximum K count // The top heap void constructheap1 (int A [], int N, int value) {A [n] = value; Int J, temp = value; j = (n-1)/2; while (j> = 0 & n! = 0) {if (a [J]> = temp) break; A [n] = A [J]; n = J; j = (n-1)/2 ;} A [n] = temp;} // heap update void updataheap1 (int A [], int index, int N) {Int J, temp = A [Index]; j = 2 * index + 1; while (j <n) {If (J + 1 <n & A [J + 1]> A [J]) + + J; if (A [J] <= temp) break; A [Index] = A [J]; Index = J; j = Index * 2 + 1 ;} A [Index] = temp;} void getmaxk () {const int rows = 20; const int Cols = 500; const int K = 500; int data [rows] [Cols]; int result [k]; // The first 500int heap [20]; // heap int I, j; for (I = 0; I <rows; ++ I) {for (j = 0; j <Cols; ++ J) {data [I] [J] = rand () ;}// Quick Sort for (I = 0; I <rows; ++ I) {quiksortdown (data [I], 0, cols-1) ;}// start for (j = 0; j <Cols; ++ J) {for (I = 0; I <rows; ++ I) {If (0 = J) constructheap1 (heap, I, data [I] [0]); // create heap else {If (J-1) * Rows + I> K-1) break; Result [(J-1) * Rows + I] = heap [0]; heap [0] = data [I] [J]; updataheap1 (heap, 0, 20 ); // update heap }}for (I = 0; I <K; ++ I) {cout <result [I] <"" <Endl ;}}
Evaluate the maximum K Number of arrays (heap Application)