温馨提示×

c语言sort函数怎么使用

小亿
331
2023-11-07 11:54:27
栏目: 编程语言

C语言中的sort函数用于对数组进行排序。该函数位于stdlib.h头文件中。

sort函数的使用方法如下:

  1. 首先,需要创建一个用于排序的数组。
  2. 然后,需要定义一个比较函数,用于比较两个数组元素的大小关系。
  3. 最后,调用sort函数进行排序。

下面是一个示例程序,演示了如何使用sort函数对一个整数数组进行排序:

#include <stdio.h> #include <stdlib.h> // 比较函数,用于比较两个整数的大小关系 int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int main() { int arr[] = {5, 3, 8, 1, 2}; int n = sizeof(arr) / sizeof(arr[0]); // 调用sort函数对数组进行排序 qsort(arr, n, sizeof(int), compare); // 打印排序后的数组 for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; } 

输出结果:

1 2 3 5 8 

在上述示例程序中,compare函数用于比较两个整数的大小关系。qsort函数用于对数组进行排序,参数依次为待排序的数组、数组元素个数、每个元素的大小、比较函数。最后,使用循环打印排序后的数组。

0