0%

数据结构-第八章-排序

冒泡排序

1
2
3
4
5
6
7
#include<stdio.h>

void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void BubbleSort(int A[], int n) {
for (int i = 0; i < n - 1; i++)
{
bool flag = false;
for (int j = n - 1; j > i; j--)
{
if (A[j - 1] > A[j])
{
swap(A[j - 1], A[j]);
flag = true;
}
}
if (flag == false)
{
for (int i = 0; i < n; i++)
{
printf("%d ", A[i]);
}
return;
}
}
}

int main() {
int A[] = { 52,6,65,52,85,33,99,125,22,33,55,66,55,88,77,55,66,55,22,59 };
BubbleSort(A, (sizeof(A)/sizeof(int)));
return 0;
}

快速排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<stdio.h>

int Partition(int A[], int low, int high) {
int pivot = A[low];
while (low < high)
{
while (low < high && A[high] >= pivot)
{
high -= 1;
}
A[low] = A[high];
while (low < high && A[low] <= pivot)
{
low += 1;
}
A[high] = A[low];
}
A[low] = pivot;
return low;
}

void QuickSort(int A[], int low, int high) {
if (low < high)
{
int point = Partition(A, low, high);
QuickSort(A, low, point - 1);
QuickSort(A, point + 1, high);
}
}

int main() {
int A[] = { 52,6,65,52,85,33,99,125,22,33,55,66,55,88,77,55,66,55,22,59 };
QuickSort(A, 0, (sizeof(A) / sizeof(A[0]) - 1));
for (int i = 0; i < (sizeof(A) / sizeof(A[0])); i++)
{
printf("%d ", A[i]);
}
return 0;
}

本文标题:数据结构-第八章-排序

文章作者:fanchen

发布时间:2021年06月05日 - 17:55:03

最后更新:2021年06月05日 - 18:47:03

原始链接:http://88fanchen.github.io/posts/d311869f/

许可协议:署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。