交换类排序

一、冒泡排序(Bubble Sort)

1.时间复杂度:O(n2)

2.空间复杂度:O(1)

 1 void BubbleSort(int* a, int num) {
 2     int i, j;
 3     for (i = 1; i <= num - 1; ++i) {
 4         for (j = 1; j <= num - i; ++j) {
 5             if (a[j] > a[j + 1]) {//前后交换
 6                 a[0] = a[j];
 7                 a[j] = a[j + 1];
 8                 a[j + 1] = a[0];
 9             }
10         }
11     }
12 }

二、快速排序(Quick Sort)

1.时间复杂度:O(nlog2n)

2.空间复杂度:O(log2n)

3.实现:

 1 int Patition(int* a, int low, int high) {
 2     a[0] = a[low];
 3     while (low < high) {
 4         while (low < high && a[high] >= a[0]) {
 5             high--;
 6         }
 7         a[low] = a[high];//将比枢轴记录小的记录移到低端
 8         while (low < high && a[low] <= a[0]) {
 9             low++;
10         }
11         a[high] = a[low];//将比枢轴记录大的记录移到高端
12     }
13     a[low] = a[0];//枢轴记录到位
14     return low;//返回枢轴位置
15 }
16 
17 void QuickSort(int* a, int low, int high) {
18     int pos;
19     if (low < high) {
20         pos = Patition(a, low, high);//枢轴位置
21         QuickSort(a, pos + 1, high);//右区间
22         QuickSort(a, low, high - 1);//左区间
23     }
24 }

三、源代码

交换类排序
 1 //在 Microsoft Visual Studio Community 2022 下测试通过
 2 #define _CRT_SECURE_NO_WARNINGS
 3 #include <stdio.h>
 4 
 5 void BubbleSort(int* a, int num) {
 6     int i, j;
 7     for (i = 1; i <= num - 1; ++i) {
 8         for (j = 1; j <= num - i; ++j) {
 9             if (a[j] > a[j + 1]) {//前后交换
10                 a[0] = a[j];
11                 a[j] = a[j + 1];
12                 a[j + 1] = a[0];
13             }
14         }
15     }
16 }
17 
18 int Patition(int* a, int low, int high) {
19     a[0] = a[low];
20     while (low < high) {
21         while (low < high && a[high] >= a[0]) {
22             high--;
23         }
24         a[low] = a[high];//将比枢轴记录小的记录移到低端
25         while (low < high && a[low] <= a[0]) {
26             low++;
27         }
28         a[high] = a[low];//将比枢轴记录大的记录移到高端
29     }
30     a[low] = a[0];//枢轴记录到位
31     return low;//返回枢轴位置
32 }
33 
34 void QuickSort(int* a, int low, int high) {
35     int pos;
36     if (low < high) {
37         pos = Patition(a, low, high);//枢轴位置
38         QuickSort(a, pos + 1, high);//右区间
39         QuickSort(a, low, high - 1);//左区间
40     }
41 }
42 
43 int main(void) {
44     int i;
45     int a[11] = { 0, 9, 4, 8, 3, 1, 6, 7, 0, 2, 5 };//a[0]设为监视哨
46     //BubbleSort(a, 10);
47     QuickSort(a, 1, 10);
48     for (i = 1; i < 11; ++i) {
49         printf("%d ", a[i]);
50     }
51     return 0;
52 }
源代码

 

上一篇:最短路径


下一篇:腾讯五十题 No.46 反转字符串