转载:https://blog.csdn/w_linux/article/details/76222112
 

用法

1、sort函数可以三个参数也可以两个参数,必须的头文件#include < algorithm>和using namespace std; 

2、它使用的排序方法是类似于快排的方法,时间复杂度为n*log2(n)

3、Sort函数有三个参数:(第三个参数可不写)

(1)第一个是要排序的数组的起始地址。

(2)第二个是结束的地址(最后一位要排序的地址)

(3)第三个参数是排序的方法,可以是「降序」也可是「升序」,

         还可以不写第三个参数,此时默认的排序方法是「升序」排序。

两个参数用法

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
 int a[20]={2,4,1,23,5,76,0,43,24,65},i;
 for(i=0;i<20;i++)
  cout<<a[i]<<endl;
 sort(a,a+20);
 for(i=0;i<20;i++)
 cout<<a[i]<<endl;
 return 0;
}

输出结果是升序排列。(两个参数的sort默认升序排序)

三个参数用法

形式:sort ( arr, arr+SIZE, compare ) 或者 sort ( begin, end, compare )

可以通过编写compare函数改变Sort的排序规则。

降序

#include <iostream>
#include <algorithm>

using namespace std;

bool compare(int a,int b)
{
  return a>b; //降序排列,如果改为return a<b,则为升序
}

int main()
{
  int a[20]={2,4,1,23,5,76,0,43,24,65},i;
  for(i=0;i<20;i++)
  cout<<a[i]<<endl;
  sort(a,a+20,compare);
  for(i=0;i<20;i++)
  cout<<a[i]<<endl;
  return 0;
}

绝对值排序

#include <cmath>

bool compare(int a, int b)

{

    return abs(a) > abs(b);

}

结构体排序

自己写比较算子函数的写法
 

struct node
{
    int u, v, w;
};


bool cmp(node a, node b)
{
    if(a.w < b.w ) //按照w的值进行的是:升序排列 !
        return true;
    else
        return false;
}


//还可以这样写
bool cmp(node a, node b)
{
    return a.w<b.w; //升序
}

当然cmp函数也可以写的稍微复杂点,也就是说,

按照优先级对结构体的多个成员按照某种规则排序,就像刚才上面写的

//先按照w的值升序排序,如果w相等,再按照v的值升序排序

bool cmp(node a, node b)

{

    if(a.w==b.w)
        return a.v<b.v;
    else
        return a.w<b.w;
}

//或者这样写

bool cmp(node a, node b)
{
    if(a.w<b.w)
        return true;
    if(a.w==b.w && a.v<b.v )
        return true;
    return false;
}

 

更多推荐

C++ sort 排序函数使用方法