c库qsort的使用

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

void printArray(int* array, int length)
{
    for (int i = 0; i < length; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
}

// 定义比较函数,以 int 为例
int compare(const void* a, const void* b)
{
    return *(int*)a - *(int*)b;
}

// void qsort(void *, size_t, size_t, int (*)(const void *, const void *))
// 参数依次为:
//   要排序数组的指针
//   元素的个数
//   每个元素的大小
//   比较函数的指针

int main()
{
    int array[] = { -4, 13, 1, 8, -5, 0 };
    printArray(array, 6);
    qsort(array, 6, sizeof(int), compare);
    printArray(array, 6);
    return 0;
}

运行结果如下:

猜你喜欢

转载自www.cnblogs.com/tongyishu/p/12221262.html