直接上代码
初次版本
public static void main(String[] args) { int[] ints = {1, 5, 2, 6, 8, 4}; for (int i = 0; i < ints.length; i++) { for (int j = 0; j < ints.length - i - 1; j++) { if (ints[j] > ints[j + 1]) { int temp = ints[j]; ints[j] = ints[j + 1]; ints[j + 1] = temp; } } } System.out.println(Arrays.toString(ints)); }
优化版本
public static void main(String[] args) { int[] ints = {11, 5, 2, 6, 8, 4}; for (int i = 0; i < ints.length; i++) { Boolean swap = true; for (int j = 0; j < ints.length - i - 1; j++) { if (ints[j] > ints[j + 1]) { int temp = ints[j]; ints[j] = ints[j + 1]; ints[j + 1] = temp; swap = false; } } if (swap) { break; } } System.out.println(Arrays.toString(ints)); }
优化思想是:
如果发现一次比较中没有发生排序现象则判断是有序数组了。