diff --git a/sort/comb_sort/comb_sort.go b/sort/comb_sort/comb_sort.go index 253ba12..9007551 100644 --- a/sort/comb_sort/comb_sort.go +++ b/sort/comb_sort/comb_sort.go @@ -1,45 +1,34 @@ -package main - -/* - * Comb sort - https://en.wikipedia.org/wiki/Combsort - */ - -import "fmt" - -import "github.com/0xAX/go-algorithms" - -func main() { - arr := utils.RandArray(10) - fmt.Println("Initial array is:", arr) - fmt.Println("") - - tmp := 0 - gap := len(arr) - - for { - if gap > 1 { - gap = gap * 100 / 124 - } - - for i := 0 ; ; { - - if arr[i] > arr[i + gap] { - tmp = arr[i] - arr[i] = arr[i + gap] - arr[i + gap] = tmp - } - - i++ - - if i + gap >= len(arr){ - break - } - } - - if gap == 1 { - break - } - } - - fmt.Println("Sorted array is: ", arr) +package comb_sort + +import ( + sortable "github.com/0xAX/go-algorithms/sort" +) + +func Sort(data sortable.Sortable) sortable.Sortable { + gap := data.Len() + + for { + if gap > 1 { + gap = gap * 100 / 124 + } + + for i := 0; ; { + + if data.Less(i+gap, i) { + data.Swap(i, i+gap) + } + + i++ + + if i+gap >= data.Len() { + break + } + } + + if gap == 1 { + break + } + } + + return data } diff --git a/sort/comb_sort/comb_sort_test.go b/sort/comb_sort/comb_sort_test.go new file mode 100644 index 0000000..958b267 --- /dev/null +++ b/sort/comb_sort/comb_sort_test.go @@ -0,0 +1,25 @@ +package comb_sort + +import ( + sortable "github.com/0xAX/go-algorithms/sort" + "math/rand" + "testing" +) + +func TestSort(t *testing.T) { + var s = make(sortable.IntSlice, 10) + + for i := 0; i < 10; i++ { + s[i] = rand.Intn(i + 1) + } + + Sort(&s) + + for i := 0; i < 10; i++ { + if i != 9 { + if s[i] > s[i+1] { + t.Fatal("s[i] > s[i + 1]", s[i], s[i+1]) + } + } + } +}