中位数和顺序统计(线性时间)算法导论9.2

来源:互联网 发布:淘宝预售权限开通 编辑:程序博客网 时间:2024/04/27 18:07

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 ofChapter 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 inSection 7.3. Thus, like RANDOMIZED-QUICKSORT, it is a randomized algorithm, since its behavior is determined in part by the output of a random-numbergenerator. The following code for RANDOMIZED-SELECT returns theith smallest element of the array A[p .. r].

RANDOMIZED-SELECT(A, p, r, i)1  if p = r2      then return A[p]3  q  RANDOMIZED-PARTITION(A, p, r)4  k  q - p + 15  if i = k           the pivot value is the answer6      then return A[q]7  elseif i < k8      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 0int 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();}

原创粉丝点击