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
+14k Golang : How to convert a number to words
+18.9k Golang : Check if directory exist and create if does not exist
+10.8k Golang : Read until certain character to break for loop
+13.1k Golang : Generate Code128 barcode
+9.1k Golang : Find the length of big.Int variable example
+9k Golang : Temperatures conversion example
+12k Golang : How to display image file or expose CSS, JS files from localhost?
+5.1k Javascript : Shuffle or randomize array example
+3.4k Golang : Switch Redis database redis.NewClient
+8.6k Golang : HTTP Routing with Goji example
+6.6k Default cipher that OpenSSL used to encrypt a PEM file
+47.2k Golang : Convert int to byte array([]byte)