STL:排序

来源:互联网 发布:网络电视怎么放音乐 编辑:程序博客网 时间:2024/05/18 08:45

前言

区间范围[a, b)

全局排序:给定区间,全部排序。有sort, stable_sort。

局部排序:给定区间,只需排除前几个,或后几个。比如:一个班级100名学生,只输出前10名同学,并且有序。或者倒数10名。有partial_sort, partial_stable_sort。

测试文本内容:

1 3 4 2 5 8 6 7 9 10 

测试1:partial_sort

#include <stdio.h>#include <iostream>#include <algorithm>using namespace std;int main(){#ifdef ONLINE_JUDGE#else    freopen("E:\\in.txt", "r", stdin);#endifint buf[100];for(int i=0; i<10; i++){scanf("%d", &buf[i]);}partial_sort(buf, buf+3, buf+10); //前3个有序for(int i=0; i<10; i++){printf("%d ", buf[i]);}cout << endl;return 0;}

结果:

10 1 8 3 7 2 5 6 9 4  //排序前1 2 3 10 8 7 5 6 9 4  //排序后

测试2:nth_element():

只求第几小,或第几大。比如,我要求第3小,那么buf[3-1]这个位置上就应当是第3小的值,其他不定。


代码与上面相同,仅仅把partial_sort 换成nth_element.

nth_element(buf, buf+3, buf+10);


结果:

10 1 8 3 7 2 5 6 9 4  //前3 1 2 4 7 8 5 6 9 10  //后

我们求的是倒数第4(buf+3是第4个位置)小,理论上,第四个位置应为4.实际也是。



0 0
原创粉丝点击