作战大师Qcm —— 原创代码, 转载请附注出处。
/**
* @name bubbleSortByOneWay 单向冒泡排序 (多次优化)
* @param data: int[] 数组
* @variable count: 记录循环次数
* @variable lastChangeIndex: 此轮循环中, 最后一个 "被交换元素" 的 "下标"
* @variable nextStartIndex: 下轮循环中, "可能发生交换元素" 的 "最大边界"
* @variable jumpIntoNextLoop: 跳进下一轮循环 ? [true: 进入] | [false: 终止循环]
* @return data: int[] 数组
*/
private static int[] bubbleSortInOneWay(int[] data) {
int count = 0;
int lastChangeIndex = 0;
int nextStartIndex = data.length - 1;
boolean jumpIntoNextLoop = true;
for (int i = 0; i < data.length && jumpIntoNextLoop; i++) {
jumpIntoNextLoop = false;
for (int j = 0; j < nextStartIndex; j++) {
count++;
if (data[j] > data[j+1]) {
// java 一种 "交换元素" 或 "赋值" 的 特殊写法
data[j] = data[j+1] + (data[j+1] = data[j])*0;
lastChangeIndex = j;
jumpIntoNextLoop = true;
}
}
// 将 "上一次被交互元素" 的 [下标] 设置为 "下轮循环" 的 [最大边界]
nextStartIndex = lastChangeIndex;
}
System.out.println(count + " 次");
return data;
}
151 次
12 ,18 ,19 ,21 ,22 ,25 ,26 ,30 ,30 ,33 ,37 ,45 ,46 ,47 ,52 ,52 ,54 ,59 ,70 ,83
单项冒泡排序特点:
1. 每轮循环会使元素在数组的其中一侧有序排列
2. 随着循环次数的增加, 有序元素的会在一侧增加, 因此下一次需要比较的数组长度会减少
3. 数组在一次外循环中, 没有发生一次元素交换, 意味数组已经是有序数组, 因此可以提前退出循环