算法-插入排序-直接插入排序

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/XiaHeShun/article/details/82223250

算法–插入排序–直接插入排序

基本思想:

在要排序的一组数中,假设前面(n-1) [n>=2] 个数已经是排好顺序的,现在要把第n个数插到前面的有序数中,使得这n个数也是排好顺序的。如此反复循环,直到全部排好顺序。

插图:
这里写图片描述

代码实现

import java.util.Arrays;

public class insertSort {

    public static int[] sort(int[] array) {
        int temp = 0;
        for (int i = 1; i < array.length; i++) {
            int j = i - 1;
            temp = array[i];
            for (; j >= 0 && temp < array[j]; j--) {
                array[j + 1] = array[j]; // 将大于temp的值整体后移一个单位
            }
            array[j + 1] = temp;
            System.out.println("过程:"+Arrays.toString(array));
        }
        return array;
    }

    public static void main(String[] args) {
        int[] arr = { 53, 27, 36, 15, 69, 42 };
        System.out.println("初始状态:"+Arrays.toString(arr));
        System.out.println("最终结果:"+Arrays.toString(sort(arr)));
    }

}

输出结果:

初始状态:[53, 27, 36, 15, 69, 42]
过程:[27, 53, 36, 15, 69, 42]
过程:[27, 36, 53, 15, 69, 42]
过程:[15, 27, 36, 53, 69, 42]
过程:[15, 27, 36, 53, 69, 42]
过程:[15, 27, 36, 42, 53, 69]
最终结果:[15, 27, 36, 42, 53, 69]

猜你喜欢

转载自blog.csdn.net/XiaHeShun/article/details/82223250