对于给定的一组记录,初始时假设第一个记录自成一个有序序列,其余记录为无序序列。接着从而个记录开始,按照记录的大小依次将当前处理的记录插入到其之前的有序序列中,直至最后一条记录插入到有序序列中为止。

例如:数组 {38,65,97,76,13,27,49}
第一步插入38以后:[38]65 97 76 13 27 49
第一步插入65以后:[38 65]97 76 13 27 49
第一步插入97以后:[38 65 97]76 13 27 49
第一步插入76以后:[38 65 76 97]13 27 49
第一步插入13以后:[13 38 65 76 97]27 49
第一步插入27以后:[13 27 38 65 76 97]49
第一步插入49以后:[13 27 38 49 65 76 97]

【程序示例如下】:

/**
 * 插入排序
 */
public class InsertionSort {
    public static void insertSort(Integer[] src){
        //循环遍历目标数组,从下标1开始,默认有一个元素
        for(int i=1;i<src.length;i++){
            int j=i;
            int temp = src[i];
            while((j >= 1) && (src[j-1] > temp)){
                src[j]=src[j-1];
                j--;
            }
            src[j]=temp;
        }
    }
    public static void main(String[] args){
        Integer[] array = {13,27,38,49,65,76,97};
        //使用插入排序,对 array 进行排序
        insertSort(array);
        System.out.println(Arrays.asList(array).toString());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

【输出结果】: [13, 27, 38, 49, 65, 76, 97]

插入排序(Insertion sort)是一种简单直观且稳定的排序算法。如果有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序,这个时候就要用到一种新的排序方法:插入排序法,插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为 O(n^2)。是稳定的排序方法。插入算法把要排序的数组分成两部分:第一部分包含了这个数组的所有元素,但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。插入排序的基本思想是:每步将一个待排序的记录,按其关键码值的大小插入前面已经排序的文件中适当位置上,直到全部插入完为止。

【程序示例如下】:

/**
 * 插入排序
 */
public class TestSort {
    public static Integer[] insertSort(int target, Integer[] src){
        Integer[] newArray = new Integer[src.length+1];
        //将原数据拷贝到目标数组中
        System.arraycopy(src,0,newArray,0,src.length);
        int j = src.length-1;
        int n = newArray.length-1;
        while((j >= 0) && (src[j] > target)){
            newArray[n] = src[j];
            j--;
            n--;
        }
        newArray[n] = target;
        return newArray;
    }
    public static void main(String[] args){
        Integer[] array = {7,13,43,56,17,7,32};
        //向原有队列插入一个数据 0
        Integer[] integers = insertSort(0, array);
        array = integers;
        System.out.println(Arrays.asList(array).toString());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

【输出结果】: [0, 7, 13, 43, 56, 17, 7, 32]

(adsbygoogle = window.adsbygoogle || []).push({});