# Golang. Bubble sorting

О… how much is in this “Chink”-sound!.. We learned to sort by “bubble” back in school (hello, Mr.Obama!). Why not make a code for this sorting in Go? 😀 Even if it is seldom useful, it’s a good exercise for beginners.

Our program will take a string of integers separated by spaces, convert them to a slice of integers and sort the slice in ascending order… Code:

```package main

import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)

func main() {

strInput = strings.TrimSpace(strInput)

strSlice := strings.Split(strInput, " ")
var nums []int

for _, v := range strSlice {
num, _ := strconv.Atoi(v)
nums = append(nums, num)
}

// Bubble sort
// 1) Compare two adjacent values
// 2) swap them it lowest value stays at right position
// 3) continue until there won't be any swaps

for {
for i := 0; i < len(nums)-1; i++ {
if nums[i] > nums[i+1] {
nums[i], nums[i+1] = nums[i+1], nums[i]
}
}
break
}
}

fmt.Println(nums)
}
```

So, what we have here.

As usual, we import lots of packages, including “bufio” to read input, “fmt” to output, “os” to access system information, “strconv” to convert strings to integers and “strings” to handle strings.

Next, we wildly write the main function, which begins by creating a new buffered reader “r” – it reads data from standard input using the “os” package.

Finally, our input is read as a string and assigned to the “strInput” variable. Here we use the “strings” package to remove spaces from the input string.

Then we cleverly split the string into separate integers using the awesome “strings.Split()” function, and each integer is stored as the apple of the eye as a string in a slice called “strSlice”.

Next, armed with “strconv.Atoi()” we convert each string in “strSlice” to an integer, which is then added to a new slice called “nums”.

Ok. Now it’s time to unholster our bubble sorting cannon… We cocoon our outer loop in besconeity, and there we make the wise assumption that the slice hasn’t been sorted yet (by setting the “ready” flag to true). The inner loop iterates over the slice “nums”, comparing each pair of neighboring integers. If the current integer is greater than the next integer, they swap places, and the ready variable is set to false. Here it is, street magic, in my mouth and my feet!

Finally, if the outer loop completes without swapping the integers, the ready variable remains true – then the loop is interrupted, indicating that the “nums” slice is now sorted. Hallelujah!

This entry was posted in Go (en). Bookmark the permalink.