qsort使用方法
时间: 2025-05-22 09:27:20 浏览: 35
### C语言中qsort函数的用法
`qsort()` 是C标准库 `<stdlib.h>` 中的一个通用排序函数,适用于各种数据类型的数组排序。它的功能强大且灵活,主要依赖于用户自定义的比较函数来决定如何排序。
#### 函数原型
以下是 `qsort()` 的函数声明:
```c
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
```
- **`base`**: 指向要排序的数组首地址。
- **`nmemb`**: 数组中元素的数量。
- **`size`**: 单个元素的大小(以字节为单位),通常使用 `sizeof(type)` 来计算。
- **`compar`**: 用户定义的比较函数指针,用于指定排序逻辑[^1]。
#### 自定义比较函数
比较函数的形式如下:
```c
int compar(const void *a, const void *b);
```
返回值的意义:
- 如果第一个参数小于第二个参数,则返回负数;
- 如果相等则返回零;
- 如果大于则返回正数[^4]。
下面是一些具体的例子展示 `qsort()` 的实际应用:
---
### 示例 1:整型数组排序
这是一个典型的升序排列整型数组的例子。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义比较函数
int compare_int(const void *a, const void *b) {
return (*(int *)a - *(int *)b); // 升序排列
}
int main() {
int arr[] = {5, 8, 3, 9, 1};
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(int), compare_int);
for (int i = 0; i < n; ++i) {
printf("%d ", arr[i]);
}
return 0;
}
```
此代码会输出按升序排列的结果:`1 3 5 8 9`[^2]。
---
### 示例 2:字符串数组排序
对于字符串数组,可以通过调用 `strcmp()` 实现字母顺序排序。
```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 字符串比较函数
int compare_str(const void *a, const void *b) {
return strcmp(*(char **)a, *(char **)b);
}
int main() {
char str_arr[][10] = {"banana", "apple", "orange"};
char *str_ptr_arr[3];
for (int i = 0; i < 3; ++i) {
str_ptr_arr[i] = str_arr[i]; // 创建指向字符串的指针数组
}
qsort(str_ptr_arr, 3, sizeof(char *), compare_str);
for (int i = 0; i < 3; ++i) {
printf("%s\n", str_ptr_arr[i]);
}
return 0;
}
```
这段代码将输出按字典顺序排列的字符串列表:
`apple banana orange`[^3]。
---
### 示例 3:字符数组排序
如果需要对单个字符组成的数组进行排序,可以直接操作字符本身。
```c
#include <stdio.h>
#include <stdlib.h>
// 对字符数组进行比较
int compare_char(const void *a, const void *b) {
return (*(char *)a - *(char *)b);
}
int main() {
char ch_arr[] = {'z', 'a', 'm', 'k'};
int n = sizeof(ch_arr) / sizeof(ch_arr[0]) - 1;
qsort(ch_arr, n, sizeof(char), compare_char);
for (int i = 0; i < n; ++i) {
printf("%c ", ch_arr[i]);
}
return 0;
}
```
最终结果将是:`a k m z`[^3]。
---
### 示例 4:结构体数组排序
假设有一个学生记录表,可以根据学生的成绩对学生进行降序排序。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Student {
char name[20];
float score;
} Student;
// 结构体成员比较函数
int compare_student(const void *a, const void *b) {
Student *student_a = (Student *)a;
Student *student_b = (Student *)b;
if (student_a->score > student_b->score) return -1;
if (student_a->score < student_b->score) return 1;
return 0;
}
int main() {
Student students[] = {{"Alice", 78.5}, {"Bob", 89.0}, {"Charlie", 67.3}};
int n = sizeof(students) / sizeof(Student);
qsort(students, n, sizeof(Student), compare_student);
for (int i = 0; i < n; ++i) {
printf("Name: %s, Score: %.1f\n", students[i].name, students[i].score);
}
return 0;
}
```
这将显示学生成绩从高到低的排名[^3]。
---
### 总结
`qsort()` 提供了一种高效而灵活的方式来处理不同数据类型的排序需求。通过合理设计比较函数,可以满足几乎所有的排序场景。
阅读全文
相关推荐















