【经典排序算法 time: 2023-10-12】插入排序(层层优化改进)

  1. 原理
    每次循环往后面拿出一个元素排到前面有序序列中(动态演示)

  2. 插排第一版

public class InsertSort {
    public static void main(String[] args) {
        long start= System.currentTimeMillis();
        int[] arr = {11, 23, 69, 99, 1, 3, 45, 67, 5, 234, 678, 999, 7, 123};
        int[] result = insertSort(arr);
        System.out.println(Arrays.toString(result));

        System.out.println(System.currentTimeMillis()-start);
    }

    private static int[] insertSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int target = arr[i];
            for (int j = i-1; j >= 0; j--) {
                if (target < arr[j]) {
                    swap(arr, j, j+1);
                }
            }
            System.out.println(Arrays.toString(arr));
        }
        System.out.println("循环了" +( arr.length -1 ) + "次");
        return arr;
    }

    public static void swap(int[] a, int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
}
  1. 改进一,少去一轮循环,内部循环在找到位置时提前退出,再进行交换
public class InsertSortPlus {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        int[] arr = {11, 23, 69, 99, 1, 3, 45, 67, 5, 234, 678, 999, 7, 123};
        int[] result = insertSort(arr);
        System.out.println(Arrays.toString(result));

        System.out.println(System.currentTimeMillis() - start);
    }

    private static int[] insertSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int target = arr[i];
            int j = i - 1;
            while (j >= 0) {
                if (arr[j] > target) {
                    arr[j + 1] = arr[j];
                } else {
                    break;
                }
                j--;
            }
            arr[j + 1] = target;
            System.out.println(Arrays.toString(arr));
        }
        System.out.println("循环了" + (arr.length - 1) + "次");
        return arr;
    }

}

你可能感兴趣的:(排序算法,排序算法,算法,java)