Skip to content

Commit c715abc

Browse files
joonazanthecodershub
authored andcommitted
Go bubblesort
Ref thecodershub#47
1 parent d7f858f commit c715abc

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed
File renamed without changes.

go/bubblesort/sort.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package bubblesort
2+
3+
func sort(s []int) {
4+
for {
5+
swapped := false
6+
7+
for i := 0; i < len(s)-1; i++ {
8+
if s[i] > s[i+1] {
9+
s[i], s[i+1] = s[i+1], s[i]
10+
swapped = true
11+
}
12+
}
13+
14+
if !swapped {
15+
break
16+
}
17+
}
18+
}

go/bubblesort/sort_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package bubblesort
2+
3+
import "testing"
4+
5+
func withInput(t *testing.T, input []int) {
6+
sort(input)
7+
8+
for i := 1; i < len(input); i++ {
9+
if input[i-1] > input[i] {
10+
t.Fatalf("Got %v instead of nondecreasing slice.", input)
11+
}
12+
}
13+
}
14+
15+
func TestEmpty(t *testing.T) {
16+
withInput(t, []int{})
17+
}
18+
19+
func TestOne(t *testing.T) {
20+
withInput(t, []int{1})
21+
}
22+
23+
func TestFiveNumbers(t *testing.T) {
24+
withInput(t, []int{8, 2, 3, 8, -1})
25+
}
26+
27+
func TestSorted(t *testing.T) {
28+
withInput(t, []int{3, 4, 5, 6, 8})
29+
}

0 commit comments

Comments
 (0)