C语言中排序函数的用法

来源:互联网 发布:2016淘宝客导购源码 编辑:程序博客网 时间:2024/06/15 08:52

第一篇blog啊还有点小激动~学生党一枚,就记录一下学习心得,然后每天进步吧。好哒切入正题~
C语言中没有预置的sort函数,下学期还是好好学下C++吧orz。所以用到排序的时候,嗯见下文。
一、自己编吧
最简单的冒泡排序:

#include <stdio.h>#include <stdlib.h>int main(){    int n, i, a[100], temp, j;    scanf("%d", &n);    for(i = 0; i < n; i++)        scanf("%d", &a[i]);    for(i = 0; i < n - 1; i++)        for(j = 0; j < n - i -1; j++)    {        if(a[j] > a[j+1])        {            temp = a[j];            a[j] = a[j+1];            a[j+1] = temp;        }    }    for(i = 0; i < n; i++)        printf("%d ",a[i]);    return 0;}

然后各种归并排序、快排啊什么的,注意一下时间复杂度。
二、C语言自有的qsort函数
功 能: 快速排序
头文件:stdlib.h
原型: void qsort(void base,int nelem,int width,int (*fcmp)(const void ,const void *));
参数:
1 待排序数组首地址
2 数组中待排序元素数量
3 各元素的占用空间大小
4 指向函数的指针,用于确定排序的顺序
PS:要自己写比较函数,从而实现递增或者递减。
下面介绍几种比较函数的写法:
1.对int类型数组排序

int m[100];  Sample:  int comp (const void *a, const void *b )   {   return *(int *)a - *(int *)b;   }  qsort(m,100,sizeof(m[0]),comp);

2.对char类型数组排序

char m[100];  Sample:  int comp( const void *a , const void *b )   {   return *(char *)a - *(int *)b;   }  qsort(m,100,sizeof(m[0]),comp);  

3.对double类型数组排序(特别要注意)

double m[100];  int comp( const void *a , const void *b )   {   return *(double *)a > *(double *)b ? 1 : -1;   }  qsort(m,100,sizeof(m[0]),comp);  

4.对结构体一级排序

struct Price  {   double data;   int other;   }m[100]  //按照data的值从小到大将结构体排序,关于结构体内的排序关键数据data的类型可以很多种,参考上面的例子写  int comp( const void *a ,const void *b)   {   return ((Price *)a)->data - ((Price *)b)->data ;   }  qsort(m,100,sizeof(m[0]),comp); 

5.对结构体排序

struct In {    int x;    int y; }m[100]; //按照x从小到大排序,当x相等时按照y从大到小排序 int comp( const void *a , const void *b ) {     struct In *c = (struct In *)a;     struct In *d = (struct In *)b;     if(c->x != d->x) return c->x - d->x;     else return d->y - c->y; } qsort(m,100,sizeof(m[0]),comp); 

6.对字符串进行排序

struct Price   {   int data;   char str[100];   }m[100];  //按照结构体中字符串str的字典顺序排序  int comp ( const void *a , const void *b )   {   return strcmp( ((Price *)a)->str , ((Price *)b)->str );   }  qsort(m,100,sizeof(m[0]),comp);

以下是应用qsort函数的一个例子:

#include <stdio.h>#include <stdlib.h>int compin(const void *a,const void *b)//int型递增{    return *(int *)a - *(int *)b;}int compde(const void *a,const void *b)//double型递减{    return *(double *)a < *(double *)b ? 1 : -1;}int main(){    int a[100],i,n;    double b[100];    scanf("%d",&n);    for(i = 0; i < n; i++)        scanf("%d",&a[i]);    for(i = 0; i < n; i++)        scanf("%lf",&b[i]);    qsort(a,n,sizeof(a[0]),compin);//调用qsort函数快排    printf("递增:");    for(i = 0; i < n; i++)        printf("%d ",a[i]);    printf("\n");    printf("递减:");    qsort(b,n,sizeof(b[0]),compde);    for(i = 0; i < n; i++)        printf("%f ",b[i]);    printf("\n");    return 0;}
0 0
原创粉丝点击