分析
每相邻两个数比较,大的向右沉,数据“冒泡”。每一次排序,能使最大的排在最后。
代码
/*
* 算法改进:加一个标志位,记录每趟排序最后一个进行交换的位置,下一次只需扫描到pos
*/
public static void bubbleSort(int a[]) {
int i = a.length - 1;
while (i > 0) {
int pos = 0;
for (int j = 0; j < i; j++) {
if (a[j] > a[j + 1]) {
pos = j;
common.swap(a, j, j + 1);
}
}
common.print(a);
i = pos;
}
}
public static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
原始数组:
3 1 5 7 2 4 6 8
排序过程:
1 3 5 2 4 6 7 8
1 3 2 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8原始数组:
10 7 2 3 1 4 6 0
排序过程:
7 2 3 1 4 6 0 10
2 3 1 4 6 0 7 10
2 1 3 4 0 6 7 10
1 2 3 0 4 6 7 10
1 2 0 3 4 6 7 10
1 0 2 3 4 6 7 10
0 1 2 3 4 6 7 10