File tree 2 files changed +64
-1
lines changed
2 files changed +64
-1
lines changed Original file line number Diff line number Diff line change
1
+ // Implementation of Cocktail sorting
2
+ // reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort
3
+
4
+ package sort
5
+
6
+ import "github.com/TheAlgorithms/Go/constraints"
7
+
8
+ // Cocktail sort is a variation of bubble sort, operating in two directions (beginning to end, end to beginning)
9
+ func Cocktail [T constraints.Ordered ](arr []T ) []T {
10
+ if len (arr ) == 0 { // ignore 0 length arrays
11
+ return arr
12
+ }
13
+
14
+ swapped := true // true if swapped two or more elements in the last loop
15
+ // if it loops through the array without swapping, the array is sorted
16
+
17
+ // start and end indexes, this will be updated excluding already sorted elements
18
+ start := 0
19
+ end := len (arr ) - 1
20
+
21
+ for swapped {
22
+ swapped = false
23
+ var new_start int
24
+ var new_end int
25
+
26
+ for i := start ; i < end ; i ++ { // first loop, from start to end
27
+ if arr [i ] > arr [i + 1 ] { // if current and next elements are unordered
28
+ arr [i ], arr [i + 1 ] = arr [i + 1 ], arr [i ] // swap two elements
29
+ new_end = i
30
+ swapped = true
31
+ }
32
+ }
33
+
34
+ end = new_end
35
+
36
+ if ! swapped { // early exit, skipping the second loop
37
+ break
38
+ }
39
+
40
+ swapped = false
41
+
42
+ for i := end ; i > start ; i -- { // second loop, from end to start
43
+ if arr [i ] < arr [i - 1 ] { // same process of the first loop, now going 'backwards'
44
+ arr [i ], arr [i - 1 ] = arr [i - 1 ], arr [i ]
45
+ new_start = i
46
+ swapped = true
47
+ }
48
+ }
49
+
50
+ start = new_start
51
+ }
52
+
53
+ return arr
54
+ }
Original file line number Diff line number Diff line change 1
1
package sort_test
2
2
3
3
import (
4
- "github.com/TheAlgorithms/Go/sort"
5
4
"math/rand"
6
5
"reflect"
7
6
"testing"
8
7
"time"
8
+
9
+ "github.com/TheAlgorithms/Go/sort"
9
10
)
10
11
11
12
func testFramework (t * testing.T , sortingFunction func ([]int ) []int ) {
@@ -85,6 +86,10 @@ func TestBucketSort(t *testing.T) {
85
86
testFramework (t , sort .Bucket [int ])
86
87
}
87
88
89
+ func TestCocktailSort (t * testing.T ) {
90
+ testFramework (t , sort .Cocktail [int ])
91
+ }
92
+
88
93
func TestExchange (t * testing.T ) {
89
94
testFramework (t , sort .Exchange [int ])
90
95
}
@@ -222,6 +227,10 @@ func BenchmarkBucketSort(b *testing.B) {
222
227
benchmarkFramework (b , sort .Bucket [int ])
223
228
}
224
229
230
+ func BenchmarkCocktailSort (b * testing.B ) {
231
+ benchmarkFramework (b , sort .Cocktail [int ])
232
+ }
233
+
225
234
func BenchmarkExchange (b * testing.B ) {
226
235
benchmarkFramework (b , sort .Exchange [int ])
227
236
}
You can’t perform that action at this time.
0 commit comments