Skip to content

Commit

Permalink
Merge pull request wangzheng0822#66 from liutianyi1989/master
Browse files Browse the repository at this point in the history
11_sorts
  • Loading branch information
wangzheng0822 authored Oct 16, 2018
2 parents af53eac + 74b4b80 commit 4410a62
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
54 changes: 54 additions & 0 deletions go/11_sorts/Sort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package _1_sorts

func BubbleSort(a []int) {
arrLen := len(a)
if arrLen <= 1 {
return
}
for i := arrLen - 1; i > 0; i-- {
for j := 0; j < i; j++ {
if a[j] > a[j+1] {
tmp := a[j+1]
a[j+1] = a[j]
a[j] = tmp
}
}
}
}

func InsertSort(a []int) {
arrLen := len(a)
if arrLen <= 1 {
return
}
for i := 1; i < arrLen; i++ {
v := a[i]
j := i - 1
for ; j >= 0; j-- {
if a[j] > v {
a[j+1] = a[j]
}
}
a[j+1] = v
}
}

func SelectionSort(a []int) {
arrLen := len(a)
if arrLen <= 1 {
return
}
for i := 0; i < arrLen; i++ {
minIndex := i
for j := i + 1; j < arrLen; j++ {
if a[j] < a[minIndex] {
minIndex = j
}
}
if minIndex != i {
tmp := a[minIndex]
a[minIndex] = a[i]
a[i] = tmp
}
}
}
43 changes: 43 additions & 0 deletions go/11_sorts/Sort_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package _1_sorts

import (
"testing"
)

func TestBubbleSort(t *testing.T) {
a := []int{5, 4, 3, 2, 1}
BubbleSort(a)
t.Log(a)
}

func TestSelectionSort(t *testing.T) {
a := []int{5, 4, 3, 2, 1}
SelectionSort(a)
t.Log(a)
}
func TestInsertSort(t *testing.T) {
a := []int{5, 4, 3, 2, 1}
InsertSort(a)
t.Log(a)
}

func BenchmarkBubbleSort(b *testing.B) {
a := []int{5, 4, 3, 2, 1}
for i := 0; i < b.N; i++ {
BubbleSort(a)
}
}

func BenchmarkSelectionSort(b *testing.B) {
a := []int{5, 4, 3, 2, 1}
for i := 0; i < b.N; i++ {
SelectionSort(a)
}
}

func BenchmarkInsertSort(b *testing.B) {
a := []int{5, 4, 3, 2, 1}
for i := 0; i < b.N; i++ {
InsertSort(a)
}
}

0 comments on commit 4410a62

Please sign in to comment.