冒泡排序的原理:两个相邻的数比较大小,将两个数中较大的数往右边放,小的往左边放。
代码如下
// bubble sort v1
int bubble_sort(int *array, int len)
{
int i, j;
int temp, loop_count = 0;
for (i = 0; i < (len - 1); i++) {
for (j = i + 1; j < len; j++) {
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
loop_count++;
}
}
printf("loop=%d\n", loop_count);
return 0;
}
// bubble sort v2
int bubble_sort(int *array, int len)
{
int temp = 0;
int i, j, loop_count = 0;
int first_diff_flag = 0;
for (i = 0; i < len - 1; i++) {
if (array[i] > array[i + 1]) {
temp = array[i] ;
array[i] = array[i + 1];
array[i + 1] = temp;
if (i >= 1) {
if (!first_diff_flag) {
j = i;
first_diff_flag = 1; // 第1次出现不同值时i赋给j, 退出后array[i]之前的数已排序完成,
}
i -= 2; // 第i和i + 1个数交换后, 从第i - 1个数开始需要从新比较
}
} else {
if (first_diff_flag) {
i = j;
first_diff_flag = 0; // 将j赋值给i, 比较array[j]和array[j + 1]
}
}
loop_count++;
}
printf("loop_count=%d\n", loop_count);
return 0;
}