Find a set of N number of the largest of the K, set K=N/2.
1 ImportJava.util.Random;2 3 4 Public classK_max {5 6 /**7 * @paramargs8 */9 //The number of k large, to ensure that K is greater than or equal to 1, less than equals ARRAY.LENGTH/2 ohTen Public Static intTopK (intArray[],intK) One { A intTopk[] =New int[K]; - for(inti = 0; i<topk.length;i++) -Topk[i] =Array[i]; the -Insertsort (TOPK);//from small to large - - for(inti = topk.length; i<array.length;i++) + { - inttarget =Array[i]; + if(Target < Topk[0]) A ; at Else - { - intPosition = Findinsertplace (topk,target,0,topk.length-1); - for(intj = 0;j<position;j++) -TOPK[J] = topk[j+1]; -Topk[position] =Target; in } - } to returnTopk[0]; + } - //find the location where you want to insert the two points the Public Static intFindinsertplace (int[] A,intTargetintAintb) * { $ intMiddle = a + (b-a)/2;Panax Notoginseng if(a>b) - returnb; the Else if(a[middle]==target) + returnMiddle; A Else if(a[middle]<target) the returnFindinsertplace (a,target,middle+1, b); + Else - returnFindinsertplace (a,target,a,middle-1); $ } $ //Insert Sort - Public Static voidInsertsort (int[] num)//sort from small to large - { the for(inti = 1; i<num.length;i++) - { Wuyi inttemp =Num[i]; the intJ=i-1; - while(J>=0 && Temp <Num[j]) Wu { -num[j+1]=Num[j]; Aboutj--; $ } -NUM[J+1] =temp; - } - A } + Public Static voidMain (string[] args) { the //random assignment of an array - intRandomarray[] =New int[15]; $Random random =NewRandom (); the for(inti = 0; I < randomarray.length;i++) { theRandomarray[i] = Math.Abs (Random.nextint ()% (randomarray.length*10)); the } the intK =3; - intK_max =TopK (randomarray,k); inSystem.out.println ("the" +k + "th biggest number of:"); the Insertsort (randomarray); the for(intA:randomarray) AboutSystem.out.print (A + ""); the System.out.println (); theSystem.out.println ("is:" +K_max); the } -}
"Data structure and algorithm analysis: C language description" Reading notes------exercise 1.1 to ask for the number of k large