C++實現(xiàn)查找中位數(shù)的O(N)算法和Kmin算法
更新時間:2014年09月18日 10:44:21 投稿:shichen2014
這篇文章主要介紹了C++實現(xiàn)查找中位數(shù)的O(N)算法和Kmin算法,對于C++程序算法設(shè)計有一定的借鑒價值,需要的朋友可以參考下
本文實例講述了C++實現(xiàn)查找中位數(shù)的O(N)算法和Kmin算法,分享給大家供大家參考。具體方法如下:
利用快速排序的partition操作來完成O(N)時間內(nèi)的中位數(shù)的查找算法如下:
#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++程序算法設(shè)計的學(xué)習(xí)有所幫助。
相關(guān)文章
C語言 數(shù)據(jù)結(jié)構(gòu)堆排序順序存儲(升序)
這篇文章主要介紹了C語言 數(shù)據(jù)結(jié)構(gòu)堆排序順序存儲(升序)的相關(guān)資料,需要的朋友可以參考下2017-05-05基于Matlab實現(xiàn)BP神經(jīng)網(wǎng)絡(luò)交通標(biāo)志識別
道路交通標(biāo)志用以禁止、警告、指示和限制道路使用者有秩序地使用道路,?保障出行安全.若能自動識別道路交通標(biāo)志,?則將極大減少道路交通事故的發(fā)生。本文將介紹基于Matlab實現(xiàn)BP神經(jīng)網(wǎng)絡(luò)交通標(biāo)志識別,感興趣的可以學(xué)習(xí)一下2022-01-01數(shù)據(jù)結(jié)構(gòu)之堆的具體使用
本文主要介紹了數(shù)據(jù)結(jié)構(gòu)之堆的具體使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02C++中的類成員函數(shù)當(dāng)線程函數(shù)
這篇文章主要介紹了C++中的類成員函數(shù)當(dāng)線程函數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11