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

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(); }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值