selection sort

This commit is contained in:
Gregory 2021-12-06 08:01:25 +02:00
parent f2817471d1
commit 0e9394e9e1
5 changed files with 94 additions and 0 deletions

15
sorting/int.go Normal file
View file

@ -0,0 +1,15 @@
package sorting
type IntSort []int
func (items IntSort) Len() int {
return len(items)
}
func (items IntSort) Swap(i, j int) {
items[i], items[j] = items[j], items[i]
}
func (items IntSort) Less(i, j int) bool {
return items[i] < items[j]
}

20
sorting/selection.go Normal file
View file

@ -0,0 +1,20 @@
package sorting
type selection struct{}
func (*selection) Sort(items Sortable) {
len := items.Len()
for i := 0; i < len; i++ {
min := i
for j := i + 1; j < len; j++ {
if items.Less(j, min) {
min = j
}
}
items.Swap(min, i)
}
}
func NewSelection() Sorter {
return &selection{}
}

13
sorting/sort.go Normal file
View file

@ -0,0 +1,13 @@
package sorting
type Sortable interface {
Len() int
Swap(i, j int)
Less(i, j int) bool
}
type Sorter interface {
Sort(Sortable)
// TODO: add generic slice sort when type variables are landed
// SortSlice[T any](T, func(i, j int) bool)
}

9
sorting/sort_test.go Normal file
View file

@ -0,0 +1,9 @@
package sorting
import (
"testing"
)
func TestSelection(t *testing.T) {
CheckSorter(NewSelection())
}

37
sorting/testing.go Normal file
View file

@ -0,0 +1,37 @@
package sorting
import (
"log"
"math/rand"
"sort"
"time"
)
func SameInts(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
func CheckSorter(s Sorter) {
rand.Seed(time.Now().Unix())
actual := rand.Perm(100)
expected := make([]int, len(actual))
copy(expected, actual)
s.Sort(IntSort(actual))
sort.Sort(IntSort(expected))
if !SameInts(actual, expected) {
log.Fatalf("wrong order:\n actual:\t%v\n expected:\t%v\n", actual, expected)
}
}