Skip to content

Commit

Permalink
Merge pull request #596 from harirakr/lab2
Browse files Browse the repository at this point in the history
Add lab2 - Bubble and Insertion sort
  • Loading branch information
harirakr authored Aug 26, 2019
2 parents a35bc0b + 08d1307 commit 892953f
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
42 changes: 42 additions & 0 deletions 02_bubble/harirakr/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import (
"fmt"
"io"
"os"
)

var out io.Writer = os.Stdout

func bubble(s []int) []int {
n := len(s)
cs := append([]int{}, s...)
for i := n; i > 0; i-- {
swapped := false
for j := 0; j < i-1; j++ {
if cs[j] > cs[j+1] {
cs[j], cs[j+1] = cs[j+1], cs[j]
swapped = true
}
}
if !swapped {
break
}
}
return cs
}

func insertion(s []int) []int {
n := len(s)
cs := append([]int{}, s...)
for i := 1; i < n; i++ {
for j := i; j > 0 && cs[j-1] > cs[j]; j-- {
cs[j], cs[j-1] = cs[j-1], cs[j]
}
}
return cs
}

func main() {
fmt.Fprintln(out, bubble([]int{3, 2, 1, 5}))
}
68 changes: 68 additions & 0 deletions 02_bubble/harirakr/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package main

import (
"bytes"
"strconv"
"testing"

"github.com/stretchr/testify/assert"
)

type Data struct {
name string
input []int
expected []int
}

type Sortfns func([]int) []int

func TestMain(t *testing.T) {
var buf bytes.Buffer
out = &buf
main()
assert.Equal(t, "[1 2 3 5]\n", buf.String())
}

func TestSortFunctions(t *testing.T) {

testCases := []Data{
{"Empty set",
[]int{},
[]int{},
},
{"Single element set",
[]int{10},
[]int{10},
},
{"Two element set",
[]int{20, 10},
[]int{10, 20},
},
{"Worst case",
[]int{200, 111, 108, 93, 89, 76, 68, 51, 42, 35},
[]int{35, 42, 51, 68, 76, 89, 93, 108, 111, 200},
},
{"Average case a",
[]int{6, 5, 3, 2, 8, 7, 1, 4},
[]int{1, 2, 3, 4, 5, 6, 7, 8},
},
{"Average case b",
[]int{3, 2, 1, 5},
[]int{1, 2, 3, 5},
},
{"Best case",
[]int{20, 31, 48, 53, 69, 76, 88, 91, 102, 115},
[]int{20, 31, 48, 53, 69, 76, 88, 91, 102, 115},
},
}

for i, fn := range []Sortfns{bubble, insertion} {
fn := fn
for _, tc := range testCases {
tc := tc
t.Run(tc.name+strconv.Itoa(i), func(t *testing.T) {
assert.Equal(t, tc.expected, fn(tc.input))
})
}
}
}

0 comments on commit 892953f

Please sign in to comment.