Skip to content

Commit 6723515

Browse files
committed
implemented cocktail sort in golang
1 parent 15874a1 commit 6723515

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func cocktailSort(arr []int) {
6+
n := len(arr)
7+
for { // forever loop, as long as there are changes in the array
8+
swapped := false
9+
// reset the 'swapped' flag
10+
for i := 0; i < n-1; i++ {
11+
if arr[i] > arr[i+1] {
12+
arr[i], arr[i+1] = arr[i+1], arr[i]
13+
swapped = true
14+
}
15+
}
16+
// if they are no changes in the entire iteration,
17+
// this means that the algorithm has ended
18+
if !swapped {
19+
break
20+
}
21+
}
22+
}
23+
24+
func main() {
25+
26+
// user input
27+
fmt.Printf("Enter number of elements in array: ")
28+
var n int
29+
fmt.Scanf("%d", &n)
30+
31+
fmt.Printf("Enter the array: ")
32+
var arr []int
33+
for i := 0; i < n; i++ {
34+
var k int
35+
fmt.Scanf("%d", &k)
36+
arr = append(arr, k)
37+
}
38+
39+
cocktailSort(arr)
40+
41+
fmt.Printf("Sorted array: %v\n", arr)
42+
}

0 commit comments

Comments
 (0)