记录下冒泡算法的实现。
public class BubbleSort { public static void sort(Integer[] array) { if (array == null || array.length == 0) { return; } for (int bubbleNum = 0; bubbleNum < array.length - 1; bubbleNum++) { // 一次只能将一个元素冒泡到对应的位置,所以要将N-1个元素冒泡 for (int i = 1; i < array.length - bubbleNum; i++) { // 有N个元素,需要对比N-1次将元素冒泡到对应的位置。但因前面的冒泡已经将M个元素冒泡到最后,所以有M个元素无须对比。(N = array.length,M = bubbleNum) if (array[i - 1] > array[i]) { swap(array, i - 1, i); } } } } private static void swap(Integer[] array, Integer i, Integer j) { Integer temp = array[i]; array[i] = array[j]; array[j] = temp; } }
import org.junit.Test; public class HowToTest { @Test public void c1() { Integer[] array = {3,16,1,5,2,18,0,9,20,11}; BubbleSort.sort(array); for (int i = 0; i < array.length; i++) { System.out.print(array[i] + ", "); } System.out.println(); } @Test public void c2() { Integer[] array = {99,98,97,96,95,94,93,92,91,101,90,89,88,87,86,85};; BubbleSort.sort(array); for (int i = 0; i < array.length; i++) { System.out.print(array[i] + ", "); } System.out.println(); } }