forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcocktail_sort.go
More file actions
41 lines (32 loc) · 744 Bytes
/
cocktail_sort.go
File metadata and controls
41 lines (32 loc) · 744 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main
import "fmt"
func CocktailSort(slice []int) {
swapped := true
begining := 0
ending := len(slice) - 1
for begining < ending && swapped {
for index := begining; index < ending; index++ {
if slice[index] > slice[index+1] {
slice[index], slice[index+1] = slice[index+1], slice[index]
swapped = true
}
}
ending--
if swapped {
swapped = false
for index := ending; index > begining; index-- {
if slice[index] < slice[index-1] {
slice[index], slice[index-1] = slice[index-1], slice[index]
swapped = true
}
}
}
begining++
}
}
func main() {
slice := []int{1, 5, 8, 3, 7, 4, 9, 6, 2}
fmt.Println("Slice:", slice)
CocktailSort(slice)
fmt.Println("CocktailSort:", slice)
}