分治法实现元素选择问题！！！

xiaomubiao 2004-04-30 12:15:06

...全文
397 2 打赏 收藏 举报

2 条回复

#include<stdlib.h>
#include<time.h>
#include<stdio.h>

#define Swap(a,b) {int t=b; b=a; a=t;}

int partition(int a[],int L, int r)
{
int i = L-1,j=r;
int v = a[r];
while(1)
{
while(a[++i] < v);
while(v < a[--j]) if(j==L) break;
if(i>=j) break;
Swap(a[i],a[j]);
}
Swap(a[i],a[r]);
return i;
}

int RandomPartition( int a[], int l, int r)
{
srand(time(0));
int i = rand()%(r-l+1)+l;//随机划分:
Swap(a[i],a[r]);
return partition(a,l,r);
}

int RandomSelect(int a[], int l, int r, int k)
{
if(r<=l) return a[r];
int i= RandomPartition(a,l,r);
int j = i-l+1;
if(j == k)
return a[i];
if(j>k)
return RandomSelect(a,l,i-1,k);
else
return RandomSelect(a,i+1,r,k-j);

}

void disp(int a[],int n)
{
for(int i=0; i<n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[]={1,12,3,-4,81,16,100,17};
disp(a,8);
int k;
scanf("%d",&k);
printf("\n the %d's Big Number is : %d ",k,RandomSelect(a,0,7,k));

system("pause");

}
• 打赏
• 举报

BlueSky2008 2004-04-30
http://expert.csdn.net/Expert/topic/2642/2642994.xml?temp=.6752436
• 打赏
• 举报

3.2w+

2004-04-30 12:15