C语言sort函数如何使用

来源:互联网 发布:matlab数据毛刺 编辑:程序博客网 时间:2024/05/24 00:10

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

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

1、自定义排序功能

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

void sort(int *a, int l)//a为数组地址,l为数组长度。{    int i, j;    int v;    //排序主体    for(i = 0; i < l - 1; i ++)        for(j = i+1; j < l; j ++)        {            if(a[i] > a[j])//如前面的比后面的大,则交换。            {                v = a[i];                a[i] = a[j];                a[j] = v;            }        }}

2、自有的qsort函数

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

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。
#include<iostream>//#include<stdio.h>#include<string>#include<algorithm>#include<cstdlib>using namespace std;int main(int argc,char *argv[]){int data[10];for(int i=0;i<5;i++)cin>>data[i];sort(data,data+5);for(int j=0;j<5;j++)cout<<data[j]<<endl;return 0;}



原创粉丝点击