0%

C语言库函数之qsort

文章时效性提示

本文发布于 511 天前,部分信息可能已经改变,请注意甄别。

qsort,是C语言库函数,用于排序,使用这个库函数需要#include <stdlib.h>头文件
语法:
void qsort(void* base,size_t num,size_t width,int( *cmp)(const void *e1,const void *e2));

  • void* base是指要排序的数组的首元素位置
  • size_t num是指数组的元素个数
  • size_t width是指数组内每个元素的大小,单位是字节
  • int( *cmp)(const void *e1,const void *e2)是函数指针,比较两个元素用的函数的地址,此函数需自己实现。

参见:指针详解

关于void*:

  • void* 类型的指针可以接收任意类型的地址
  • 对于void*类型的指针不能进行解引用操作
  • void*类型的指针也不能进行加减整数的运算

使用qsort对整型数组排序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <stdlib.h>
int cmp_int(const void* e1,const void* e2)
{
    //比较函数,比较两个整型值
    return *(int*)e1 - *(int*)e2;
}
int main() {
    int arr[10] = {9,8,7,6,5,4,3,2,1,0};
    int sz = sizeof(arr)/sizeof(arr[0]);
    qsort(arr,sz,sizeof(arr[0]),cmp_int);
    int i = 0;
    for (i=0; i<sz; i++) {
        printf("%d ",arr[i]);
    }
    return 0;

使用qsort函数对arr数组排序,打印的结果是0 1 2 3 4 5 6 7 8 9


使用qsort对float型数组排序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <stdlib.h>
int cmp_float(const void* e1,const void* e2)
{
    if (*(float*)e1 == *(float*)e2)
    {
        return 0;
    }else if (*(float*)e1 > *(float*)e2)
    {
        return 1;
    }else
    {
        return -1;
    }
}
int main() {
    float f[10] = {9.0,8.0,7.0,6.0,5.0,4.0,3.0,2.0,1.0,0.0};
    int sz = sizeof(f)/sizeof(f[0]);
    qsort(f,sz,sizeof(f[0]),cmp_float);
    int i = 0;
    for (i=0; i<sz; i++) {
        printf("%f ",f[i]);
    }
    return 0;
}

使用qsort对float型数组排序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <stdlib.h>
struct Stu
{
    char name[20];
    int age;
};
int cmp_stu_by_age(const void* e1,const void* e2)
{
    return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;
}

int cmp_stu_by_name(const void* e1,const void* e2)
{
    //比较名字,也就是比较字符串,不能直接用大于、小于、等于比较、应该用strcmp函数
    return strcmp(((struct Stu*)e1)->name,((struct Stu*)e2)->name);
}

int main() {
    struct Stu s[3] = {{"zhangsan",20},{"lisi",25},{"wangwu",50}};//结构体数组
    int sz = sizeof(s)/sizeof(s[0]);
    qsort(s,sz,sizeof(s[0]),cmp_stu_by_age);
    return 0;
}