C语言快速排序函数用法(qsort)

所属分类: 软件编程 / C 语言 阅读数: 45
收藏 0 赞 0 分享

本文实例为大家分享了C语言快排函数用法,供大家参考,具体内容如下

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
  int id;
  char name[12];
  char sex;
};
int compare(const void* a,const void* b)//基本数据类型排序
{
  return *(char*)a-*(char*)b;//从小到大
    //取值//强转为相应类型的指针!!
}
int compare_struct(const void* a,const void* b)
{
  return (*(struct student*)a).id-((struct student*)b)->id;
         //注意优先级诶!//否则报错在非结构体中。。。
}
int compare_struct_duoji(const void* a,const void* b)//多级排序
{
  struct student student_a=*(struct student*)a;
  struct student student_b=*(struct student*)b;

  if(student_a.id==student_b.id)
  {
    return student_a.sex-student_b.sex;
  }
  else
  {
    return student_a.id-student_b.id;
  }
}
void main()
{
//*************char型*************
  char a[5]="hello";
  qsort(a,5,sizeof(a[0]),compare);
      //元素个数//元素大小//函数指针
  int i;
  for(i=0;i<5;i++)
      printf("%c ",a[i]);
  printf("\n");

//************struct型************
  struct student e[4]={{100,"chen",'m'},{100,"li",'f'}, \
             {70,"wang",'f'},{100,"zhang",'m'}};
  qsort(e,4,sizeof(e[1]),compare_struct_duoji);

  for(i=0;i<4;i++)
      printf("%d %s %c\n",e[i].id,e[i].name,e[i].sex);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

C 语言基础教程(我的C之旅开始了)[三]

C 语言基础教程(我的C之旅开始了)[三]
收藏 0 赞 0 分享

C 语言基础教程(我的C之旅开始了)[四]

C 语言基础教程(我的C之旅开始了)[四]
收藏 0 赞 0 分享

C 语言基础教程(我的C之旅开始了)[五]

C 语言基础教程(我的C之旅开始了)[五]
收藏 0 赞 0 分享

C 语言基础教程(我的C之旅开始了)[六]

C 语言基础教程(我的C之旅开始了)[六]
收藏 0 赞 0 分享

C 语言基础教程(我的C之旅开始了)[七]

C 语言基础教程(我的C之旅开始了)[七]
收藏 0 赞 0 分享

C 语言基础教程(我的C之旅开始了)[八]

C 语言基础教程(我的C之旅开始了)[八]
收藏 0 赞 0 分享

C 语言基础教程(我的C之旅开始了)[九]

C 语言基础教程(我的C之旅开始了)[九]
收藏 0 赞 0 分享

C 语言基础教程(我的C之旅开始了)[十]

C 语言基础教程(我的C之旅开始了)[十]
收藏 0 赞 0 分享

tc编译的dos程序和vc编译的win32控制台程序的异同

tc编译的dos程序和vc编译的win32控制台程序的异同
收藏 0 赞 0 分享

C语言WinSock学习笔记第1/2页

本篇文章主要介绍了C语言WinSock学习笔记,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多