插入排序

1. 插入排序思路

image-20220812183249450


2. 代码实现

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
27
28
public class cha_ru_pai_xu {
public static void main(String[] args) {
int[] a = {9, 3, 7, 2, 5, 8, 1, 4};
int[] b = {1,2,4,5,3};
insert(a);
}

private static void insert(int[] a){
int n = 0;
for (int i = 1; i < a.length; i++) {
int temp = a[i]; // 记录当前要插入的值
int j = i - 1;
/**
* 这是从后往前比较插入
* 这样会有一个空位直接移位
*/
while (j >= 0){
// 记住 temp 不能用 a[i]代替 因为下面的对换可能会改变a[i]的值
if (a[j] > temp) {
a[j+1] = a[j];
} else break;
j--;
}
a[j + 1] = temp;
System.out.println(Arrays.toString(a));
}
}
}
1
2
3
4
5
6
7
[3, 9, 7, 2, 5, 8, 1, 4]
[3, 7, 9, 2, 5, 8, 1, 4]
[2, 3, 7, 9, 5, 8, 1, 4]
[2, 3, 5, 7, 9, 8, 1, 4]
[2, 3, 5, 7, 8, 9, 1, 4]
[1, 2, 3, 5, 7, 8, 9, 4]
[1, 2, 3, 4, 5, 7, 8, 9]

3. 简单图解

[2,3,1]为例

image-20220812184750309


4. 与选择排序比较

image-20220812184838772


5. 插入、选择面试题例

image-20220812184917509

1
91819232315

image-20220812184951572

1
91518192323

插入排序
https://blog.gutaicheng.top/2022/07/25/插入排序/
作者
GuTaicheng
发布于
2022年7月25日
许可协议