重点:维护一个有序段,取后面的元素,按顺序插入到有序段中
public class InsertSort<T extends Comparable> { public void sort(T[] arr) { if (arr != null && arr.length > 1) { for (int i = 1; i < arr.length; i++) { T temp = arr[i]; int j; for (j = i; j > 0; j--) { // 如果插入值比对比值小,就将对比值后移一位 // 否则,就跳出循环,此时,j即为要插入的下标 // 对比的下标是j-1 if (temp.compareTo(arr[j - 1]) < 0) { arr[j] = arr[j - 1]; } else { break; } for (T n : arr) { System.out.print(n); } System.out.println(); } arr[j] = temp; for (T n : arr) { System.out.print(n); } System.out.println(); System.out.println(String.format("第%d次执行,交换了%d次,赋值了1次", i, i - j)); } } } public static void main(String[] args) { Integer[] arr = new Integer[]{1, 3, 8, 7, 6, 9, 5, 4, 3, 2, 0}; InsertSort is = new InsertSort(); is.sort(arr); } /** * 13876954320 * 第1次执行,交换了0次,赋值了1次 * 将3赋值在3位置 * 13876954320 * 第2次执行,交换了0次,赋值了1次 * 将8赋值在8位置 * 13886954320 => 8后移 * 13786954320 => 7赋值 * 第3次执行,交换了1次,赋值了1次 * 13788954320 => 8后移 * 13778954320 => 7后移 * 13678954320 => 6赋值 * 第4次执行,交换了2次,赋值了1次 * 13678954320 * 将9赋值在9位置 * 第5次执行,交换了0次,赋值了1次 * 13678994320 => 9后移 * 13678894320 => 8后移 * 13677894320 => 7后移 * 13667894320 => 6后移 * 13567894320 => 5赋值 * 第6次执行,交换了4次,赋值了1次 * 13567899320 * 13567889320 * 13567789320 * 13566789320 * 13556789320 * 13456789320 * 第7次执行,交换了5次,赋值了1次 * 13456789920 => 9后移 * 13456788920 => 8后移 * 13456778920 => 7后移 * 13456678920 => 6后移 * 13455678920 => 5后移 * 13445678920 => 4后移 * 13345678920 => 3赋值 => 与原顺序没有改变 * 第8次执行,交换了6次,赋值了1次 * 13345678990 * 13345678890 * 13345677890 * 13345667890 * 13345567890 * 13344567890 * 13334567890 * 13334567890 * 12334567890 * 第9次执行,交换了8次,赋值了1次 * 12334567899 * 12334567889 * 12334567789 * 12334566789 * 12334556789 * 12334456789 * 12333456789 * 12333456789 * 12233456789 * 11233456789 * 01233456789 * 第10次执行,交换了10次,赋值了1次 * * 最外层遍历了10次,内层交换次数不超过i次 * => 遍历次数:与数据分布有关 * => 时间复杂度:O(n2) * => 稳定性:稳定 */ }