C 库函数 ------ qsort()

头文件:

#include <stdlib.h>

声明:

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))

参数:

base: 指向要排序的数组的指针,可以是一维数组,也可以是二位数组

nitems:数组中前多少个元素需要排序

size:每个元素所占字节数

compar:比较函数

实例1:

    一个字符串数组:*str[MAX],假设里面现在保存了n个字符串了。
    首先要正确理解什么是字符串数组,简单的说,可以理解成它就是一个数组,只不过其中的元素是一串字符串,而访问这些字符串,得用指针,也就是它们的地址,比如*name[]={"james","henry"},那么访问其中的字符串就是name[0],name[1]...这里就有个容易混淆的地方了,对于字符串数组,那么每个元素的大小到底是多少呢?对name[0]来说,到底是字符串“james”的长度5,还是char*的大小4呢?答案应该是4,因为字符串数组里面保存的是各个字符串的指针,所以回到上面所说的第二点注意,用qsort的时候应该要传sizeof(char *);
   第二,编写compar函数比较字符串有地方要注意:
       不能把strcmp本身传给qsort,即不能写strcmp(p,q),因为形参是const void*类型,同理,写成strcmp((char *)p, (char *)q);也是无效的;正确的写法应该是:strcmp(*(char **)p, *(char **)q);先强制转换成char**,在用*减少一层间接寻址操作:
int compar_words(const void *p, const void *q)
{
    return strcmp(*(char **)p, *(char **)q);
}

对于上面的应用,最后使用qsort应该是这样:

qsort(str, n, sizeof(char *), compar);

实例2:

如果是一个是一个二位数组,不是字符串数组,得按以下写法

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int func(const void *a, const void *b){
    return strcmp((char *)a, (char *)b);
}
int main(void){
    
    int n;
    char str[1000][200];
    
    scanf("%d", &n);

    for(int i=0; i<n; i++){
        scanf("%s", str[i]);
    }
    qsort(str, n, 200, func);
    
    for(int i=0; i<n; i++){
        printf("%s
", str[i]);
    }
    return 0;
}
 

实例3:

#include <stdio.h>
#include <stdlib.h>

int values[] = { 88, 56, 100, 2, 25 };

int cmpfunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

int main()
{
   int n;

   printf("排序之前的列表:
");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values[n]);
   }

   qsort(values, 5, sizeof(int), cmpfunc);

   printf("
排序之后的列表:
");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values[n]);
   }
 
  return(0);
}

输出:

排序之前的列表:
88 56 100 2 25 
排序之后的列表:
2 25 56 88 100
原文地址:https://www.cnblogs.com/god-of-death/p/14767932.html