summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2023-04-09 22:25:37 +0300
committerPaul Buetow <paul@buetow.org>2023-04-09 22:25:37 +0300
commit66aae6a827fa58eb753f51acb0a4205608f9bf09 (patch)
tree9d84a83d2bc9c7413b28833604c1624c0bbc903b
parent198ceb7a3c1a6cb4416e861320c4a7c8033f2deb (diff)
add sleep sort
-rw-r--r--sort/sleep.go34
-rw-r--r--sort/sort_test.go27
2 files changed, 58 insertions, 3 deletions
diff --git a/sort/sleep.go b/sort/sleep.go
new file mode 100644
index 0000000..3ca45b2
--- /dev/null
+++ b/sort/sleep.go
@@ -0,0 +1,34 @@
+package sort
+
+import (
+ "codeberg.org/snonux/algorithms/ds"
+ "sync"
+ "time"
+)
+
+func Sleep[V ds.Integer](a ds.ArrayList[V]) ds.ArrayList[V] {
+ sorted := ds.NewArrayList[V](len(a))
+
+ numCh := make(chan V)
+ var wg sync.WaitGroup
+ wg.Add(len(a))
+
+ go func() {
+ wg.Wait()
+ close(numCh)
+ }()
+
+ for _, num := range a {
+ go func(num V) {
+ defer wg.Done()
+ time.Sleep(time.Duration(num) * time.Second)
+ numCh <- num
+ }(num)
+ }
+
+ for num := range numCh {
+ sorted = append(sorted, num)
+ }
+
+ return sorted
+}
diff --git a/sort/sort_test.go b/sort/sort_test.go
index 3cfbc77..fb8870b 100644
--- a/sort/sort_test.go
+++ b/sort/sort_test.go
@@ -20,6 +20,14 @@ var arrayListCache map[string]ds.ArrayList[int]
type sortAlgorithm[V ds.Number] func(ds.ArrayList[V]) ds.ArrayList[V]
type sortAlgorithmInt func([]int) []int
+func TestSleepSort(t *testing.T) {
+ a := ds.NewRandomArrayList[int](10, 10)
+ a = Sleep(a)
+ if !a.Sorted() {
+ t.Errorf("Array not sorted: %v", a)
+ }
+}
+
func TestSelectionSort(t *testing.T) {
for i := minLength; i <= maxSlowLength; i *= factor {
test(Selection[int], i, t)
@@ -79,11 +87,24 @@ func TestQuick3WaySort(t *testing.T) {
func TestShuffleSort(t *testing.T) {
for i := 10; i <= maxLength; i *= factor {
- testShuffle(Shuffle[int], i, t)
+ testShuffleSort(Shuffle[int], i, t)
}
}
-func benchmarknsertionSort(b *testing.B) {
+func BenchmarkSleepSort(b *testing.B) {
+ a := ds.NewRandomArrayList[int](10, 10)
+ aux := ds.NewArrayList[int](10)
+
+ b.Run(fmt.Sprintf("random(%d)", 10), func(b *testing.B) {
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ copy(aux, a)
+ benchResult = Sleep(aux)
+ }
+ })
+}
+
+func BenchmarkInsertionSort(b *testing.B) {
for i := minLength; i <= maxSlowLength; i *= factor {
benchmark(Insertion[int], i, b)
}
@@ -157,7 +178,7 @@ func test[V ds.Number](sort sortAlgorithm[V], l int, t *testing.T) {
t.Run(fmt.Sprintf("%d", l), cb)
}
-func testShuffle[V ds.Number](sort sortAlgorithm[V], l int, t *testing.T) {
+func testShuffleSort[V ds.Number](sort sortAlgorithm[V], l int, t *testing.T) {
cb := func(t *testing.T) {
t.Parallel()
a := sort(ds.NewAscendingArrayList[V](l))