用c语言写一个快速排序
时间: 2024-01-15 12:40:32 浏览: 15
以下是使用 C 语言编写的快速排序示例代码:
```c
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}
void quicksort(int arr[], int low, int high) {
if (low < high) {
int pivot = partition(arr, low, high);
quicksort(arr, low, pivot - 1);
quicksort(arr, pivot + 1, high);
}
}
int main() {
int arr[] = {5, 3, 9, 1, 7, 2, 8, 4, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
quicksort(arr, 0, n - 1);
printf("\nSorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出结果:
```
Original array: 5 3 9 1 7 2 8 4 6
Sorted array: 1 2 3 4 5 6 7 8 9
```
在这个示例中,我们定义了三个函数:
- `swap()` 函数:用于交换两个变量的值。
- `partition()` 函数:用于将数组分为两部分,并返回枢轴元素的下标。
- `quicksort()` 函数:用于递归地对子数组排序。
程序首先打印原始数组,然后调用 `quicksort()` 函数对数组进行排序,并打印排序后的数组。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)