Quick Sort
The following is a quick-sort code that was previously implemented.
functionQuickSort (a,left,right) {if(left<Right ) {Let Mid=partition (A,left,right);//Select key subscriptQuickSort (a,left,mid-1);//sort the left half of keyQuickSort (A,mid+1,right)//sort the right half of the key }}functionpartition (A,left,right) {let key=a[left];//start by making key the first number while(Left<right) {//Scan it again . while(Key<=a[right]&&left<right) {//if key is less than a[right], then right decrements, continuing to compareright--; } [A[left],a[right]]=[a[right],a[left]];//Exchange while(Key>=a[left]&&left<right) {//if key is greater than a[left], left is incremented to continue the comparisonleft++; } [A[left],a[right]]=[a[right],a[left]];//Exchange } returnLeft//return the key where it is now}
Obviously, we can see that the idea of the Clippers is that each time a datum number is found, the array is arranged into a number that is larger than the base number, and each number on the right is smaller than the base number. With this idea, we can modify the Quicksort function slightly to make it a quicksearch function that has the largest number of K before it is quickly found.
finding the number of K-large based on the idea of fast sorting
functionQuickSearch (a,left,right,k) {if(k<1| | K>RIGHT-LEFT+1)return-1;//Focus 1, when the value of K does not meet the requirements, return-1 if(Left==right)returnA[left];//Focus 2, the end condition of the recursionLet Key=-1,len=0; if(left<Right ) {Key=partition (A,left,right); Len=right-key+1; if(len==k) {//Focus 3, the end condition of the recursion returnA[key]; } Else if(len>k) { returnQuickSearch (a,key+1, right,k); } Else{ returnQuickSearch (a,left,key-1,k-Len); } } returnkey;}functionpartition (A,left,right) {let key=a[left];//start by making key the first number while(Left<right) {//Scan it again . while(Key<=a[right]&&left<right) {//if key is less than a[right], then right decrements, continuing to compareright--; } [A[left],a[right]]=[a[right],a[left]];//Exchange while(Key>=a[left]&&left<right) {//if key is greater than a[left], left is incremented to continue the comparisonleft++; } [A[left],a[right]]=[a[right],a[left]];//Exchange } returnLeft//return the key where it is now}let arr=[5,4,3,2,1,6];let Kmax=quicksearch (arr,0,5,2); Console.log (Kmax);
The key point is to pay attention to determine the boundary conditions, left,right,k Three are changing, so need to examine
In the same vein, you can also ask for a small number of K
Operation Result:
Top K maximum number based on fast sort lookup