move comb_sort to separate package
Signed-off-by: Alexander Kuleshov <kuleshovmail@gmail.com>move-sorts-to-separate-packages
parent
22a9e841eb
commit
63d2d69629
@ -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
|
||||
}
|
||||
|
@ -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])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue