From 55bd35f9b5a10faf26351abb05ab22fa8c4f7c57 Mon Sep 17 00:00:00 2001 From: dimitrijjedich Date: Mon, 25 Nov 2024 10:40:29 +0100 Subject: [PATCH 1/2] initial commit --- algorithms/shaker.go | 5 +++++ algorithms_test/shaker_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 algorithms/shaker.go create mode 100644 algorithms_test/shaker_test.go diff --git a/algorithms/shaker.go b/algorithms/shaker.go new file mode 100644 index 0000000..980bca6 --- /dev/null +++ b/algorithms/shaker.go @@ -0,0 +1,5 @@ +package algorithms + +func ShakerSort(arr []int) []int { + return arr +} diff --git a/algorithms_test/shaker_test.go b/algorithms_test/shaker_test.go new file mode 100644 index 0000000..1697ef1 --- /dev/null +++ b/algorithms_test/shaker_test.go @@ -0,0 +1,33 @@ +package algorithms_test + +import ( + "github.com/dimitrijjedich/go-algorithms/algorithms" + "reflect" + "testing" +) + +func TestShakerSort(t *testing.T) { + testCases := []struct { + name string + input []int + expected []int + }{ + {"already sorted", []int{1, 2, 3, 4, 5}, []int{1, 2, 3, 4, 5}}, + {"reverse sorted", []int{5, 4, 3, 2, 1}, []int{1, 2, 3, 4, 5}}, + {"unsorted array", []int{5, 3, 8, 6, 2}, []int{2, 3, 5, 6, 8}}, + {"non consecutive array", []int{9, 3, 5, 1, 7}, []int{1, 3, 5, 7, 9}}, + {"empty array", []int{}, []int{}}, + {"single element", []int{42}, []int{42}}, + {"duplicates", []int{3, 1, 2, 3, 1}, []int{1, 1, 2, 3, 3}}, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + result := algorithms.ShakerSort(testCase.input) + + if !reflect.DeepEqual(result, testCase.expected) { + t.Errorf("Failed %s: expected %v, got %v", testCase.name, testCase.expected, result) + } + }) + } +} From 5da8e3a9d9a3f49b178c9efe73f3a51e71dd59ac Mon Sep 17 00:00:00 2001 From: dimitrijjedich Date: Mon, 25 Nov 2024 10:48:32 +0100 Subject: [PATCH 2/2] add initial implementation --- algorithms/shaker.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/algorithms/shaker.go b/algorithms/shaker.go index 980bca6..1a33276 100644 --- a/algorithms/shaker.go +++ b/algorithms/shaker.go @@ -1,5 +1,25 @@ package algorithms func ShakerSort(arr []int) []int { - return arr + n := len(arr) + result := make([]int, n) + copy(result, arr) + + sorted := false + for !sorted { + sorted = true + for i := 0; i < n-1; i++ { + if result[i] > result[i+1] { + result[i], result[i+1] = result[i+1], result[i] + sorted = false + } + } + for i := n - 1; i > 0; i-- { + if result[i] < result[i-1] { + result[i], result[i-1] = result[i-1], result[i] + sorted = false + } + } + } + return result }