帮我写一个分治法实现快速排序的C++程序
时间: 2023-03-28 16:00:24 浏览: 119
好的,我可以帮您写一个分治法实现快速排序的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, 4, 1, 9, 6, 3, 7};
int n = sizeof(arr) / sizeof(arr[]);
int i;
printf("Original array: ");
for (i = ; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
quickSort(arr, , n - 1);
printf("Sorted array: ");
for (i = ; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return ;
}
希望对您有所帮助!
阅读全文