在一组随机排列的数中找出第k小元素

在一组随机排列的数中找出第k小的,这个元素称为k-th Order Statistic。能想到的最直观的算法肯定是先把这些数排序然后取第k个,时间复杂度和排序算法相同,可以是Θ(nlgn),但它也有平均情况下时间复杂度是Θ(n)的算法,将快速排序算法稍加修改就可以解决这个问题:

 1 /*
2 **Find out the K-th small number of a set of random numbers with O(n)
3 **2011.10.25
4 **By LYLtim
5 */
6
7 #include<stdio.h>
8 #include<stdlib.h>
9 #include<time.h>
10
11 #define LEN 6
12 int a[LEN], k;
13
14 void creat()
15 {
16 register int *pa;
17 srand(time(NULL));
18 for (pa = a; pa < &a[LEN]; )
19 printf("%d ", *pa++ = rand() % LEN);
20 printf("\n");
21 }
22
23 void swap(int *a, int *b)
24 {
25 int t = *a;
26 *a = *b;
27 *b = t;
28 }
29
30 int Find (int left, int right)
31 {
32 if (left >= right) return; //do nothing if array contains fewer than 2 elemants
33 swap(&a[left], &a[(left + right) >> 1]); //move partition elem to left
34 unsigned p, last = left;
35 for (p = left + 1; p <= right; p++) //partiton
36 if (a[p] < a[left])
37 swap(&a[p], &a[++last]);
38 swap(&a[left], &a[last]); //restore partiton elem
39 if (last > k - 1) return Find(left, last - 1);
40 if (last < k - 1) return Find(last + 1, right);
41 return a[last];
42 }
43
44 int main(void)
45 {
46 creat();
47 printf("Inupt k to find out the K-th small number:");
48 scanf("%d", &k);
49 printf("The %dth small number is: %d\n", k, Find(0, LEN - 1));
50 }

 

  

转载于:https://www.cnblogs.com/LYLtim/archive/2011/10/29/2228328.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值