summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2020-07-12 11:35:03 +0100
committerPaul Buetow <paul@buetow.org>2020-07-12 11:35:03 +0100
commit4edf2dd20b300c27dcc96829e262aedcd438291a (patch)
treef4596883c8210b4e855166289f482efb907bec64
have selection sort
-rw-r--r--Makefile4
-rw-r--r--ds/comparer.go9
-rw-r--r--ds/integer.go25
-rw-r--r--main.go14
-rw-r--r--sort/selection.go24
-rw-r--r--sort/selection_test.go12
6 files changed, 88 insertions, 0 deletions
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..6883353
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,4 @@
+all:
+ go build
+test:
+ go run main.go
diff --git a/ds/comparer.go b/ds/comparer.go
new file mode 100644
index 0000000..737ad1b
--- /dev/null
+++ b/ds/comparer.go
@@ -0,0 +1,9 @@
+package ds
+
+type Comparer interface {
+ LowerThan(a Comparer) bool
+ HigherThan(a Comparer) bool
+ Equals(a Comparer) bool
+}
+
+type CompareList []Comparer
diff --git a/ds/integer.go b/ds/integer.go
new file mode 100644
index 0000000..69ee0aa
--- /dev/null
+++ b/ds/integer.go
@@ -0,0 +1,25 @@
+package ds
+
+import "math/rand"
+
+type Integer int
+
+func RandomIntegers(length, max int) []Comparer {
+ a := make([]Comparer, length)
+ for i := 0; i < length; i++ {
+ a[i] = Integer(rand.Intn(max))
+ }
+ return a
+}
+
+func (i Integer) LowerThan(j Comparer) bool {
+ return i < j.(Integer)
+}
+
+func (i Integer) HigherThan(j Comparer) bool {
+ return i > j.(Integer)
+}
+
+func (i Integer) Equals(j Comparer) bool {
+ return i == j.(Integer)
+}
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..aa4a82f
--- /dev/null
+++ b/main.go
@@ -0,0 +1,14 @@
+package main
+
+import (
+ "algorithms/ds"
+ "algorithms/sort"
+ "fmt"
+)
+
+func main() {
+ fmt.Println("Hello to Algorithms Playground!")
+ a := ds.RandomIntegers(100, 1000)
+ fmt.Printf("Random: %v\n", a)
+ fmt.Printf("Sorted: %v\n", sort.Selection(a))
+}
diff --git a/sort/selection.go b/sort/selection.go
new file mode 100644
index 0000000..e2a774c
--- /dev/null
+++ b/sort/selection.go
@@ -0,0 +1,24 @@
+package sort
+
+import (
+ "algorithms/ds"
+)
+
+func Selection(a []ds.Comparer) []ds.Comparer {
+ length := len(a)
+ for i := 0; i < length; i++ {
+ max := i
+ for j := i + 1; j < length; j++ {
+ if a[max].HigherThan(a[j]) {
+ max = j
+ }
+ }
+ if max == i {
+ continue
+ }
+ tmp := a[i]
+ a[i] = a[max]
+ a[max] = tmp
+ }
+ return a
+}
diff --git a/sort/selection_test.go b/sort/selection_test.go
new file mode 100644
index 0000000..3881850
--- /dev/null
+++ b/sort/selection_test.go
@@ -0,0 +1,12 @@
+package sort
+
+import (
+ "algorithms/ds"
+ "testing"
+)
+
+func BenchmarkSelection1000(b *testing.B) {
+ a := ds.RandomIntegers(1000, 1000)
+ b.ResetTimer()
+ Selection(a)
+}