Solution Review: Bubble Sort the Slice
This lesson discusses the solution to the challenge given in the previous lesson.
We'll cover the following...
Press + to interact
package mainimport ("fmt")func main() {sla := []int{2, 6, 4, -10, 8, 89, 12, 68, -45, 37}fmt.Println("before sort: ",sla)// sla is passed via call by value, but since sla is a reference type// the underlying array is changed (sorted)bubbleSort(sla)fmt.Println("after sort: ",sla)}func bubbleSort(sl []int) {// passes through the slice:for pass:=1; pass < len(sl); pass++ {// one pass:for i:=0; i < len(sl) - pass; i++ { // the bigger value 'bubbles up' to the last positionif sl[i] > sl[i+1] {sl[i], sl[i+1] = sl[i+1], sl[i]}}}}
In the program above, in main
at line 7, we make a slice sla
of integers and assign random integers to it in an unsorted manner. Now, at line 11, we call the function bubbleSort
and pass sla
to it. Look at the header for bubbleSort
at line 15, it ...