3 分钟学会插入排序

思路

  1. 将待排元素插入到有序数组中的合适位置,后边的元素依次向后移动
  2. 将数组分为有序与待排两个区域
  3. 待排区从 1 开始,依次取出每个元素插入有序区,一共进行 n-1 趟
  4. 从有序区后面开始比较,有序元素>待排元素,有序元素则向后移动

实现

public class Solution {
    public static void insertSort(int[] array) {
        for (int i = 1; i < array.length; i++) {
            int value = array[i]; // 待排元素
            int j = i - 1;
            for (; j >= 0; j--) {
                if (value < array[j]) {
                    array[j + 1] = array[j];
                } else {
                    break;
                }
            }
            // j = -1 时,value >= array[j] 时
            array[j + 1] = value;
        }
    }

    public static void main(String[] args) {
        int[] array = new int[]{2, 5, 1, 6, 9, 3};
        insertSort(array);
        for (int i : array) {
            System.out.print(i + " ");
        }
    }
}

发布了243 篇原创文章 · 获赞 16 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_29150765/article/details/105186131