From 12de3f78e0bf9dde7f29d48102cce40dc0f59820 Mon Sep 17 00:00:00 2001 From: Gregory Eremin Date: Mon, 12 Oct 2015 01:28:58 +0300 Subject: [PATCH] Implemented sleep sort algorithm --- sort/sleep_sort.go | 37 +++++++++++++++++++++++++++++++++++++ sort/sleep_sort_test.go | 12 ++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 sort/sleep_sort.go create mode 100644 sort/sleep_sort_test.go diff --git a/sort/sleep_sort.go b/sort/sleep_sort.go new file mode 100644 index 0000000..d76da2c --- /dev/null +++ b/sort/sleep_sort.go @@ -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 +} diff --git a/sort/sleep_sort_test.go b/sort/sleep_sort_test.go new file mode 100644 index 0000000..b7790b2 --- /dev/null +++ b/sort/sleep_sort_test.go @@ -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}, + ) +}