一、介绍
冒泡排序:它重复地走访过要排序的元素列,依次比较两个相邻的元素,如果顺序(如从大到小、首字母从Z到A)错误就把他们的交换过来。走访元素的工作是重复地进行直到没有相邻元素需要交换,也就是说该元素列已经排序完成。
这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端(升序或降序排列),就如同碳酸饮料中二氧化碳的气泡最终会上浮到顶端一样,故名“冒泡排序”。(摘自百度百科)
时间复杂度:O(n^2)
额外空间复杂度:O(1)
是否稳定性算法:是
稳定性定义:能保证两个相等的数,经过排序之后,其在序列的前后位置顺序不变。如data1=data2,排序前data1在data2前面,排序后data1还在data2前面)
二、实现
1.最简单实现
public class BubbleSort {
public static void main(String[] args) {
bubbleSort(new int[]{ 9, 8, 7, 6, 1});
}
public static int[] bubbleSort(int[] source){
int length = source.length;
for (int i = 0; i < length-1; i++) {
System.out.println("第" + (i+1) + "趟排序");
for (int j = 0; j < length -1; j++) {
System.out.print("第" + (j+1) + "次比较, source[" + j + "]=" + source[j]
+ " , source[" + (j+1) + "]=" + source[j+1] + " ; ");
if (source[j] > source[j+1]){
System.out.print(source[j] + "与" + source[j+1] + "交换位置; ");
int temp = source[j];
source[j] = source[j+1];
source[j+1] = temp;
}
System.out.println("该次结果:" + Arrays.toString(source));
}
}
return source;
}
}
排序过程如图所示:
2.优化一
注意上图中红色框中的内容,比较后没有发生交换,且有规律,那么我们可以去掉这些没有交换的比较。
public class BubbleSort {
public static void main(String[] args) {
bubbleSort(new int[]{ 9, 8, 7, 6, 1});
}
public static int[] bubbleSort(int[] source){
int length = source.length;
for (int i = 0; i < length-1; i++) {
System.out.println("第" + (i+1) + "趟排序");
// 注意这里的条件是(length - 1 - i)
for (int j = 0; j < length - 1 - i; j++) {
System.out.print("第" + (j+1) + "次比较, source[" + j + "]=" + source[j]
+ " , source[" + (j+1) + "]=" + source[j+1] + " ; ");
if (source[j] > source[j+1]){
System.out.print(source[j] + "与" + source[j+1] + "交换位置; ");
int temp = source[j];
source[j] = source[j+1];
source[j+1] = temp;
}
System.out.println("该次结果:" + Arrays.toString(source));
}
}
return source;
}
}
排序过程如图所示:
3.优化二
当我们遇到源数据里本就部分有序的情况,我还能再优化一下代码。我们先假定数据有序,如果没有发生交换,那么就说明数据是有序的,排序完成。 代码如下:
public class BubbleSort {
public static void main(String[] args) {
bubbleSort(new int[]{ 1, 6, 9, 7, 8});
}
public static int[] bubbleSort(int[] source){
int length = source.length;
for (int i = 0; i < length-1; i++) {
System.out.println("第" + (i+1) + "趟排序");
boolean sorted = true;
for (int j = 0; j < length -1 - i; j++) {
System.out.print("第" + (j+1) + "次比较, source[" + j + "]=" + source[j]
+ " , source[" + (j+1) + "]=" + source[j+1] + " ; ");
if (source[j] > source[j+1]){
System.out.print(source[j] + "与" + source[j+1] + "交换位置; ");
int temp = source[j];
source[j] = source[j+1];
source[j+1] = temp;
sorted = false;
}
System.out.println("该次结果:" + Arrays.toString(source));
}
if (sorted){
System.out.println("确认有序~~~~~~~~~~~");
break;
}
}
return source;
}
}
运行结果如图: