分治法:快速排序求第K极值

标题其实就是nth_element函数的底层实现

nth_element(first, nth, last, compare)

求[first, last]这个区间中第n大小的元素

如果参数加入了compare函数,就按compare函数的方式比较

array[first, last)元素区间,排序后,array[nth]就是第n大的元素(从0开始)

 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4  
 5 int main(){
 6     int array[] = {5,6,7,8,4,2,1,3,0};
 7     int len=sizeof(array)/sizeof(int);
 8     cout<<"排序前: ";
 9     for(int i=0; i<len; i++)
10         cout<<array[i]<<" ";
11     nth_element(array, array+6, array+len);  //排序第6个元素
12         cout<<endl;
13     cout<<"排序后:"; 
14     for(int i=0; i<len; i++)
15         cout<<array[i]<<" ";
16         
17     cout<<endl<<"第6个元素为"<<array[6]<<endl; 
18 }
原文地址:https://www.cnblogs.com/aininot260/p/9643645.html