algorithms/sorting/testing.go

60 lines
996 B
Go
Raw Permalink Normal View History

2021-12-06 08:01:25 +02:00
package sorting
import (
"log"
"math/rand"
"sort"
"time"
)
2021-12-16 17:46:10 +02:00
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]
}
2021-12-06 08:01:25 +02:00
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
}
2021-12-16 17:46:10 +02:00
func intCmp(a, b int) bool { return a < b }
func CheckSliceSorter(sorter SliceSorter[int]) {
2021-12-06 08:01:25 +02:00
rand.Seed(time.Now().Unix())
2021-12-14 12:35:28 +02:00
actual := rand.Perm(1000)
2021-12-06 08:01:25 +02:00
expected := make([]int, len(actual))
copy(expected, actual)
2021-12-16 17:46:10 +02:00
sorter(actual, intCmp)
2021-12-06 08:01:25 +02:00
sort.Sort(IntSort(expected))
if !SameInts(actual, expected) {
log.Fatalf("wrong order:\n actual:\t%v\n expected:\t%v\n", actual, expected)
}
}
2021-12-14 12:35:28 +02:00
2021-12-16 17:46:10 +02:00
func BenchmarkSort(numItems int, sorter SliceSorter[int]) {
2021-12-14 12:35:28 +02:00
rand.Seed(time.Now().Unix())
items := rand.Perm(numItems)
2021-12-16 17:46:10 +02:00
sorter(items, intCmp)
2021-12-14 12:35:28 +02:00
}