As an extended application for quick sorting, here is a question about choosing the K-min element.
1. Description of the problem
Given the n elements in a linear sequence and an integer k, 0<=k<n, it is required to find the nth element of this n element.
2. Solution method
2.1 Direct sorting
Using the quick sort and then selecting the K element, the time complexity required is O (N*LOGN).
2.2 Solving "divide-and-conquer method" with the idea of quick sorting
In the quick sort we use the partition method to find the middle element each time, can ensure that the left element is smaller than it, and the right side is larger than it. So we can take advantage of this and let us find the K element in the average time of O (n).
1 intPartitionintInt_array[],intLowintHigh )2 {3 intFirst = low, last =High ;4 intKey =Int_array[first];5 6 while(First <Last )7 {8 while(First < last && Int_array[last] >= key)--Last ;9Int_array[first] =Int_array[last];Ten while(First < last && Int_array[first] <= key) first++; OneInt_array[last] =Int_array[first]; A } -Int_array[first] =key; - returnFirst ; the } - - int Select(intA[],intLowintHighintk) - { + intindex =partition (A, low, high); - if(Index = =k) + returnA[index]; A Else at { - if(K <index) - Select(A, low, index-1, k); - Else - Select(A, index+1, High, Kindex); - } in}
Select the smallest element of K