nth_element 找第k大的數
阿新 • • 發佈:2018-12-11
nth_element
nth_element用於排序一個區間,它使得位置n上的元素正好誰全排序情況下的第n個元素,而且,當nth_element返回的時候,所有按照全排序規則排在位置n之前的元素也都排在位置n之前,按照全排序規則排在n之後的元素全都排在位置n之後。 所以,我們使用nth_element既可以尋找最好的前k個元素,也可以尋找第k大元素。
先看示例:
#include <iostream> #include <algorithm> #include <functional> using namespace std; int main() { int a[10] = { 8, 9, 1, 2, 4, 3, 5, 6, 7, 10 }; nth_element(a, a + 5, a + 10, std::greater<int>()); cout << "陣列中的中間元素是" << a[5] << endl; nth_element(a, a, a + 10, std::greater<int>()); cout << "陣列中第1大元素為" << a[0] << endl; nth_element(a, a + 1, a + 10, std::greater<int>()); cout << "陣列中第2大元素是" << a[1] << endl; }
結果為:
陣列中的中間元素是5
陣列中第1大元素為10
陣列中第2大元素是9
請按任意鍵繼續. . .