Finds the number of K in an array
Problem:
Finds the number of K-large in a given array. For example [3,2,7,1,8,9,6,5,4], the 1th largest number is 9, the 2nd largest number is 8 ...
Ideas:
1. Directly from the big to the small sort, after the order, the number of k large is arr[k-1].
2. Simply find the number of K-large and do not order all the numbers. We use the quick sort to partition the process, in general, before the order of all the numbers, you can find the number K. We are based on the logic that after a partition, the array is divided into two parts: s left, S right. Number of elements when s left | When S left | equals k-1, Pivot is the number to be searched; S left | Less than k-1, the number found is in s right; when | s left |>k-1, the number found in the s left. Obviously, the latter two situations will reduce the search space.
Code:
intPartition (int*arr,intFromint to){intI, J; i = j = from; while(J <= to) {if(Arr[j] >= arr[ to]) {intTMP = Arr[i]; Arr[i] = Arr[j]; ARR[J] = tmp; i++; } j + +; } return I-1;}intQuickselect (int*s,intKint Left,int Right){if( Left== Right) Return s[ Left];intI i = Partition (s, Left, Right);ifI Left+1= = k) {return s[i]; }Else ifI Left+1< K) {return Quickselect (S, K-(I- Left+1), I +1, Right); }ElseReturn Quickselect (S, K, LeftI1);}intFindkthlargest (int* Nums,intNumssize,intk) {return Quickselect (Nums, K,0, Numssize-1);}
As for "Finding the small number of K in an array", it can naturally be extrapolate and treated as well.
Code Download: Find the number of the K-large in the array
Directory of all content
Challenge Interview Programming: Finding the number of K in an array