冒泡排序的优化
这下面就是我自己的理解冒泡排序的小优化吧
package cn.itcast.algorithm.suanFa; import java.util.Arrays; /** * 冒泡排序的优化 */ public class MainS12 { public static void main(String[] args) { int[] a = {3, 1, 5, 4, 6, 9, 8, 7, 2}; // int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = a.length-1; while(true) { int last = 0; //表示最后一次交换索引位置 boolean swapped = false; //判断是否发生交换 //a.length - 1 - j减少不必要的比较次数 for (int i = 0; i < n; i++) { System.out.println("比较了"+ (i+1)+ "次"); if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; swapped = true; last = i; } } n = last; /* 如果最后一次的索引位置为0则说明要交换的次数为0, 证明已经排序好了,不需要在进行比较了,退出该循环 */ if (n == 0){ break; } System.out.println("-------------------"); //这里是考虑到如果原本就是有序的,即没有发生交换,就不用在进行不必要的比较了 if (!swapped){ break; } } System.out.println("冒泡排序之后:" + Arrays.toString(a)); } }