一些排序方法的总结

1.sort

头文件:algorithm

(1)有数组a[n],通过sort(a,a+n),可以将数列从a[0]到a[n-1]排序;通过sort(a+1,a+n-1)可以将数列由a[1]到a[n-2]排序。默认是从小到大排序。

(2)如果希望从大到小排序或者按照其他规则排序可以设置比较函数。

排序对象:

struct Group
{
    int s,e,idx;
}a[5001];

比较函数:

bool cmp(Group x, Group y)
{
    if(x.e!=y.e) return x.e<y.e;//从小到大排序
    else if(x.s!=y.s) return x.s<y.s;
    else return x.idx<y.idx;
}
执行:
sort(a+1,a+n+1,cmp);

则可以将结构体数组从a[1]到a[n]从小到大排序。注意这里的“大”和“小”是严格弱序中的大与小。

(3)重载运算符。

排序对象:

struct Node
{
    int x;
    int y;
}a[10];
重载operator <

bool operator < (const Node &i,const Node &j)
{
    if(i.x!=j.x) return i.x>j.x;//按x从大到小排序
    else return i.y>j.y;
}
执行

sort(a,a+10);

即可对a进行排序

2.用库函数实现快速排序:qsort

推荐文章:http://blog.csdn.net/eroswang/article/details/4075580


原文地址:https://www.cnblogs.com/cszlg/p/2910490.html