Skip to content

Commit a96662a

Browse files
authored
Update bubbleSort.go
Move func bubbleSort to the top.
1 parent 828e8d1 commit a96662a

File tree

1 file changed

+21
-17
lines changed

1 file changed

+21
-17
lines changed

sorting/bubbleSort.go

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,26 @@ func main() {
3232
checkSorted(arr)
3333
}
3434

35+
// Sort an array of integers.
36+
func bubbleSort(arr []int) {
37+
// If we had to swap, the array is not sorted yet.
38+
swapped := true
39+
for swapped {
40+
// Assume sorted to begin with. May change during loop.
41+
swapped = false
42+
// Check next element, swap if necessary.
43+
for i,l := 0,len(arr); i < l-1; i++ {
44+
if arr[i] > arr[i+1] {
45+
arr[i], arr[i+1] = arr[i+1], arr[i]
46+
swapped = true
47+
}
48+
}
49+
}
50+
}
51+
52+
// Returns a slice of numItems random ints, up to max.
3553
func makeRandomSlice(numItems, max int) []int {
54+
// We are calling this an array, but it's actually a slice.
3655
arr := make([]int, numItems)
3756

3857
// Seed the random number generator, otherwise it will generate the same set.
@@ -44,6 +63,7 @@ func makeRandomSlice(numItems, max int) []int {
4463
return arr
4564
}
4665

66+
// Prints the first numItems of the slice arr.
4767
func printSlice(arr []int, numItems int) {
4868
if (len(arr) < numItems) {
4969
numItems = len(arr)
@@ -54,6 +74,7 @@ func printSlice(arr []int, numItems int) {
5474
fmt.Println()
5575
}
5676

77+
// Checks to see if arr is sorted.
5778
func checkSorted(arr []int) {
5879
for i := 0; i < len(arr)-1; i++ {
5980
if arr[i] <= arr[i+1] {
@@ -64,20 +85,3 @@ func checkSorted(arr []int) {
6485
}
6586
fmt.Println("The array is sorted")
6687
}
67-
68-
func bubbleSort(arr []int) {
69-
// If we had to swap, the array is not sorted yet.
70-
swapped := true
71-
for swapped {
72-
// Assume sorted to begin with. May change during loop.
73-
swapped = false
74-
// Check next element, swap if necessary.
75-
for i,l := 0,len(arr); i < l-1; i++ {
76-
if arr[i] > arr[i+1] {
77-
arr[i], arr[i+1] = arr[i+1], arr[i]
78-
swapped = true
79-
}
80-
}
81-
}
82-
}
83-

0 commit comments

Comments
 (0)