我也贴一个!寻找第k大的元素的代码如下(为简单起见,数组作顺序表,改链表也不难:))。使用的是随机算法!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int select(int a[], int n, int k)
{
int r;
int p;
int a1[10], a2[10];
int j = 0, l = 0, i = 0;
srand((int)time(0));
r = rand()%n;
p = a[r];
//printf("%d, %d,%d\n", r,n,p);
for(i = 0; i < n; ++i)
{
if(a[i] > p)
a1[j++] = a[i];
else
if(a[i] < p )
a2[l++] = a[i];
}
if( k <= j)
return select(a1, j, k);
else
if (k > (n - l))
return select(a2, l, k-(n-l));
else
return p;
}
int main()
{
int k = 4;
int a[10] = {11,3,343,2399, 9892, 133, 29, 5923,83,4939};
int x = select(a, 10, k);
printf("第%d大的元素为: %d\n", k, x);
system("PAUSE");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int select(int a[], int n, int k)
{
int r;
int p;
int a1[10], a2[10];
int j = 0, l = 0, i = 0;
srand((int)time(0));
r = rand()%n;
p = a[r];
//printf("%d, %d,%d\n", r,n,p);
for(i = 0; i < n; ++i)
{
if(a[i] > p)
a1[j++] = a[i];
else
if(a[i] < p )
a2[l++] = a[i];
}
if( k <= j)
return select(a1, j, k);
else
if (k > (n - l))
return select(a2, l, k-(n-l));
else
return p;
}
int main()
{
int k = 4;
int a[10] = {11,3,343,2399, 9892, 133, 29, 5923,83,4939};
int x = select(a, 10, k);
printf("第%d大的元素为: %d\n", k, x);
system("PAUSE");
return 0;
}