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
+6.6k Get Facebook friends working in same company
+13.4k Golang : How to determine if a year is leap year?
+12.5k Golang : Convert int(year) to time.Time type
+22.2k Golang : Set and Get HTTP request headers example
+11.7k Golang : Determine if time variables have same calendar day
+23.4k Golang : Fix type interface{} has no field or no methods and type assertions example
+17.4k Golang : Iterate linked list example
+7.7k Golang : Check from web if Go application is running or not
+24.6k Golang : Create PDF file from HTML file
+33.6k Golang : Call a function after some delay(time.Sleep and Tick)
+77.6k Golang : How to return HTTP status code?