@@ -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.
3553func 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.
4767func 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.
5778func 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