冒泡排序通过比较相邻两个数的大小来排列顺序。
难点:
需要两层循环
需要交换相邻两个数组元素的值
下面这段代码,只有一层循环。这个循环执行完毕时只是找出了最大的数,剩下的数并没有排序。
import org.junit.Test; import java.util.Arrays; public class Demo { int[] a = {2, 0, 1, 9, 3, 6, 5, 8, 4}; @Test public void bubbleSort() { int temp = 0; for (int j = 0; j < a.length - 1; j++) {//注意:j<a.length-1,如果不减去1,数组会越界 if (a[j + 1] < a[j]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; System.out.println(Arrays.toString(a)); } } } }
上面代码的运行结果
[0, 2, 1, 9, 3, 6, 5, 8, 4] [0, 1, 2, 9, 3, 6, 5, 8, 4] [0, 1, 2, 3, 9, 6, 5, 8, 4] [0, 1, 2, 3, 6, 9, 5, 8, 4] [0, 1, 2, 3, 6, 5, 9, 8, 4] [0, 1, 2, 3, 6, 5, 8, 9, 4] [0, 1, 2, 3, 6, 5, 8, 4, 9]
改进上面的代码,加个外层循环
import org.junit.Test; import java.util.Arrays; public class Demo { int[] a = {2, 0, 1, 9,7, 3, 6, 5, 8, 4}; @Test public void bubbleSort() { int temp = 0; for (int i = 0; i < a.length - 1; i++) { for (int j = 0; j < a.length - i - 1; j++) {
//注意:这里是j<a.length-i-1.
//原因,第一次循环时已经把最大数9,排到最后面了,第二次循环时就应该在剩下的数里面找出8,要少一次循环。 if (a[j + 1] < a[j]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; System.out.println(Arrays.toString(a)); } } } } }
运行结果
[0, 2, 1, 9, 7, 3, 6, 5, 8, 4] [0, 1, 2, 9, 7, 3, 6, 5, 8, 4] [0, 1, 2, 7, 9, 3, 6, 5, 8, 4] [0, 1, 2, 7, 3, 9, 6, 5, 8, 4] [0, 1, 2, 7, 3, 6, 9, 5, 8, 4] [0, 1, 2, 7, 3, 6, 5, 9, 8, 4] [0, 1, 2, 7, 3, 6, 5, 8, 9, 4] [0, 1, 2, 7, 3, 6, 5, 8, 4, 9] [0, 1, 2, 3, 7, 6, 5, 8, 4, 9] [0, 1, 2, 3, 6, 7, 5, 8, 4, 9] [0, 1, 2, 3, 6, 5, 7, 8, 4, 9] [0, 1, 2, 3, 6, 5, 7, 4, 8, 9] [0, 1, 2, 3, 5, 6, 7, 4, 8, 9] [0, 1, 2, 3, 5, 6, 4, 7, 8, 9] [0, 1, 2, 3, 5, 4, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
来看一个最复杂的排序,这是冒泡排序空间复杂度最复杂的情况
import org.junit.Test; import java.util.Arrays; public class Demo { int[] a = {9, 8, 7, 6,5, 4, 3, 2, 1, 0}; @Test public void bubbleSort() { int temp = 0; for (int i = 0; i < a.length - 1; i++) { for (int j = 0; j < a.length - i - 1; j++) { if (a[j + 1] < a[j]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; System.out.println(Arrays.toString(a)); } } } } }
其结果
[8, 9, 7, 6, 5, 4, 3, 2, 1, 0] [8, 7, 9, 6, 5, 4, 3, 2, 1, 0] [8, 7, 6, 9, 5, 4, 3, 2, 1, 0] [8, 7, 6, 5, 9, 4, 3, 2, 1, 0] [8, 7, 6, 5, 4, 9, 3, 2, 1, 0] [8, 7, 6, 5, 4, 3, 9, 2, 1, 0] [8, 7, 6, 5, 4, 3, 2, 9, 1, 0] [8, 7, 6, 5, 4, 3, 2, 1, 9, 0] [8, 7, 6, 5, 4, 3, 2, 1, 0, 9] [7, 8, 6, 5, 4, 3, 2, 1, 0, 9] [7, 6, 8, 5, 4, 3, 2, 1, 0, 9] [7, 6, 5, 8, 4, 3, 2, 1, 0, 9] [7, 6, 5, 4, 8, 3, 2, 1, 0, 9] [7, 6, 5, 4, 3, 8, 2, 1, 0, 9] [7, 6, 5, 4, 3, 2, 8, 1, 0, 9] [7, 6, 5, 4, 3, 2, 1, 8, 0, 9] [7, 6, 5, 4, 3, 2, 1, 0, 8, 9] [6, 7, 5, 4, 3, 2, 1, 0, 8, 9] [6, 5, 7, 4,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