diff --git a/02_bubble/nicholsk/main.go b/02_bubble/nicholsk/main.go new file mode 100644 index 000000000..6b2d64d17 --- /dev/null +++ b/02_bubble/nicholsk/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + "io" + "os" +) + +var out io.Writer = os.Stdout + +func main() { + fmt.Fprintln(out, bubble([]int{3, 2, 1, 5})) +} + +func bubble(s []int) []int { + + // track whether the sort is complete + sorted := false + + for !sorted { + + // track whether any swaps took place in current iteration + swaps := false + + // iterate every index in the list, starting at index 1 + for i := 1; i < len(s); i++ { + + // compare element to previous + if s[i-1] > s[i] { + + // if less than previous then swap elements + s[i], s[i-1] = s[i-1], s[i] + swaps = true + } + + } + + // an iteration with no swaps indicates the array is sorted + if !swaps { + sorted = true + } + } + + return s +} diff --git a/02_bubble/nicholsk/main_test.go b/02_bubble/nicholsk/main_test.go new file mode 100644 index 000000000..9a8c4e9f6 --- /dev/null +++ b/02_bubble/nicholsk/main_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "bytes" + "math/rand" + "sort" + "strconv" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestBubbleSortMain(t *testing.T) { + var buf bytes.Buffer + out = &buf + + main() + + expected := strconv.Quote("[1 2 3 5]\n") + actual := strconv.Quote(buf.String()) + + if expected != actual { + t.Errorf("Unexpected output in main()") + } +} + +func TestBubbleWithSmallSlice(t *testing.T) { + a := assert.New(t) + + sorted := bubble([]int{2, 1}) + expected := []int{1, 2} + + a.Equal(expected, sorted) +} + +func TestBubbleWithRepeatedNumbers(t *testing.T) { + a := assert.New(t) + + sorted := bubble([]int{3, 1, 2, 3, 2, 1}) + expected := []int{1, 1, 2, 2, 3, 3} + + a.Equal(expected, sorted) +} + +func TestBubbleWithLargeSlice(t *testing.T) { + a := assert.New(t) + + expected := make([]int, 100) + for i := range expected { + expected[i] = rand.Intn(1000) + } + + sorted := bubble(expected) + sort.Ints(expected) + + a.Equal(expected, sorted) +} + +func TestBubbleWithSmallSliceIncludingNegativeInts(t *testing.T) { + a := assert.New(t) + + sorted := bubble([]int{1, -2, -3}) + expected := []int{-3, -2, 1} + + a.Equal(expected, sorted) +}