MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / Cocktail

Function Cocktail

sort/cocktailsort.go:9–54  ·  view source on GitHub ↗

Cocktail sort is a variation of bubble sort, operating in two directions (beginning to end, end to beginning)

(arr []T)

Source from the content-addressed store, hash-verified

7
8// Cocktail sort is a variation of bubble sort, operating in two directions (beginning to end, end to beginning)
9func 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}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected