zoukankan      html  css  js  c++  java
  • C++ 中的sort排序用法

     

    C++ 中的sort排序用法

    C中的qsort()采用的是快排算法,C++的sort()则是改进的快排算法。两者的时间复杂度都是n*(logn),但是实际应用中,sort()一般要快些,建议使用sort()。

    STL中自带了快速排序,对给定区间进行排序,包含在头文件<algorithm>中 ,语法描述为 sort(begin,end)

     

    #include <algorithm>
    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函数是默认升序排列,如果想降序,如下操作:

    #include <iostream>
    #include <algorithm>
    bool cmp(int a,int b)
    {
     return a>b//降序 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,cmp);//这里是区别哈   for(i=0;i<20;i++)     cout<<a[i]<<endl;   return 0; }
     

    想要对结构体的某一元素排序,还需要对上述的cmp函数重新传参

  • 相关阅读:
    Pytorch 入门之Siamese网络
    Pytorch 之 backward
    非极大值抑制(NMS)
    Apriori 算法python实现
    canny 算子python实现
    转载
    ubuntu 安装lightgbm
    OneHotEncoder独热编码和 LabelEncoder标签编码
    Adroid—— DVM
    PHP——做服务
  • 原文地址:https://www.cnblogs.com/yusuph/p/13331650.html
Copyright © 2011-2022 走看看