C++完成查找中位數的O(N)算法和Kmin算法。本站提示廣大學習愛好者:(C++完成查找中位數的O(N)算法和Kmin算法)文章只能為提供參考,不一定能成為您想要的結果。以下是C++完成查找中位數的O(N)算法和Kmin算法正文
本文實例講述了C++完成查找中位數的O(N)算法和Kmin算法,分享給年夜家供年夜家參考。詳細辦法以下:
應用疾速排序的partition操作來完成O(N)時光內的中位數的查找算法以下:
#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算法以下:
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++法式算法設計的進修有所贊助。