Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding cocktail sort implementation #7

Closed
wants to merge 1 commit into from
Closed
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
27 changes: 27 additions & 0 deletions array/sort/cocktail_sort/Readme.md
Original file line number Diff line number Diff line change
@@ -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) <b>1</b> 4 5 3 2
2) 1 <b>4</b> 5 3 2
3) 1 4 <b>3</b> 5 2
4) 1 4 3 <b>2</b> 5
5) 1 4 3 2 <b>5</b>
5) 1 4 2 <b>3</b> 5
6) 1 2 <b>4</b> 3 5
6) 1 <b>2</b> 4 3 5
7) <b>1</b> 2 4 3 5
8) 1 <b>2</b> 4 3 5
9) 1 2 <b>3</b> 4 5
10) 1 2 3 <b>4</b> 5
11) 1 2 3 4 <b>5</b>

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)
```
24 changes: 24 additions & 0 deletions array/sort/cocktail_sort/cocktail_sort.go
Original file line number Diff line number Diff line change
@@ -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
}
42 changes: 42 additions & 0 deletions array/sort/cocktail_sort/cocktail_sort_test.go
Original file line number Diff line number Diff line change
@@ -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))
})
}
}