From 4941b97bba50d2c29ea48b323eccb8db9e253555 Mon Sep 17 00:00:00 2001 From: flykhan Date: Wed, 26 Jul 2023 23:07:31 +0800 Subject: [PATCH] =?UTF-8?q?quick=20sort(=E5=BF=AB=E9=80=9F=E6=8E=92?= =?UTF-8?q?=E5=BA=8F),=20=E5=B9=B3=E5=9D=87=E6=97=B6=E9=97=B4=E5=A4=8D?= =?UTF-8?q?=E6=9D=82=E5=BA=A6=20O(NlogN)=20->=20=E6=9C=80=E5=B7=AE?= =?UTF-8?q?=E6=97=B6=E9=97=B4=E5=A4=8D=E6=9D=82=E5=BA=A6=20O(N^2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- chapter1/quick_sort.c | 58 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 chapter1/quick_sort.c diff --git a/chapter1/quick_sort.c b/chapter1/quick_sort.c new file mode 100644 index 0000000..7dd0150 --- /dev/null +++ b/chapter1/quick_sort.c @@ -0,0 +1,58 @@ +// 快速排序 +// 平均时间复杂度: O(NlogN) - 最差时间复杂度: O(N^2) +#include +int a[101], n; // 定义全局变量,这两个变量需要在子函数中使用 + +void quicksort(int left, int right) +{ + int i, j, t, temp; + if (left > right) + return; + + temp = a[left]; // temp 中存的就是基准数 + i = left; + j = right; + while (i != j) + { + // 顺序很重要,要先从右往左找 + while (a[j] >= temp && i < j) + j--; + + // 在从左往右找 + while (a[i] <= temp && i < j) + i++; + + if (i < j) + { + t = a[i]; + a[i] = a[j]; + a[j] = t; + } + } + + // 最终将基准数归位 (交换基准数和 i 位置当前值) + a[left] = a[i]; + a[i] = temp; // temp 在上面有定义 + + quicksort(left, i - 1); // 继续处理左边的,这里是一个递归的过程 + quicksort(i + 1, right); // 继续处理右边的 + return; +} + +int main() +{ + int i, j; + // 读入数据 + scanf("%d", &n); + for (i = 1; i <= n; i++) + scanf("%d", &a[i]); + + quicksort(1, n); // 快速排序调用 + + // 输出排序后的结果 + for (i = 1; i <= n; i++) + printf("%d ", a[i]); + printf("\n"); + + return 0; +} \ No newline at end of file