请帮我用C++写一段快速排序的代码
时间: 2023-03-30 16:02:32 浏览: 89
快速排序法的C++代码
以下是快速排序的 C 代码:
```
#include <stdio.h>
void quicksort(int arr[], int left, int right) {
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
/* partition */
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
/* recursion */
if (left < j)
quicksort(arr, left, j);
if (i < right)
quicksort(arr, i, right);
}
int main() {
int arr[] = {5, 2, 8, 3, 1, 6, 9, 7, 4};
int n = sizeof(arr) / sizeof(arr[]);
int i;
printf("Before sorting:\n");
for (i = ; i < n; i++)
printf("%d ", arr[i]);
quicksort(arr, , n - 1);
printf("\nAfter sorting:\n");
for (i = ; i < n; i++)
printf("%d ", arr[i]);
return ;
}
```
阅读全文