快速排序C
时间: 2023-06-30 21:27:10 浏览: 23
好的,这是一个基于递归实现的快速排序的 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 pi = partition(arr, low, high);
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
}
int main() {
int arr[] = { 10, 7, 8, 9, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
quicksort(arr, 0, n - 1);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
这段代码中,`swap()` 函数用于交换两个数的位置,`partition()` 函数用于选择一个 pivot 元素,将小于 pivot 的元素放在左边,大于等于 pivot 的元素放在右边,并返回 pivot 的位置。`quicksort()` 函数是递归地对左右两侧的子数组进行排序,直到子数组长度为 1 时停止递归。最后在 `main()` 函数中调用 `quicksort()` 函数。