From 62b4399322841a8fd5aa9dc0e63bf12fce683ee3 Mon Sep 17 00:00:00 2001 From: Gregory Date: Tue, 14 Dec 2021 12:35:28 +0200 Subject: [PATCH] insertion sort --- sorting/insertion.go | 16 ++++++++++++++++ sorting/sort_test.go | 16 ++++++++++++++++ sorting/testing.go | 8 +++++++- 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 sorting/insertion.go diff --git a/sorting/insertion.go b/sorting/insertion.go new file mode 100644 index 0000000..ee13ad4 --- /dev/null +++ b/sorting/insertion.go @@ -0,0 +1,16 @@ +package sorting + +type insertion struct{} + +func (*insertion) Sort(items Sortable) { + len := items.Len() + for i := 1; i < len; i++ { + for j := i; j > 0 && items.Less(j, j-1); j-- { + items.Swap(j, j-1) + } + } +} + +func NewInsertion() Sorter { + return &insertion{} +} diff --git a/sorting/sort_test.go b/sorting/sort_test.go index 24b6d0e..a45fca5 100644 --- a/sorting/sort_test.go +++ b/sorting/sort_test.go @@ -7,3 +7,19 @@ import ( func TestSelection(t *testing.T) { CheckSorter(NewSelection()) } + +func BenchmarkSelection(b *testing.B) { + for i := 0; i < b.N; i++ { + BenchmarkSort(10000, NewSelection()) + } +} + +func TestInsertion(t *testing.T) { + CheckSorter(NewInsertion()) +} + +func BenchmarkInsertion(b *testing.B) { + for i := 0; i < b.N; i++ { + BenchmarkSort(10000, NewInsertion()) + } +} diff --git a/sorting/testing.go b/sorting/testing.go index b5ec50b..a7c08b3 100644 --- a/sorting/testing.go +++ b/sorting/testing.go @@ -24,7 +24,7 @@ func SameInts(a, b []int) bool { func CheckSorter(s Sorter) { rand.Seed(time.Now().Unix()) - actual := rand.Perm(100) + actual := rand.Perm(1000) expected := make([]int, len(actual)) copy(expected, actual) @@ -35,3 +35,9 @@ func CheckSorter(s Sorter) { log.Fatalf("wrong order:\n actual:\t%v\n expected:\t%v\n", actual, expected) } } + +func BenchmarkSort(numItems int, s Sorter) { + rand.Seed(time.Now().Unix()) + items := rand.Perm(numItems) + s.Sort(IntSort(items)) +}