summaryrefslogtreecommitdiff
path: root/sort
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2020-07-14 09:34:50 +0100
committerPaul Buetow <paul@buetow.org>2020-07-14 09:34:50 +0100
commitaee630b03f48a9f528a4a50e9dcb0fdc8ef20aa5 (patch)
tree152644259dd29dee9dac930cca9f26e4b9422112 /sort
parent554a7a259f3feefb586374ac5a3b57acc99a4446 (diff)
add bench helper
Diffstat (limited to 'sort')
-rw-r--r--sort/bench.go21
-rw-r--r--sort/insertion_test.go14
-rw-r--r--sort/selection_test.go14
-rw-r--r--sort/sorted.go12
4 files changed, 55 insertions, 6 deletions
diff --git a/sort/bench.go b/sort/bench.go
new file mode 100644
index 0000000..094debd
--- /dev/null
+++ b/sort/bench.go
@@ -0,0 +1,21 @@
+package sort
+
+import (
+ "algorithms/ds"
+ "fmt"
+ "testing"
+)
+
+// Avoid compiler optimizations
+var benchResult []ds.Comparer
+
+func benchmark(name string, length int, sort func([]ds.Comparer) []ds.Comparer, b *testing.B) {
+ cb := func(b *testing.B) {
+ a := ds.RandomIntegers(length, length)
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ benchResult = sort(a)
+ }
+ }
+ b.Run(fmt.Sprintf("Benchmark%s%d", name, length), cb)
+}
diff --git a/sort/insertion_test.go b/sort/insertion_test.go
index 4b503b8..afec414 100644
--- a/sort/insertion_test.go
+++ b/sort/insertion_test.go
@@ -5,8 +5,16 @@ import (
"testing"
)
-func BenchmarkInsertion1000(b *testing.B) {
+func BenchmarkInsertion(b *testing.B) {
+ benchmark("Insertion", 10, Insertion, b)
+ benchmark("Insertion", 100, Insertion, b)
+ benchmark("Insertion", 1000, Insertion, b)
+}
+
+func TestInsertion1000(t *testing.T) {
a := ds.RandomIntegers(1000, 1000)
- b.ResetTimer()
- Insertion(a)
+ a = Insertion(a)
+ if !Sorted(a) {
+ t.Errorf("Array not sorted: %v", a)
+ }
}
diff --git a/sort/selection_test.go b/sort/selection_test.go
index 3881850..c5d6beb 100644
--- a/sort/selection_test.go
+++ b/sort/selection_test.go
@@ -5,8 +5,16 @@ import (
"testing"
)
-func BenchmarkSelection1000(b *testing.B) {
+func BenchmarkSelection(b *testing.B) {
+ benchmark("Selection", 10, Selection, b)
+ benchmark("Selection", 100, Selection, b)
+ benchmark("Selection", 1000, Selection, b)
+}
+
+func TestSelection1000(t *testing.T) {
a := ds.RandomIntegers(1000, 1000)
- b.ResetTimer()
- Selection(a)
+ a = Selection(a)
+ if !Sorted(a) {
+ t.Errorf("Array not sorted: %v", a)
+ }
}
diff --git a/sort/sorted.go b/sort/sorted.go
new file mode 100644
index 0000000..a24de19
--- /dev/null
+++ b/sort/sorted.go
@@ -0,0 +1,12 @@
+package sort
+
+import "algorithms/ds"
+
+func Sorted(a []ds.Comparer) bool {
+ for i := len(a) - 1; i > 0; i-- {
+ if a[i].LowerThan(a[i-1]) {
+ return false
+ }
+ }
+ return true
+}