-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubblesort.go
84 lines (72 loc) · 1.14 KB
/
bubblesort.go
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import "fmt"
func bubbleSorted(a []string) (int, []string) {
length := len(a)
iteration := 0
for ; iteration<length-1; iteration++ {
swapped := false
for x:=0; x<length-1-iteration; x++ {
if len(a[x]) > len(a[x+1]) {
// fmt.Println("Swapping", x, "and", x+1)
swapped = true
a[x], a[x+1] = a[x+1], a[x]
}
}
// If the last iteration did not swap anything,
// it means all the values are now sorted comlpetely.
if !swapped{
break
}
}
return iteration, a
}
func main() {
a := []string{
"#####",
"############",
"######",
"#",
"##########",
"#########",
"####",
"########",
"##",
}
// Lets print unsorted array
fmt.Println("Unsorted array")
for _,e := range a{
fmt.Println(e)
}
// Sorting array here
iterations, a := bubbleSorted(a)
fmt.Printf("\nIterated %v times.\n", iterations)
// Lets print sorted array
fmt.Println("\nSorted array")
for _,e := range a{
fmt.Println(e)
}
}
// OUTPUT
/*
Unsorted array
#####
############
######
#
##########
#########
####
########
##
Iterated 7 times.
Sorted array
#
##
####
#####
######
########
#########
##########
############
*/