一.最大值与最小值
1 #include<iostream> 2 using namespace std; 3 4 template<typename T> 5 void MaxMin(T A[], int length, T &max, T &min) 6 { 7 if (A == NULL || length <= 0) 8 { 9 return; 10 } 11 int i; 12 if (length % 2 == 0) 13 { 14 i = 2; 15 if (A[0] > A[1]) 16 { 17 max = A[0]; 18 min = A[1]; 19 } 20 else 21 { 22 max = A[1]; 23 min = A[0]; 24 } 25 } 26 else 27 { 28 max = A[0]; 29 min = A[0]; 30 i = 1; 31 } 32 33 for (; i < length; i += 2) 34 { 35 T cmax, cmin; 36 if (A[i] > A[i + 1]) 37 { 38 cmax = A[i]; 39 cmin = A[i + 1]; 40 } 41 else 42 { 43 cmax = A[i + 1]; 44 cmin = A[i]; 45 } 46 47 if (max < cmax) 48 { 49 max = cmax; 50 } 51 if (min > cmin) 52 { 53 min = cmin; 54 } 55 } 56 } 57 58 int main() 59 { 60 int A[] = { 111, 2, 37, 3, 4, 100, 0, 600, 20, 10, -11}; 61 int max, min; 62 MaxMin(A, 11, max, min); 63 cout << max << " " << min << endl; 64 return 0; 65 }
最多3*(n / 2)次比较
二.在最坏情况下 找到n个元素第二小
http://blog.csdn.net/mishifangxiangdefeng/article/details/7983809
三.线性选择算法
1 #include<iostream> 2 #include<stdlib.h> 3 using namespace std; 4 5 template <typename T> 6 int Partition(T A[], int p, int r) 7 { 8 T x = A[r]; 9 int i = p - 1; 10 for (int j = p; j <= r - 1; j++) 11 { 12 if (A[j] <= x) 13 { 14 i++; 15 T temp = A[j]; 16 A[j] = A[i]; 17 A[i] = temp; 18 } 19 } 20 T temp = A[i + 1]; 21 A[i + 1] = A[r]; 22 A[r] = temp; 23 return i + 1; 24 } 25 26 template <typename T> 27 int RandomizedPartition(T A[], int p, int r) 28 { 29 int i = rand() % (r - p + 1) + p; 30 T temp = A[r]; 31 A[r] = A[i]; 32 A[i] = temp; 33 return Partition(A, p, r); 34 } 35 36 template <typename T> 37 T RandomizedSelect(T A[], int p, int r, int i) 38 { 39 if (A != NULL && p >= 0 && r >= 0 && r >= p) 40 { 41 if (r - p + 1 < i) 42 { 43 return NULL; 44 } 45 else 46 { 47 if (r == p) 48 { 49 return A[p]; 50 } 51 int q = RandomizedPartition(A, p, r); 52 int k = q - p + 1; 53 if (i == k) 54 { 55 return A[q]; 56 } 57 else if (i < k) 58 { 59 return RandomizedSelect(A, p, q - 1, i); 60 } 61 else 62 { 63 return RandomizedSelect(A, q + 1, r, i - k); 64 } 65 } 66 } 67 } 68 69 int main() 70 { 71 double A[] = { 1.1, -2.1, 3, 3, 4, -10, 4, 2.6 ,20, 10}; 72 cout << RandomizedSelect(A, 0, 9, 2) << endl; //-2.1 73 return 0; 74 }
四.最坏情况为线性的选择
1.将输入数组的n个元素划分为n/5组,每组5个元素,剩余的一组由n mod 5个元素组成
2.寻找n/5组,每组的中位数
3.对n/5个中位数用select找出其中位数x
4.用中位数x对输入的数进行划分
时间: 2024-10-04 23:44:18