Skip to content

Commit 4410a62

Browse files
Merge pull request wangzheng0822#66 from liutianyi1989/master
11_sorts
2 parents af53eac + 74b4b80 commit 4410a62

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed

go/11_sorts/Sort.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package _1_sorts
2+
3+
func BubbleSort(a []int) {
4+
arrLen := len(a)
5+
if arrLen <= 1 {
6+
return
7+
}
8+
for i := arrLen - 1; i > 0; i-- {
9+
for j := 0; j < i; j++ {
10+
if a[j] > a[j+1] {
11+
tmp := a[j+1]
12+
a[j+1] = a[j]
13+
a[j] = tmp
14+
}
15+
}
16+
}
17+
}
18+
19+
func InsertSort(a []int) {
20+
arrLen := len(a)
21+
if arrLen <= 1 {
22+
return
23+
}
24+
for i := 1; i < arrLen; i++ {
25+
v := a[i]
26+
j := i - 1
27+
for ; j >= 0; j-- {
28+
if a[j] > v {
29+
a[j+1] = a[j]
30+
}
31+
}
32+
a[j+1] = v
33+
}
34+
}
35+
36+
func SelectionSort(a []int) {
37+
arrLen := len(a)
38+
if arrLen <= 1 {
39+
return
40+
}
41+
for i := 0; i < arrLen; i++ {
42+
minIndex := i
43+
for j := i + 1; j < arrLen; j++ {
44+
if a[j] < a[minIndex] {
45+
minIndex = j
46+
}
47+
}
48+
if minIndex != i {
49+
tmp := a[minIndex]
50+
a[minIndex] = a[i]
51+
a[i] = tmp
52+
}
53+
}
54+
}

go/11_sorts/Sort_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package _1_sorts
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestBubbleSort(t *testing.T) {
8+
a := []int{5, 4, 3, 2, 1}
9+
BubbleSort(a)
10+
t.Log(a)
11+
}
12+
13+
func TestSelectionSort(t *testing.T) {
14+
a := []int{5, 4, 3, 2, 1}
15+
SelectionSort(a)
16+
t.Log(a)
17+
}
18+
func TestInsertSort(t *testing.T) {
19+
a := []int{5, 4, 3, 2, 1}
20+
InsertSort(a)
21+
t.Log(a)
22+
}
23+
24+
func BenchmarkBubbleSort(b *testing.B) {
25+
a := []int{5, 4, 3, 2, 1}
26+
for i := 0; i < b.N; i++ {
27+
BubbleSort(a)
28+
}
29+
}
30+
31+
func BenchmarkSelectionSort(b *testing.B) {
32+
a := []int{5, 4, 3, 2, 1}
33+
for i := 0; i < b.N; i++ {
34+
SelectionSort(a)
35+
}
36+
}
37+
38+
func BenchmarkInsertSort(b *testing.B) {
39+
a := []int{5, 4, 3, 2, 1}
40+
for i := 0; i < b.N; i++ {
41+
InsertSort(a)
42+
}
43+
}

0 commit comments

Comments
 (0)