- Using a quick sort, randomly finding an element x from an array, dividing the array into two parts that are smaller than x and larger than X, assuming that the number of elements smaller than x is B, then:
(1) if B >= K, then recursion from the small part of the x to find the element K large.
(2) If B < K, then recursively find the larger element (K-b) from the larger part of X.
2.
(1) Using the minimum heap, similar to the O (NLOGM) algorithm in the written question.
(2) Use the maximum heap, similar to the O (MLOGN) algorithm in the written question.
intGetParentintBeginintEndintindex) { intParentindex = (index-begin-1)/2+begin; returnParentindex;}intGetlchild (intBeginintEndintindex) { intLchildindex = (index-begin) *2+1+begin; returnLchildindex;}intGetrchild (intBeginintEndintindex) { intRchildindex = (index-begin) *2+1+ Begin +1; returnRchildindex;}voidAdjustheap (vector<int> & V,intBeginintEndintindex) { intLchild =Getlchild (Begin,end,index); intRchild =Getrchild (Begin,end,index); intlargest =index; if(Rchild <= end && V[rchild] >V[largest]) largest=Rchild; if(Lchild <= end && V[lchild] >V[largest]) largest=Lchild; if(Largest! =index) { inttemp =V[largest]; V[largest]=V[index]; V[index]=temp; Adjustheap (v,begin,end,largest); }//Show (v,begin,end);}voidBuildmaxheap (vector<int> & V,intBeginintend) { intParent =GetParent (begin,end,end); while(Parent >=begin) {adjustheap (v,begin,end,parent); Parent--; }}voidHeapsort (vector<int> & V,intBeginintend) {buildmaxheap (v,begin,end);//Show (v,begin,end); intTempend =end; for(; Tempend >begin;) { inttemp =V[begin]; V[begin]=V[tempend]; V[tempend]=temp; Adjustheap (V,begin,--tempend,begin); }}intGetkmaxbyheapsort (vector<int> & V,intBeginintEndintK) {//This is similar to the complete heap sequencing step, but the number of step cycles has decreased by buildmaxheap (v,begin,end); inti =0 ; inttemp =0; for(; i < K; i++) {Temp=V[begin]; V[begin]=V[end]; V[end]=temp; Adjustheap (V,begin,--end,begin); } returntemp;}
Like a quick sort of way
intPartition (vector<int> & V,intBeginintend) { intKey =V[begin]; inti =begin; intj =end; while(i<j) { while(J>i && V[j] <=key) J--; while(J>i && V[i] >key) I++; inttemp =V[j]; V[J]=V[i]; V[i]=temp; } V[i]=key; returni;}voidQuicksort (vector<int> & V,intBeginintend) { if(Begin <end) { intMID =partition (V,begin,end); Quicksort (V,begin,mid-1); Quicksort (V,mid+1, end); }}intGetkmaxbyquicksort (vector<int> & V,intBeginintEndintK) { if(Begin = =end)returnV[begin]; intMID =partition (V,begin,end); intnum = Mid-begin +1; if(num = =K) { returnV[begin +K]; } if(Num >K) { returnGetkmaxbyquicksort (v,begin,mid-1, K); } if(Num <K) { returnGetkmaxbyquicksort (v,mid+1, end,k-num); }}
Get number of K-Large