# 线性时间O(n)内求数组中第k大小的数

——本文为博主原创，转载请注明出处

因为传感器的代码需要用nesC写，所以程序采用C语言实现

``` 1 #include <stdio.h>
2
3 int partition(int *a, int low, int high)
4 {
5     int pivot = a[low];
6     while (low < high)
7     {
8         while (a[high] >= pivot && low < high)
9             high--;
10         a[low] = a[high];
11
12         while (a[low] <= pivot && low <high)
13             low++;
14         a[high] = a[low];
15     }
16     a[low] = pivot;
17     return low;
18 }
19
20 int quickSortKth(int *a, int low, int high, int k)
21 {
22     if (low >= high)
23         return a[low];
24     else
25     {
26         int mid = partition(a, low, high);
27         if (mid > k)
28             quickSortKth(a, low, mid - 1, k);
29         else if (mid < k)
30             quickSortKth(a, mid + 1, high, k);
31         else
32             return a[mid];
33     }
34 }
35
36 int getKthMax(int *a, int k, int len) {
37     return quickSortKth(a, 0, len - 1, len-k);
38 }
39
40 int getKthMin(int *a, int k, int len) {
41     return quickSortKth(a, 0, len - 1, k-1);
42 }
43
44 int main()
45 {
46     int a[15] = { 13,7,8,6,3,10,11,14,15,12,1,5,2,4,9 };
47     int k;
48     int len = sizeof(a) / sizeof(a[0]);//获取数组a的大小
49     scanf("%d", &k);
50     //printf("%d", len);
51     printf("result: %d\n", getKthMin(a, k, len));
52     return 0;
53 }```

2016-12-25

(0)
(0)

0条