Skip to content

Commit 5ef02ef

Browse files
committed
add selection sort
1 parent 190f247 commit 5ef02ef

File tree

5 files changed

+52
-0
lines changed

5 files changed

+52
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.vscode/

go.mod

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
module algorithm
2+
3+
go 1.14
4+
5+
require github.com/stretchr/testify v1.6.1

go.sum

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
2+
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3+
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
4+
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
5+
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
6+
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
7+
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
8+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
9+
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
10+
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

selection_sort.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package algorithm
2+
3+
// SelectionSort ..
4+
// 算法步骤:
5+
// 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置。
6+
// 再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
7+
// 重复第二步,直到所有元素均排序完毕。
8+
func SelectionSort(arr []int) []int {
9+
length := len(arr)
10+
for i := 0; i < length-1; i++ {
11+
min := i
12+
for j := i + 1; j < length; j++ {
13+
if arr[min] > arr[j] {
14+
min = j
15+
}
16+
}
17+
arr[i], arr[min] = arr[min], arr[i]
18+
}
19+
return arr
20+
}

selection_sort_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package algorithm
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func TestSelectionSort(t *testing.T) {
11+
arr := []int{3, 2, 0, 5, 10, 1}
12+
arrSort := SelectionSort(arr)
13+
fmt.Printf("arr after sored: %v\n", arrSort)
14+
assert.Equal(t, 10, arrSort[5])
15+
assert.Equal(t, 5, arrSort[4])
16+
}

0 commit comments

Comments
 (0)