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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| #include <iostream> #include <algorithm>
using namespace std;
int InsertSort(int array[], int left, int right); int GetPivotIndex(int array[], int left, int right); int Partition(int array[], int left, int right, int pivot_index); int BFPRT(int array[], int left, int right, int k);
int main() { int k = 8; int array[20] = { 11,9,10,1,13,8,15,0,16,2,17,5,14,3,6,18,12,7,19,4 };
cout << "原数组:"; for (int i = 0; i < 20; i++) cout << array[i] << " "; cout << endl;
cout << "第 " << k << " 小值为:" << array[BFPRT(array, 0, 19, k)] << endl;
cout << "变换后的数组:"; for (int i = 0; i < 20; i++) cout << array[i] << " "; cout << endl;
return 0; }
int InsertSort(int array[], int left, int right) { int temp; int j;
for (int i = left + 1; i <= right; i++) { temp = array[i]; j = i - 1;
while (j >= left && array[j] > temp) { array[j + 1] = array[j]; j--; }
array[j + 1] = temp; }
return ((right - left) >> 1) + left; }
int GetPivotIndex(int array[], int left, int right) { if (right - left < 5) return InsertSort(array, left, right);
int sub_right = left - 1;
for (int i = left; i + 4 <= right; i += 5) { int index = InsertSort(array, i, i + 4); swap(array[++sub_right], array[index]); }
return BFPRT(array, left, sub_right, ((sub_right - left + 1) >> 1) + 1); }
int Partition(int array[], int left, int right, int pivot_index) { swap(array[pivot_index], array[right]);
int partition_index = left; for (int i = left; i < right; i++) { if (array[i] < array[right]) { swap(array[partition_index++], array[i]); } }
swap(array[partition_index], array[right]);
return partition_index; }
int BFPRT(int array[], int left, int right, int k) { int pivot_index = GetPivotIndex(array, left, right); int partition_index = Partition(array, left, right, pivot_index); int num = partition_index - left + 1;
if (num == k) return partition_index; else if (num > k) return BFPRT(array, left, partition_index - 1, k); else return BFPRT(array, partition_index + 1, right, k - num); }
|