Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions algorithms/shaker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package algorithms

func ShakerSort(arr []int) []int {
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
}
33 changes: 33 additions & 0 deletions algorithms_test/shaker_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}