Bubble sort
The snippet can be accessed without any authentication.
Authored by
Kiryuu Sakuya
main.c 874 B
#include <stdio.h>
int main() {
int a[5] = {3, 1, 4, 5, 2};
// Bubble Sort
/*
* 冒泡排序
* 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
* 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
* 针对所有的元素重复以上的步骤,除了最后一个。
* 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
*/
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < 5 - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < 5; i++) {
printf("%d ", a[i]);
}
return 0;
}
Please register or sign in to comment