基于快排的partition实现TOPK问题

来源:互联网 发布:剑三萝莉脸型数据截图 编辑:程序博客网 时间:2024/06/06 04:02

 

类似于快速排序,首先选择一个划分元,如果这个划分元的序号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.

  1. public class TopK_Quick {
  2. public static int Partition(int a[],int low,int high)
  3. {
  4. a[0]=a[low];
  5. int pivokey = a[low];
  6. while(low<high)
  7. {
  8. while(low<high && a[high]>=pivokey) --high;
  9. a[low] = a[high];
  10. while(low<high && a[low]<=pivokey) ++low;
  11. a[high]= a[low];
  12. }
  13. a[low]=a[0];
  14. return low;
  15. }
  16. public static void display(int a[],int k)
  17. {
  18. for(int i=1;i<=k;i++)
  19. {
  20. System.out.print(a[i]+" ");
  21. }
  22. }
  23. public static int selectK(int a[],int start,int end,int k)
  24. {
  25. int index = 0;
  26. if(start<end)
  27. {
  28. index = Partition(a,start,end);
  29. if(index == k)//正好找到第k大的数
  30. {
  31. index = k;
  32. }else if(index < k)//还要从index的右边找k-index个数
  33. {
  34. index = selectK(a,index+1,end,k-index);
  35. }else if(index > k)//k个数都在Index的左边
  36. {
  37. index = selectK(a,start,index-1,k);
  38. }
  39. }
  40. return index;
  41. }
  42. public static void main(String args[])
  43. {
  44. int k=0;
  45. int a[]={0,49,38,29,65,97,76,13,27,49,22,19};
  46. if(k>0&&k<=a.length-1)
  47. {
  48. selectK(a,1,a.length-1,k);
  49. display(a,k);
  50. }else{
  51. System.out.println("Are You Kidding Me?");
  52. }
  53. }
  54. }
原创粉丝点击