The general selection problem appears more difficult than the simple problem of finding a minimum. Yet, surprisingly, the asymptotic running time for both problems is the same: Θ(n). In this section, we present a divide-and-conquer algorithm for the selection problem. The algorithm RANDOMIZED-SELECT is modeled after the quicksort algorithm of Chapter 7. As in quicksort, the idea is to partition the input array recursively. But unlike quicksort, which recursively processes both sides of the partition, RANDOMIZED-SELECT only works on one side of the partition. This difference shows up in the analysis: whereas quicksort has an expected running time of Θ(n lg n), the expected time of RANDOMIZED-SELECT is Θ(n).
RANDOMIZED-SELECT uses the procedure RANDOMIZED-PARTITION introduced in Section 7.3. Thus, like RANDOMIZED-QUICKSORT, it is a randomized algorithm, since its behavior is determined in part by the output of a random-number generator. The following code for RANDOMIZED-SELECT returns the ith smallest element of the array A[p .. r].
RANDOMIZED-SELECT(A, p, r, i) 1 if p = r 2 then return A[p] 3 q ← RANDOMIZED-PARTITION(A, p, r) 4 k ← q - p + 1 5 if i = k ▹ the pivot value is the answer 6 then return A[q] 7 elseif i < k 8 then return RANDOMIZED-SELECT(A, p, q - 1, i) 9 else return RANDOMIZED-SELECT(A, q + 1, r, i - k)
#include<iostream> #include<time.h> using namespace std;
void initArray(int arr[], int n, int top){ srand(time(NULL)); for(int i=0; i<n; i++){ arr[i] = rand()%top; } }
void printArray(int arr[], int n){ for(int i=0; i<n; i++){ cout<<arr[i]<<" "; } cout <<endl; } int partition(int arr[], int p, int r){ int temp = arr[r]; int i=p-1; for(int j=p; j<r;j++){ if(arr[j]<temp){ swap<int>(arr[++i],arr[j]); } } swap<int>(arr[++i],arr[r]); return i; } //return the index smallest number, counter from 0 int selection(int arr[], int p, int r, int index){ if(p==r){ return arr[p]; } int q = partition(arr,p,r); if(index==q){ return arr[q]; }else if(index<q){ return selection(arr,p,q-1,index); }else{ return selection(arr,q+1,r,index-q-1); }
} void main(){ const int AD = 10; int arr[AD]; initArray(arr,AD,400); printArray(arr,AD); int smallest = selection(arr,0,AD-1,3); cout<<" 3 smallest: "<<smallest<<endl; cin.get(); }