插入排序作为十大排序之一,是一种简单且稳定的排序算法

算法思想相对直观,可以联想自己平常打扑克牌,发牌时自己边摸牌边整理牌顺序的场景

算法思想:A[i] 与 A[i] 之前的元素 A[j逐个进行比较,如果 A[i]<A[j],则交换,否则 j++,A[j] 往后移一位,

直到指针 i=j 时 A[j] 停止移动,A[i] 往后移一位,A[j] 重新从 0 开始到 i 依此类推,直到 i 走到数组的最后一个位置为止

A[i]:序列的第 2 到最后一个数   范围:[1, length-1]

A[j]:序列的第 1 个到 第 i 个     范围:[ 1 , i  ]

适用场景:数据量小、有序或者部分有序的数列

时间复杂度:O(n^2)       空间复杂度:O(1)

 

代码实现:

import java.util.Arrays;
/**
 * Java十大排序之插入排序
 * @author com
 *
 */
public class Sorts {

	public static void main(String[] args) {
		int[] arr = {49,26,2,9,16,0,10,100,24};
		System.out.println(Arrays.toString(insertSort(arr)));
	}
	public static int[] insertSort(int[] A) {
		int length = A.length;
		int temp = 0;
		for(int i=1;i<length;i++) {
			for(int j=0;j<i;j++) {
				if(A[i]<A[j]) {
					temp = A[i];
					A[i] = A[j];
					A[j] = temp;
				}
			}
			//System.out.println(Arrays.toString(A));
		}
		return A;
	}
}

运行结果:

[0, 2, 9, 10, 16, 24, 26, 49, 100]

原数据:

[49, 26, 2, 9, 16, 0, 10, 100, 24]

第 1 趟排序:i = 1,A[i] = 26;当 j = 0 时 ,A[i] < A[j], A[i] 和 A[j] 互换,即 26和49互换

[26, 49, 2, 9, 16, 0, 10, 100, 24]

第 2 趟排序:

[2, 49, 26, 9, 16, 0, 10, 100, 24]
[2, 26, 49, 9, 16, 0, 10, 100, 24]

第 3 趟排序:

[2, 26, 49, 9, 16, 0, 10, 100, 24]
[2, 9, 49, 26, 16, 0, 10, 100, 24]
[2, 9, 26, 49, 16, 0, 10, 100, 24]

第 4 趟排序:

[2, 9, 26, 49, 16, 0, 10, 100, 24]
[2, 9, 26, 49, 16, 0, 10, 100, 24]
[2, 9, 16, 49, 26, 0, 10, 100, 24]
[2, 9, 16, 26, 49, 0, 10, 100, 24]

第 5 趟排序:

[0, 9, 16, 26, 49, 2, 10, 100, 24]
[0, 2, 16, 26, 49, 9, 10, 100, 24]
[0, 2, 9, 26, 49, 16, 10, 100, 24]
[0, 2, 9, 16, 49, 26, 10, 100, 24]
[0, 2, 9, 16, 26, 49, 10, 100, 24]

第 6 趟排序:

[0, 2, 9, 16, 26, 49, 10, 100, 24]
[0, 2, 9, 16, 26, 49, 10, 100, 24]
[0, 2, 9, 16, 26, 49, 10, 100, 24]
[0, 2, 9, 10, 26, 49, 16, 100, 24]
[0, 2, 9, 10, 16, 49, 26, 100, 24]
[0, 2, 9, 10, 16, 26, 49, 100, 24]

第 7 趟排序:

[0, 2, 9, 10, 16, 26, 49, 100, 24]
[0, 2, 9, 10, 16, 26, 49, 100, 24]
[0, 2, 9, 10, 16, 26, 49, 100, 24]
[0, 2, 9, 10, 16, 26, 49, 100, 24]
[0, 2, 9, 10, 16, 26, 49, 100, 24]
[0, 2, 9, 10, 16, 26, 49, 100, 24]
[0, 2, 9, 10, 16, 26, 49, 100, 24]

第 8 趟排序:

[0, 2, 9, 10, 16, 26, 49, 100, 24]
[0, 2, 9, 10, 16, 26, 49, 100, 24]
[0, 2, 9, 10, 16, 26, 49, 100, 24]
[0, 2, 9, 10, 16, 26, 49, 100, 24]
[0, 2, 9, 10, 16, 26, 49, 100, 24]
[0, 2, 9, 10, 16, 24, 49, 100, 26]
[0, 2, 9, 10, 16, 24, 26, 100, 49]
[0, 2, 9, 10, 16, 24, 26, 49, 100]

最终结果:

[0, 2, 9, 10, 16, 24, 26, 49, 100]