• 排序算法积累(2)----sort排序


    转载:http://blog.csdn.net/sunshangjin/article/details/40296357

    想起来自己天天排序排序,冒泡啊,二分查找啊,结果在STL中就自带了排序函数sort,qsort,总算把自己解脱了~

    std::sort()函数的功能很强大,且可以对类,结构体等元素进行排序。C++sort参考手册

    所以自己总结了一下,首先看sort函数见下表:参考csdn

    函数名功能描述
    sort 对给定区间所有元素进行排序
    stable_sort 对给定区间所有元素进行稳定排序
    partial_sort 对给定区间所有元素部分排序
    partial_sort_copy 对给定区间复制并排序
    nth_element 找出给定区间的某个位置对应的元素
    is_sorted 判断一个区间是否已经排好序
    partition 使得符合某个条件的元素放在前面
    stable_partition 相对稳定的使得符合某个条件的元素放在前面

    要使用此函数只需用#include <algorithm> 

    sort即可使用,语法描述为:

    sort(begin,end),表示一个范围,例如:

    [cpp] view plain copy
     
    1. #include<iostream>  
    2. #include<algorithm>  
    3. #include<string>  
    4. using namespace std;  
    5. int main()  
    6. {  
    7.     int a[10]={9,12,17,30,50,20,60,65,4,49};  
    8.     sort(a,a+10);  
    9.     for(int i=0;i<10;i++)  
    10.         cout<<a[i]<<' ';  
    11.     cout<<endl;  
    12.     return 0;  
    13. }  

    2)自己编写一个比较函数来实现,接着调用三个参数的sort:sort(begin,end,compare)就成了。对于list容器,这个方法也适用,把compare作为sort的参数就可以了,即:sort(compare).

    [cpp] view plain copy
     
    1. #include<iostream>  
    2. #include<algorithm>  
    3. #include<string>  
    4. using namespace std;  
    5. bool compare(int a,int b)  
    6. {  
    7.     return a<b;   //默认升序排列,如果改为return a>b,则为降序  
    8. }  
    9. bool compare_decrease(int a,int b)  
    10. {  
    11.     return a>b;   //从大到小的排列  
    12. }  
    13. int main()  
    14. {  
    15.     int a[10]={9,12,17,30,50,20,60,65,4,49};  
    16.     sort(a,a+10);  
    17.     for(int i=0;i<10;i++)  
    18.         cout<<a[i]<<' ';  
    19.     cout<<endl;  
    20.     sort(a,a+10,compare_decrease);  
    21.     for(int i=0;i<10;i++)  
    22.         cout<<a[i]<<' ';  
    23.     cout<<endl;  
    24.     return 0;  
    25. }  

    PS:一般不用于字符串排序

  • 相关阅读:
    typescript接口初识
    TypeScript如何创建一个工程
    typescript开发入门
    node.js下面创建一个express应用的几条命令【乱序版】
    一天入门typescript
    Node.js快速创建一个Express应用的几个步骤
    数据结构--栈
    数据结构--单链表
    数据结构--二叉树
    数据结构--树
  • 原文地址:https://www.cnblogs.com/panlangen/p/7854060.html
Copyright © 2020-2023  润新知