|
1 | 1 | package algorithm
|
2 | 2 |
|
| 3 | +import "fmt" |
| 4 | + |
3 | 5 | // InsertionSort ..
|
4 | 6 | // 算法步骤:
|
5 | 7 | // 将第一待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列。
|
6 | 8 | // 从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。
|
7 | 9 | //(如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面。)
|
| 10 | +// arr := []int{3, 2, 0, 5, 10, 1} |
8 | 11 | func InsertionSort(arr []int) []int {
|
9 | 12 | for i := range arr {
|
10 | 13 | preIndex := i - 1
|
11 | 14 | current := arr[i]
|
| 15 | + fmt.Printf("current: %v\n", current) |
12 | 16 | for preIndex >= 0 && arr[preIndex] > current {
|
13 | 17 | arr[preIndex+1] = arr[preIndex]
|
14 | 18 | preIndex--
|
15 | 19 | }
|
| 20 | + fmt.Printf("finally i: %v, current: %v, preIndex: %v\n", i, current, preIndex) |
16 | 21 | arr[preIndex+1] = current
|
17 | 22 | }
|
18 | 23 | return arr
|
|
0 commit comments