基於快排的partition實現TOPK問題
阿新 • • 發佈:2019-02-14
類似於快速排序,首先選擇一個劃分元,如果這個劃分元的序號index剛好等於k,那麼這個劃分元以及左邊的數,剛好組成了top-k small data;如果index>k, 那top-k small data在index的左邊,那麼就繼續遞迴從index-1和數中選取top-k.如果index < k,那麼說明還要從index的右邊,選取top-(k-index) small data.
- public class TopK_Quick {
- public static int Partition(int a[],int low,int high)
- {
- a[0]=a[low];
- int
- while(low<high)
- {
- while(low<high && a[high]>=pivokey) --high;
- a[low] = a[high];
- while(low<high && a[low]<=pivokey) ++low;
- a[high]= a[low];
- }
- a[low]=a[0];
- return low;
- }
- public static void display(int a[],int k)
- {
- for(int i=1;i<=k;i++)
- {
- System.out.print(a[i]+" ");
- }
- }
- public static int selectK(int a[],int start,int end,int k)
- {
- int index = 0;
- if(start<end)
- {
- index = Partition(a,start,end);
- if(index == k)//正好找到第k大的數
- {
- index = k;
- }else if(index <k)//還要從index的右邊找k-index個數
- {
- index = selectK(a,index+1,end,k-index);
- }else if(index > k)//k個數都在Index的左邊
- {
- index =
selectK
- }
- }
- return index;
- }
- public static void main(String args[])
- {
- int k=0;
- int a[]={0,49,38,29,65,97,76,13,27,49,22,19};
- if(k>0&&k<=a.length-1)
- {
- selectK(a,1,a.length-1,k);
- display(a,k);
- }else{
- System.out.println("Are You Kidding Me?");
- }
- }
- }