日期:2014-05-20 浏览次数:20714 次
#include <stdio.h>
#include <time.h>
#define SWAP(x, y) {int t; t=x; x=y; y=t;}
int partition(int a[], int p, int r)
{
int x = a[r];
int i = p-1, j;
for(j = p; j <= r-1; j++)
{
if(a[j] <= x)
{
i++;
SWAP(a[i], a[j]);
}
}
SWAP(a[i+1], a[r]);
return i+1;
}
int randomized_partiton(int a[], int p, int r)
{
int x = rand()%r;
int temp;
temp = x+p > r ? x: x+p;
SWAP(a[temp], a[r]);
return partition(a, p, r);
}
int randomized_select(int a[], int p, int r, int i)
{
int q, k;
// 检测程序只有一个元素的情况
if(p==r)
return a[p];
q = randomized_partiton(a, p, r);
k = q - p+1;
if(i==k)
return a[q];
else if(i < k)
return randomized_select(a, p, q-1, i);
else
return randomized_select(a, q+1, r, i-k);
}
int main()
{
int a[10]={3,1,5,7,8,2,4,6,10,9};
int x;
srand(time(NULL));
x = randomized_select(a, 0, 9, 10);
printf("%d\n", x);
system("pause");
return 0;
}