Skip to content

Commit 1f88e3c

Browse files
committed
插入排序
1 parent db71033 commit 1f88e3c

File tree

4 files changed

+48
-1
lines changed

4 files changed

+48
-1
lines changed

.gitignore

Whitespace-only changes.

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
# go-algorithm
1+
# go 算法

insertion/insertion.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//插入排序
2+
package insertion
3+
4+
//原理:通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入
5+
6+
//算法步骤:
7+
// 1.第一待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列
8+
// 2.从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。(如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面
9+
10+
11+
//[]int{3,44,56,38,77,38,26}
12+
//[]int{3}
13+
14+
func InsertionSort(arr []int) []int {
15+
for i := range arr {
16+
preIndex := i -1
17+
current := arr[i]
18+
for preIndex >=0 && arr[preIndex] > current{
19+
arr[preIndex + 1] = arr[preIndex]
20+
preIndex -=1
21+
}
22+
arr[preIndex +1] = current
23+
}
24+
return arr
25+
}

insertion/insertion_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package insertion
2+
3+
import (
4+
"testing"
5+
"github.com/stretchr/testify/assert"
6+
)
7+
8+
var (
9+
insertValues = []struct {
10+
nosort []int
11+
sort []int
12+
}{
13+
{[]int{3,44,56,38,77,38,26},[]int{3,26,38,38,44,56,77}},
14+
{[]int{3},[]int{3}},
15+
{[]int{3,-1,-6,34,-78},[]int{-78,-6,-1,3,34}},
16+
}
17+
)
18+
func TestInsertionSort(t *testing.T) {
19+
for _,v := range insertValues {
20+
assert.Exactly(t,v.sort,InsertionSort(v.nosort),"no eq")
21+
}
22+
}

0 commit comments

Comments
 (0)