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
| #include <stdio.h>
#define ARRSIZE(arr) (sizeof(arr) / sizeof(arr[0]))
void Swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void BubbleSort(int elements[], int length)
{
int flag = 0; //记录排序是否完成
for (int i = 0; i < length; i++)
{
flag = 0;
for (int j = 0; j < length - i - 1; j++)
{
if (elements[j] > elements[j + 1])
{
flag = 1; //这趟循环进行了元素交换
Swap(&elements[j], &elements[j + 1]);
}
}
if (!flag)//如果没有进行元素交换则代表集合已经是有序的,退出循环
break;
}
}
int main(int argc, char const *argv[])
{
int elems[] = {3, 4, 2, 1, 5, 9, 2, 1, 0, 22, 33, 5, 112, 11, 22, 55, 22, 61, 97};
int len = ARRSIZE(elems);
BubbleSort(elems, len);
for (int i = 0; i < len; i++)
printf("%4d", elems[i]);
printf("\n");
return 0;
}
|