From 77540e759f97b05ff53b14c252f3aa65064a1e74 Mon Sep 17 00:00:00 2001 From: Matheus Alves Date: Wed, 23 Oct 2019 23:24:40 -0300 Subject: [PATCH] Adding cocktail sort implementation --- array/sort/cocktail_sort/Readme.md | 27 ++++++++++++ array/sort/cocktail_sort/cocktail_sort.go | 24 +++++++++++ .../sort/cocktail_sort/cocktail_sort_test.go | 42 +++++++++++++++++++ 3 files changed, 93 insertions(+) create mode 100644 array/sort/cocktail_sort/Readme.md create mode 100644 array/sort/cocktail_sort/cocktail_sort.go create mode 100644 array/sort/cocktail_sort/cocktail_sort_test.go diff --git a/array/sort/cocktail_sort/Readme.md b/array/sort/cocktail_sort/Readme.md new file mode 100644 index 0000000..6518792 --- /dev/null +++ b/array/sort/cocktail_sort/Readme.md @@ -0,0 +1,27 @@ +# Cocktail Sort +It is a sorting algorithm that iterates over an array in both directions, leaving the largest elements to the right, and the lowest elements to the left. It is a variation of the Bubble Sort Algorithm. + +### Example +[1, 4, 5, 3, 2] + +1) 1 4 5 3 2 +2) 1 4 5 3 2 +3) 1 4 3 5 2 +4) 1 4 3 2 5 +5) 1 4 3 2 5 +5) 1 4 2 3 5 +6) 1 2 4 3 5 +6) 1 2 4 3 5 +7) 1 2 4 3 5 +8) 1 2 4 3 5 +9) 1 2 3 4 5 +10) 1 2 3 4 5 +11) 1 2 3 4 5 + +And then, the array is sorted. + +``` +Best case (When it is already sorted): O(n) +Worst case: O(n^2) +Average time complexity: O(n^2) +``` diff --git a/array/sort/cocktail_sort/cocktail_sort.go b/array/sort/cocktail_sort/cocktail_sort.go new file mode 100644 index 0000000..9d4be07 --- /dev/null +++ b/array/sort/cocktail_sort/cocktail_sort.go @@ -0,0 +1,24 @@ +package sort + +func CocktailSort(arr []int) []int { + swapped := true + for swapped { + swapped = false + for i := 0; i < len(arr)-1; i++ { + if arr[i] > arr[i+1] { + arr[i], arr[i+1] = arr[i+1], arr[i] + swapped = true + } + } + if !swapped { + break + } + for i := len(arr) - 1; i > 0; i-- { + if arr[i] < arr[i-1] { + arr[i], arr[i-1] = arr[i-1], arr[i] + swapped = true + } + } + } + return arr +} diff --git a/array/sort/cocktail_sort/cocktail_sort_test.go b/array/sort/cocktail_sort/cocktail_sort_test.go new file mode 100644 index 0000000..d3e4f55 --- /dev/null +++ b/array/sort/cocktail_sort/cocktail_sort_test.go @@ -0,0 +1,42 @@ +package sort + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCocktailSort(t *testing.T) { + tests := []struct { + name string + arr []int + valid []int + }{ + { + "Unsorted array", + []int{5, 3, 2, 1, 8, 4}, + []int{1, 2, 3, 4, 5, 8}, + }, + { + "Sorted array", + []int{1, 2, 3, 4, 5, 6}, + []int{1, 2, 3, 4, 5, 6}, + }, + { + "Equal values", + []int{5, 5, 5, 5, 5, 5}, + []int{5, 5, 5, 5, 5, 5}, + }, + { + "Sorted and reversed", + []int{6, 5, 4, 3, 2, 1}, + []int{1, 2, 3, 4, 5, 6}, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + assert.Equal(t, test.valid, CocktailSort(test.arr)) + }) + } +}