C++实现查找中位数的O(N)算法和Kmin算法

时间:2021-12-05 06:05:45

本文实例讲述了C++实现查找中位数的O(N)算法和Kmin算法,分享给大家供大家参考。具体方法如下:

利用快速排序的partition操作来完成O(N)时间内的中位数的查找算法如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <cassert>
#include <algorithm>
#include <iterator>
 
using namespace std;
 
int array[] = {1, 2, 10, 8, 9, 7, 5};
const int size = sizeof array / sizeof *array;
 
int partition(int *array, int left, int right)
{
 if (array == NULL)
 return -1;
 
 int pos = right;
 right--;
 while (left <= right)
 {
 while (left < pos && array[left] <= array[pos])
  left++;
 
 while (right >= 0 && array[right] > array[pos])
  right--;
 
 if (left >= right)
  break;
 
 swap(array[left], array[right]);
 }
 swap(array[left], array[pos]);
 
 return left;
}
 
int getMidIndex(int *array, int size)
{
 if (array == NULL || size <= 0)
 return -1;
 
 int left = 0;
 int right = size - 1;
 int midPos = right >> 1;
 int index = -1;
 
 while (index != midPos)
 {
 index = partition(array, left, right);
 
 if (index < midPos)
 {
  left = index + 1;
 }
 else if (index > midPos)
 {
  right = index - 1;
 }
 else
 {
  break;
 }
 }
 
 assert(index == midPos);
 return array[index];
}
 
void main()
{
 int value = getMidIndex(array, size);
 
 cout << "value: " << value << endl;
}

寻找kmin算法如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
int findKMin(int *array, int size, int k)
{
 if (array == NULL || size <= 0)
 return -1;
 
 int left = 0;
 int right = size - 1;
 int index = -1;
 
 while (index != k)
 {
 index = partition(array, left, right);
 
 if (index < k)
 {
  left = index + 1;
 }
 else if (index > k)
 {
  right = index - 1;
 }
 else
 {
  break;
 }
 }
 
 assert(index == k);
 return array[index];
}

希望本文所述对大家C++程序算法设计的学习有所帮助。