This problem is also a more famous face test. Of course there are many variants.
The main meaning of the topic is: to find the top n elements from a large array of data. Sorting is not allowed.
There are two better ideas for this problem:
Idea one: With a quick sort of thought, is thought, not to sort;
Idea two: Use the maximum heap of thought.
I temporarily only realized the idea of one, thinking two I realized after the will fill up.
The idea is relatively simple. We first use the idea of a fast line to find the nth number, and then take the back n-1, and then we're done. Because the back is bigger than the fulcrum number.
How to find the number of the nth large? I wrote on the previous blog, please go to find the nth number
Code:
#include <stdio.h>#include<stdlib.h>/*to find the subscript of the nth large number*/intChoose_nth (intA[],intStartIndex,intEndIndex,intn);/*find the first n large number*/voidChoose_max_n (intA[],intStartIndex,intEndIndex,intn);intMainintargcChar*argv) { intA[] = {1,4,111, +, $, +, About, -,8, A,189}; intN,i; printf ("the array is: \ n"); intan =sizeof(a)/sizeof(int); for(i =0; I < an; ++i) printf ("%d", A[i]); printf ("\ n"); printf ("you want to find the largest number in the front:"); scanf ("%d",&N); Choose_max_n (A,0, An-1, N); return 0;}voidChoose_max_n (intA[],intStartIndex,intEndIndex,intN) { inti =Choose_nth (A, StartIndex, EndIndex, N); printf ("the largest number of top n is: \ n"); for(; I <= endIndex; + +)i) printf ("%d", A[i]); printf ("\ n");}intChoose_nth (intA[],intStartIndex,intEndIndex,intN) { intMidone =A[startindex]; inti = startIndex, j =EndIndex; if(i = =j)returni; if(I <j) { while(I <j) { for(; i < J; j--) if(A[j] <Midone) {A[i++] =A[j]; Break; } for(; i < J; i++) if(A[i] >Midone) {A[j--] =A[i]; Break; }} A[i]=Midone; intth = Endindex-i +1; if(th = =N) {returni; } Else { if(Th >N) {returnChoose_nth (A, i +1, EndIndex, N); } Else { returnChoose_nth (A, startIndex, I-1Nth); } } }}
Results:
the array is: 1 4 111 + $ + About - 8 A 189 you want to find the largest number in the front: 5 the largest number of top N is: About 111 - + 189
It will then make up the code that uses the largest heap of ideas.
Find the first n large number of arrays