#include <algorithm>中sort的一般用法

本文详细介绍了C++标准库中的sort函数用法,包括其时间复杂度为n*log2(n)的特点,以及如何通过不同参数设置实现升序或降序排序。提供了具体的代码示例,展示了如何使用自定义比较函数来针对基本类型和结构体成员变量进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、sort函数的时间复杂度为n*log2(n),执行效率较高。

  2、sort函数的形式为sort(first,end,method)//其中第三个参数可选。

  3、若为两个参数,则sort的排序默认是从小到大,见如下例子

[cpp]  view plain  copy
  1. #include<iostream>  
  2.   
  3. #include<algorithm>  
  4.   
  5. using namespace std;  
  6.   
  7. int main()  
  8.   
  9. {  
  10.   
  11.   int a[10]={9,6,3,8,5,2,7,4,1,0};  
  12.   
  13.   for(int i=0;i<10;i++)  
  14.   
  15.   cout<<a[i]<<endl;  
  16.   
  17.   sort(a,a+10); //可以看出,两个参数为均地址,a为起始,a+10为结束位置  
  18.   
  19.   for(int i=0;i<10;i++)  
  20.   
  21.   cout<<a[i]<<endl;  
  22.   
  23.   return 0;  
  24.   
  25. }  


 

4、若为三个参数,则需要写一个cmp函数(此名称cmp可变),用于判断是从小到大排序还是从大到小排序。   

  (1)需要排序的数组直接为int类型,则见如下例子(从大到小排序)

 

[cpp]  view plain  copy
  1. #include <algorithm>  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. bool com(int a,int b)  
  6.   
  7. {  
  8.   
  9.  return a>b;  
  10.   
  11. }  
  12.   
  13. int main()  
  14.   
  15. {  
  16.   
  17.  int a[10]={9,6,3,8,5,2,7,4,1,0};  
  18.   
  19.  for(int i=0;i<10;i++)  
  20.   
  21.  cout<<a[i]<<endl;  
  22.   
  23.  sort(a,a+10,com);//在这里就不需要对com函数传入参数  
  24.   
  25.  for(int i=0;i<10;i++)  
  26.   
  27.  cout<<a[i]<<endl;  
  28.   
  29.  return 0;  
  30.   
  31. }  


 

(2)如果想依照一个结构体内的一个int型的属性参数进行排序,则见如下例子(从大到小排列)

 

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <algorithm>  
  3.   
  4. using namespace std;  
  5.   
  6. struct node {  
  7.     int a;  
  8.     //.........  
  9.     //  
  10. };  
  11.   
  12. bool cmp(node x,node y)  
  13. {  
  14.      if(x.a != y.a)   
  15.          return (x.a > y.a);  
  16. }  
  17.   
  18. void main(void)  
  19. {  
  20.     int i;  
  21.     node N_t[5];  
  22.     for(i=0; i<5; i++)  
  23.     {  
  24.         cin>>N_t[i].a;  
  25.     }  
  26.     sort(N_t, N_t+5, cmp);  
  27.     for(i=0; i<5; i++)  
  28.     {  
  29.         cout<<N_t[i].a;  
  30.     }  
  31.       
  32. }     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值