STL

来源:互联网 发布:json 20160212.jar 编辑:程序博客网 时间:2024/06/01 16:36

1 - sort
这个就不用说了吧。最快的一个,一般都用它。

2 - stable_sort
以前没看到过?这个保证了排序前后相等元素之间的相对位置不发生改变。这对于内置类型的默认比较方式来说没什么用(相等就相等,改变了也没用),但对于结构体,或者传入了比较函数的就有用了,它保证了排序前后“相等”元素的相对位置的不发生改变。速度比sort慢,但时间复杂度相同。用法同sort。

3 - partial_sort
这个直译为部分排序。它的原理是把所有元素放入一个堆中,然后仅将前k个元素恢复到正常顺序,后面的元素不保证有序。对于“取前x小的元素”的问题,这个函数或许要快些。第二个参数是最后一个需要有序的元素的后一个迭代器,相当于右区间。

4 - nth_element
原理就是快速选择,时间复杂度为O(n),选择第x小的元素首选!它的第二个参数是保存第x小的元素的迭代器,也就是相当于左区间。换句话说,从0开始计数的要-1。

3 4 的演示代码

//使用STL的partial_sort和nth_element(前者慢,用于部分排序,不用于查找第k小的元素,代码中的是误用)#include <cstdio>#include <cstdlib>#include <cmath>#include <cstring>#include <string>#include <iostream>#include <algorithm>#include <vector>#include <stack>#include <queue>#include <deque>#include <map>#include <set>using std::cin;using std::cout;using std::endl;typedef long long LL;inline int readIn(){    int a = 0;    char ch = getchar();    while (!(ch >= '0' && ch <= '9')) ch = getchar();    while (ch >= '0' && ch <= '9')    {        a *= 10;        a += ch;        a -= '0';        ch = getchar();    }    return a;}const int maxn = 10000000;int a[maxn];LL randEx(){    LL temp = rand();    temp <<= 15;    temp |= rand();    return temp % maxn;}int findKth_heap(int k){    std::partial_sort(a, a + k, a + maxn); //这里是k,因为相当于右区间,所以是开区间    return a[k - 1];}int findKth_quick(int k){    std::nth_element(a, a + k - 1, a + maxn); //这里是k - 1,因为传入的是一个元素的地址,相当于左区间    return a[k - 1];}int main(){    for (int i = 0; i < maxn; i++)    {        a[i] = i + 1;    }    for (int i = 0; i < maxn; i++)    {        std::swap(a[i], a[randEx()]);    }    for (int i = 0; i < maxn / 10000; i++)    {        printf("%d ", a[i]);    }    puts("");    int n = readIn();    printf("%d\n", findKth_quick(n));    return 0;}
原创粉丝点击