六、排序-插入排序

package com.zhou.sort;

import java.util.Arrays;

/**
 * @author zhou
 * @date 2021-6-1
 */
public class InsertSort {
    public static void main(String[] args) {
        int[] arr = new int[]{5, 6, 9, 1, 8, 3, 2, 0};
        insertSort(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void insertSort(int[] arr) {
        // 遍历所有的数字  以第二个数字为基准
        for (int i = 1; i < arr.length; i++) {
            // 如果当前的数字比前一个数字小
            if (arr[i - 1] > arr[i]) {
            // 就把当前的数字存储起来
                int temp = arr[i];
                int j;
                // 遍历出当前数字 前面的所有的数字
                for (j = i - 1; j >= 0 && arr[j] > temp; j--) {
                    // 把前一个数字赋给后一个数字
                    arr[j+1]=arr[j];
                }
                // 最后把临时变量 赋值给不满足条件的最后一个元素
                arr[j+1] = temp;
            }
        }

    }

}

原文地址:https://www.cnblogs.com/saysayzhou/p/14835586.html