Golang : Bubble sort example
Example for Bubble sort algorithm implementation in Golang. Bubble sort a.k.a sinking sort, is a simple sorting algorithm that repeatedly steps through the elements in an array to be sorted, compares each pair of adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until no more swaps are needed.
package main
import (
"fmt"
)
func bubbleSort(tosort []int) {
size := len(tosort)
if size < 2 {
return
}
for i := 0; i < size; i++ {
for j := size - 1; j >= i+1; j-- {
if tosort[j] < tosort[j-1] {
tosort[j], tosort[j-1] = tosort[j-1], tosort[j]
}
}
}
}
func main() {
unsorted := []int{1, 199, 3, 2, 5, 80, 99, 500}
fmt.Println("Before : ", unsorted)
bubbleSort(unsorted)
fmt.Println("After : ", unsorted)
}
Output :
Before : [1 199 3 2 5 80 99 500]
After : [1 2 3 5 80 99 199 500]
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+3.8k Java : Random alphabets, alpha-numeric or numbers only string generator
+5.6k PHP : Fix Call to undefined function curl_init() error
+6.4k PHP : Proper way to get UTF-8 character or string length
+12.7k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+7k Golang : constant 20013 overflows byte error message
+14.1k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+5.8k Golang : Find change in a combination of coins example
+19.9k Golang : Count JSON objects and convert to slice/array
+15.2k Golang : Save(pipe) HTTP response into a file
+12.7k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+16.5k Golang : Check if a string contains multiple sub-strings in []string?
+14.6k Golang : How to get URL port?