冒泡排序
What
冒泡排序(Bubble Sort),其思想是循环遍历数组,比较交换相邻的元素,此时最大(或最小)元素,会像泡泡一样,慢慢从水里冒出来(慢慢排到数组的最前面)。
例如:现在有数组:{3,2,1}
1. 遍历数组第一个元素3,3与右边的2比较,3比2大,那么3与2进行交换,得到新数组{2,3,1},注意此时数组第二个元素是3;
2. 遍历数组第二个元素3,3与右边的1比较,3比1大,那么3与1进行交换,得到新数组{2,1,3},结束第一次遍历;
3. 开始第二次遍历,遍历数组第一个元素2,2与右边的1比较,2比1大,那么2与1进行交换,得到新数组{1,2,3};
4. 结束;
上面的例子数组的变化为:
{3,2,1} -> {2,3,1} -> {2,1,3} -> {1,2,3}
可以看到元素1从右边被慢慢交换到左边,“冒”了出来。
How
//测试类
public class Test {
public static void main(String []args) {
int[] array = {1,9,8,2,7,3,4,6,5};
int[] afterSortedArray = Bubble.sort(array);
for ( int i : afterSortedArray ) {
System.out.println(i);
}
}
}
class Bubble{
//冒泡算法:对int[]数组升序排序
public static int[] sort(int[] array) {
//数组长度
int length = array.length;
//循环遍历数组
for ( int i = 0 ; i < length ; i ++ ) {
//交换是否进行标志,false表示无交换(数组已排序好),true表示交换了
boolean swap = false;
for ( int j = 0 ; j < length-i-1 ; j ++ ) {
//比较相邻的值
if ( array[j] > array[j+1] ) {
//相邻值交换
array[j] = array[j] + array[j+1];
array[j+1] = array[j] - array[j+1];
array[j] = array[j] - array[j+1];
//swap标志置位true,表示有交换
swap = true;
}
}
//swap标志为false,则表示循环遍历比较后都无需交换,此时数组已排序好
if ( !swap ) break;
}
return array;
}
}
注意:
加入swap标志,避免一些极端情况,例如对排序好的数组{1,2,3,4,5,6,7,8}再排序,如果没有加swap,则必须遍历比较n*(n-1)次之后,才会停下。加入swap标志后,n-1次的遍历比较后,发现没有元素需要交换,数组已排序好,无需再遍历,节省资源。
时间复杂度O(n^2)
When & Where
对于数据量小可以使用
结束语:优秀是一种习惯
1958

被折叠的 条评论
为什么被折叠?



