Select the small element from a set of unordered data, using the idea of quick sorting.
#include <iostream>#include<algorithm>using namespacestd;intPartitionintA[],intLintR) { intKey =A[l]; intI=l; Swap (a[l],a[r]); for(intj=l;j<r;j++) if(A[j]<key) Swap (a[i++],a[j]); Swap (a[i],a[r]); returni;}int Select(intA[],intLintRinti) { if(l==R)returnA[l]; intq=partition (A,L,R); intk=q+1-l; if(k==i)returnA[q]; Else if(k>i)return Select(a,l,q-1, i); Else return Select(a,q+1, r,i-k);}intMain () {inta[6] = {5,9, One, at,Ten, -}; cout<<SelectA0,8,4);//gets the 4th small element in a, which is one.}
Randomized version
#include <iostream>#include<algorithm>using namespacestd;intRand_partition (intA[],intLintR) { intQ=l+rand ()% (r+1-l); intKey =A[q]; intI=l; Swap (a[q],a[r]); for(intj=l;j<r;j++) if(A[j]<key) Swap (a[i++],a[j]); Swap (a[i],a[r]); returni;}int Select(intA[],intLintRinti) { if(l==R)returnA[l]; intq=rand_partition (A,L,R); intk=q+1-l; if(k==i)returnA[q]; Else if(k>i)return Select(a,l,q-1, i); Else return Select(a,q+1, r,i-k);}intMain () {inta[6] = {5,9, One, at,Ten, -}; cout<<SelectA0,8,4);//get the 4th-largest element in a, which is one.}
Selection algorithm for linear time based on average expectation