File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments