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函数重新传参

  • 相关阅读:
    使用json-lib进行Java和JSON之间的转换
    ajax+json+java
    了解Json
    Ehcache RIM
    利用FreeMarker静态化网页
    Timer和TimerTask
    windows下memcache安装
    mac下安装YII
    php static 和self区别
    YII behaviors使用
  • 原文地址:https://www.cnblogs.com/yusuph/p/13331650.html
Copyright © 2011-2022 走看看