《数据结构与算法分析:C语言描述》读书笔记------练习1.1 求第K大的数

时间:2020-12-20 14:32:31

求一组N个数中的第k个最大者,设k=N/2.

 import java.util.Random;

 public class K_Max {

     /**
      * @param args
      */
     //求第K大的数,保证K大于等于1,小于等于array.length/2哦
     public static int TopK(int array[],int K)
     {
         int topk[] = new int [K];
         for(int i = 0; i<topk.length;i++)
             topk[i] = array[i];

         InsertSort(topk);//从小到大

         for(int i = topk.length; i<array.length;i++)
         {
             int target = array[i];
             if(target < topk[0])
                 ;
             else
             {
                 int position = findInsertPlace(topk,target,0,topk.length-1);
                 for(int j = 0;j<position;j++)
                     topk[j] = topk[j+1];
                 topk[position] = target;
             }
         }
         return topk[0];
     }
     //二分查找应该插入的位置
     public static int findInsertPlace(int [] A,int target,int a, int b)
     {
         int  middle = a+(b-a)/2;
         if(a>b)
             return b;
         else if (A[middle]==target)
             return middle;
         else if (A[middle]< target)
             return findInsertPlace(A,target,middle+1,b);
         else
             return findInsertPlace(A,target,a,middle-1);
     }
     //插入排序
     public static void InsertSort(int [] num)//从小到大排序
     {
         for(int i =1; i<num.length;i++)
         {
             int temp = num[i];
             int j=i-1;
             while(j>=0 && temp < num[j])
             {
                 num[j+1]=num[j];
                 j--;
             }
             num[j+1] = temp;
         }

     }
     public static void main(String[] args) {
         //随机赋值一个数组
         int randomArray[] = new int[15];
         Random random = new Random();
         for(int i = 0; i < randomArray.length;i++) {
             randomArray[i] = Math.abs(random.nextInt()%(randomArray.length*10));
         }
         int K =3;
         int k_max = TopK(randomArray,K);
         System.out.println("The "+K +" th biggest number of:");
         InsertSort(randomArray);
         for(int a:randomArray)
             System.out.print(a+" ");
         System.out.println();
         System.out.println("is: "+k_max);
     }
 }