原理
- 将值插入到数组开头的排序序列中。它在序列结束时开始操作,并将每个元素向右移动一个位置,直到找到新元素的合适位置。该函数具有覆盖在数组中排序的序列之后立即存储的值的副作用。
- 要执行插入排序,请从数组最左侧的元素开始,然后调用Insert以将遇到的每个元素插入到正确的位置。插入元素的有序序列存储在已检查的索引集中的数组的开头。每个插入都会覆盖一个值:插入的值。
伪代码
i ← 1
while i < length(A)
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
i ← i + 1
end while
faster:
i ← 1
while i < length(A)
x ← A[i]
j ← i - 1
while j >= 0 and A[j] > x
A[j+1] ← A[j]
j ← j - 1
end while
A[j+1] ← x
i ← i + 1
end while
递归:
function insertionSortR(array A, int n)
if n>0
insertionSortR(A,n-1)
x ← A[n]
j ← n-1
while j >= 0 and A[j] > x
A[j+1] ← A[j]
j ← j-1
end while
A[j+1] ← x
end if
end function
分析
最坏情况:
逆序排列的数组
T(n) = ∑ j = 2 n Θ ( j ) = Θ ( n 2 ) \displaystyle\sum_{j=2}^n \Theta(j) = \Theta(n^2) j=2∑nΘ(j)=Θ(n2)
∑ \sum ∑是第一层循环求和,第二层求和仍是循环。
所以插入排序的时间复杂度就是 n2
代码
Java
import java.util.Arrays;
/**
* 插入排序
* @author simorel
* @date 2019/8/30
* @description
*/
public class InsertionSort {
public static void main(String[] args) {
int[] list = {3, 24, 18, 57, 26, 9, 7};
insertionSort(list);
System.out.println(Arrays.toString(list));
}
public static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
System.out.println("i: " + i);
for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
System.out.println("j: " + j);
System.out.println("arr[j]: " + arr[j]);
System.out.println("arr[j + 1]: " + arr[j + 1]);
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
System.out.println("arr[j]: " + arr[j]);
System.out.println("arr[j + 1]: " + arr[j + 1]);
System.out.println();
}
System.out.println();
System.out.println();
}
}
}
Javascript
let list = [3, 24, 18, 57, 26, 9, 7]; // 待排序的数组
function insertSort(arr) {
for (let i = 1; i < arr.length; i++) {
console.log('');
console.log('%c i: ', 'background-color: yellowgreen;color: #fff', i);
for (let j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
console.log('');
console.log(
'%c j: ',
'background-color: #d1d1d1;color: #272626',
j
);
console.log('arr[j]: ', arr[j]);
console.log('arr[j + 1]: ', arr[j + 1]);
let temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
console.log('list: ', list);
}
}
}
insertSort(list);
console.log('');
console.log('result:');
console.log(list);
参考链接
[1] 维基百科 Insertion sort
[2] 百度百科 插入排序