-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathcocktailSort.go
More file actions
42 lines (35 loc) · 755 Bytes
/
cocktailSort.go
File metadata and controls
42 lines (35 loc) · 755 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
42
package main
import "fmt"
func cocktailSort(arr []int) {
n := len(arr)
for { // forever loop, as long as there are changes in the array
swapped := false
// reset the 'swapped' flag
for i := 0; i < n-1; i++ {
if arr[i] > arr[i+1] {
arr[i], arr[i+1] = arr[i+1], arr[i]
swapped = true
}
}
// if they are no changes in the entire iteration,
// this means that the algorithm has ended
if !swapped {
break
}
}
}
func main() {
// user input
fmt.Printf("Enter number of elements in array: ")
var n int
fmt.Scanf("%d", &n)
fmt.Printf("Enter the array: ")
var arr []int
for i := 0; i < n; i++ {
var k int
fmt.Scanf("%d", &k)
arr = append(arr, k)
}
cocktailSort(arr)
fmt.Printf("Sorted array: %v\n", arr)
}