#include stdioh#include stringhvoid swapint a int b int tmp = a; a = b; b = tmp;void Q_sortint arr int begin int end if begin end return; int left = begin; int right
#include <stdio.h> #include <string.h>
// 交换a和b的值 void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; }
// 快速排序 void Q_sort(int arr[], int begin, int end) { // 递归结束条件,当begin>end时 if (begin > end) { return; } // 定义左右指针和关键字位置 int left = begin; int right = end; int key = begin;
// 开始排序
while (begin < end)
{
// 从右往左找比关键字小的数
while (arr[end] >= arr[key] && begin < end)
{
--end;
}
// 从左往右找比关键字大的数
while (arr[begin] <= arr[key] && begin < end)
{
++begin;
}
// 交换begin和end位置的数
swap(&arr[begin], &arr[end]);
}
// 将关键字和end位置的数交换
swap(&arr[key], &arr[end]);
// 更新关键字位置
key = end;
// 分治递归
Q_sort(arr, left, key-1);
Q_sort(arr, key+1, right);
}
int main() { // 待排序数组 int arr[] = {6, 2, 8, 1, 9, 4, 3, 7, 5}; int n = sizeof(arr) / sizeof(arr[0]); // 调用快速排序函数 Q_sort(arr, 0, n-1); // 输出排序后的结果 for (int i = 0; i < n; ++i) { printf("%d ", arr[i]); } printf("\n"); return 0;
原文地址: http://www.cveoy.top/t/topic/exCG 著作权归作者所有。请勿转载和采集!