0%

Algorithm-冒泡排序

C语言实现冒泡排序。

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

void BubbleSort(int *a, int n);

int main()
{
int n = 6;
int a[6] = {3, 2, 4, 6, 5, 1};
for (int i = 0; i < n; i++)
{
printf("a[%d]=%d ", i, a[i]);
}
printf("\n");
BubbleSort(a, n);
for (int i = 0; i < n; i++)
{
printf("a[%d]=%d ", i, a[i]);
}
printf("\n");
return 0;
}

void BubbleSort(int *a, int n)
{
int i, j;
int tmp;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (a[j] > a[j + 1])
{
tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
}
}
}
}
输出结果:
1
2
a[0]=3 a[1]=2 a[2]=4 a[3]=6 a[4]=5 a[5]=1
a[0]=1 a[1]=2 a[2]=3 a[3]=4 a[4]=5 a[5]=6

Welcome to my other publishing channels