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
+15.1k Golang : Get query string value on a POST request
+11k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+5k Golang : Check if a word is countable or not
+19.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+40.8k Golang : How to check if a string contains another sub-string?
+10.1k Golang : Detect number of faces or vehicles in a photo
+10.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+6.5k Golang : How to determine if request or crawl is from Google robots
+16.3k Golang : Get IP addresses of a domain name
+6.8k Golang : Normalize email to prevent multiple signups example
+25.2k Golang : Convert long hexadecimal with strconv.ParseUint example
+12.9k Golang : Calculate elapsed years or months since a date