c语言数组排序
时间: 2025-05-02 07:50:52 浏览: 13
### C语言中数组排序方法
在C语言中,可以采用多种方式对数组进行排序。以下是几种常见的排序方法及其代码示例。
#### 1. 冒泡排序 (Bubble Sort)
冒泡排序是一种简单的排序算法,通过重复地遍历待排序的列表,依次比较相邻的两个元素并按需交换它们的位置来工作。当一次完整的遍历不再发生任何交换时,则说明已经完成排序[^1]。
```c
void bubbleSort(int arr[], int len) {
int j, k;
for (j = 0; j < len - 1; j++) {
for (k = 0; k < len - j - 1; k++) {
if (arr[k] > arr[k + 1]) {
int temp = arr[k];
arr[k] = arr[k + 1];
arr[k + 1] = temp;
}
}
}
}
```
时间复杂度为O(n²),适用于小型数据集或教学用途。
---
#### 2. 计数排序 (Counting Sort)
计数排序是一种非基于比较的整数排序算法,其核心在于将输入的数据值转化为键存储在额外开辟的数组空间上。这种方法适合于一定范围内整数类型的排序[^2]。
```c
#include <stdio.h>
#define MAX_RANGE 100
void countingSort(int arr[], int size) {
int output[size];
int count[MAX_RANGE + 1] = {0};
// 统计每个值的数量
for (int i = 0; i < size; ++i) {
count[arr[i]]++;
}
// 更新count数组使其保存的是实际位置
for (int i = 1; i <= MAX_RANGE; ++i) {
count[i] += count[i - 1];
}
// 构建输出数组
for (int i = size - 1; i >= 0; --i) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
// 将结果复制回原始数组
for (int i = 0; i < size; ++i) {
arr[i] = output[i];
}
}
```
此算法的时间复杂度为O(n+k),其中k是输入数据的最大值。
---
#### 3. 简单选择排序 (Selection Sort)
简单选择排序的核心思想是从未排序部分选出最小(或者最大)的一个元素放到已排序序列的最后面[^3]。
```c
void selectionSort(int arr[], int n) {
int min_idx;
for (int i = 0; i < n - 1; i++) {
min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
if (min_idx != i) {
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
}
```
这种排序方法同样具有O(n²)的时间复杂度,在性能方面并不优于其他高级排序算法。
---
#### 4. 使用标准库函数 `qsort` 进行排序
除了手动编写排序逻辑外,还可以借助C标准库中的`qsort()`函数快速实现数组排序功能[^4]。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义比较函数
int compare(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int main() {
int array[] = {9, 7, 8, 5, 6};
int length = sizeof(array) / sizeof(array[0]);
qsort(array, length, sizeof(int), compare);
printf("Sorted Array: ");
for (int i = 0; i < length; i++) {
printf("%d ", array[i]);
}
return 0;
}
```
上述程序展示了如何调用`qsort`以及自定义比较器来进行升序排列操作。
---
阅读全文
相关推荐
















