qsort快速排序

来源:互联网 发布:问道登陆器源码 编辑:程序博客网 时间:2024/06/06 02:25

         qsortC语言自带的快速排序,今天来玩玩,直接看代码。

参数:1.待排序数组首地址

           2.数组中待排序元素数量

           3.各元素的占用空间大小

           4.指向函数的指针,用于确定排序的顺序

#include <stdio.h>  #include<string>//qsort排序结构体typedef struct node{   char name[10];   char type[10];}Node;int compInc1(const void *a, const void *b){   Node *p1=(Node *)a;   Node *p2=(Node *)b;   return strcmp(p1->type,p2->type);}int compInc2(const void *a, const void *b){   Node *p1=(Node *)a;   Node *p2=(Node *)b;   return p1->type - p2->type;}int main()  {  //指向结构体的指针    Node nodeTest[4]={{"m","1"},   {"a","3"},{"p","12"},{"n","24"}};int len=4;qsort(nodeTest,len,sizeof(Node),compInc2);int i;    for(i = 0; i < 4; i++)      {          printf("name=%s,type=%s\n", nodeTest[i].name,nodeTest[i].type);    }     return 0;  }  
compInc1和compInc2确定排序顺序。

compInc1:

name=m,type=1

name=p,type=12

name=n,type=24

name=a,type=3


compInc2:

name=m,type=1

name=a,type=3

name=p,type=12

name=n,type=24

compInc1是通过字符串大小进行排序的,compInc2是通过所指数的大小进行排序的。但是type是字符串,字符串能相减吗?其实这里是指针相减