C语言sort函数如何使用

https://zhidao.baidu.com/question/1754076342544723828.html

c语言和c++中,对于sort函数的使用,不同。c语言中没有预置的sort函数,如果在c语言中,要调用sort函数,就需要自定义一个用于排序的函数,或者使用c语言自有的qsort函数,其头文件为stdlib.h。

1、自定义排序功能

如下,为整数型从小到大排序

[html] view plain copy
  1.   
[plain] view plain copy
  1. void sort(int *a, int l)//a为数组地址,l为数组长度。  
  2. {  
  3.     int i, j;  
  4.     int v;  
  5.     //排序主体  
  6.     for(i = 0; i < l - 1; i ++)  
  7.         for(j = i+1; j < l; j ++)  
  8.         {  
  9.             if(a[i] > a[j])//如前面的比后面的大,则交换。  
  10.             {  
  11.                 v = a[i];  
  12.                 a[i] = a[j];  
  13.                 a[j] = v;  
  14.             }  
  15.         }  
  16. }  

2、自有的qsort函数 

[html] view plain copy
  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. int comp(const void*a,const void*b)//用来做比较的函数。  
  4. {  
  5.     return *(int*)a-*(int*)b;  
  6. }  
  7. int main()  
  8. {  
  9.     int a[10] = {2,4,1,5,5,3,7,4,1,5};//乱序的数组。  
  10.     int i;  
  11.     qsort(a,n,sizeof(int),comp);//调用qsort排序  
  12.     for(i=0;i<10;i++)//输出排序后的数组  
  13.     {  
  14.         printf("%d\t",array[i]);  
  15.     }  
  16.     return 0;  
  17. }  

c++语言中,对于排序包含有sort()函数及qsort函数。
其中sort函数用法为:对数组进行排序,其头文件为algorithm.h,形式为sort(数组名,数组名+数组长度),默认为升序,复杂度为nlog(n);sort(begin,end,less<数据类型>()),升序;sort(begin,end,greater<d 数据类型>()),降序;sort(数组名,数组名+数组长度,less<数组数据类型()>),升序;sort(数组名,数组名+数组长度,greater<数组数据类型>()),降序。
qsort()函数用法为,qsort(数组名,元素个数,元素占用的空间(sizeof),比较函数),其头文件为iostream。
  1. #include<iostream>//  
  2. #include<stdio.h>  
  3. #include<string>  
  4. #include<algorithm>  
  5. #include<cstdlib>  
  6. using namespace std;  
  7. int main(int argc,char *argv[])  
  8. {  
  9.     int data[10];  
  10.     for(int i=0;i<5;i++)  
  11.         cin>>data[i];  
  12.     sort(data,data+5);  
  13.     for(int j=0;j<5;j++)  
  14.         cout<<data[j]<<endl;  
  15.     return 0;  
  16. }  


  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值