用c语言快速排序算法的实现。任意输入20个整数,对这20个整数进行快速排序。要求使用末元素作为划分基准。
时间: 2024-05-14 17:15:03 浏览: 84
```
#include <stdio.h>
void quick_sort(int arr[], int left, int right);
int partition(int arr[], int left, int right);
int main() {
int arr[20];
printf("请输入20个整数:\n");
for (int i = 0; i < 20; i++) {
scanf("%d", &arr[i]);
}
quick_sort(arr, 0, 19);
printf("排序后的结果为:\n");
for (int i = 0; i < 20; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
void quick_sort(int arr[], int left, int right) {
if (left < right) {
int pivot_index = partition(arr, left, right);
quick_sort(arr, left, pivot_index - 1);
quick_sort(arr, pivot_index + 1, right);
}
}
int partition(int arr[], int left, int right) {
int pivot = arr[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[right];
arr[right] = temp;
return i + 1;
}
```
运行结果:
```
请输入20个整数:
5 9 2 8 1 0 7 4 6 3 19 11 18 16 14 10 12 15 13 17
排序后的结果为:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
```
阅读全文