1
0
Fork 0

Implemented sleep sort algorithm

This commit is contained in:
Gregory Eremin 2015-10-12 01:28:58 +03:00
parent b929919bfb
commit 12de3f78e0
No known key found for this signature in database
GPG Key ID: 5EFA427EEC26E86C
2 changed files with 49 additions and 0 deletions

37
sort/sleep_sort.go Normal file
View File

@ -0,0 +1,37 @@
package sort
import (
"time"
)
const (
// SleepSortTimeout is the default sleep sort timeout in millisecond.
SleepSortTimeout = 5
)
// SleepSort is an implementation of sleep sort algorithm.
func SleepSort(a []int) []int {
return SleepSortWithTimeout(a, SleepSortTimeout)
}
// SleepSortWithTimeout is an implementation of sleep sort algorithm with user
// defined sleep timeout.
func SleepSortWithTimeout(a []int, timeout time.Duration) []int {
start := make(chan struct{})
results := make(chan int, len(a))
for _, val := range a {
go func(val int) {
<-start
<-time.After(time.Duration(val) * time.Millisecond)
results <- val
}(val)
}
close(start)
for i := range a {
a[i] = <-results
}
return a
}

12
sort/sleep_sort_test.go Normal file
View File

@ -0,0 +1,12 @@
package sort
import (
"testing"
)
func TestSleepSort(t *testing.T) {
testSort(t, SleepSort,
[]int{5, 3, 1, 4, 2},
[]int{1, 2, 3, 4, 5},
)
}