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
+10.6k Golang : Select region of interest with mouse click and crop from image
+8.3k Golang : Emulate NumPy way of creating matrix example
+5.7k Unix/Linux : How to find out the hard disk size?
+6.3k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+8.6k Android Studio : Import third-party library or package into Gradle Scripts
+18.5k Golang : Example for RSA package functions
+18.3k Golang : Get command line arguments
+52.7k Golang : How to get struct field and value by name
+7k Nginx : Password protect a directory/folder
+4.9k Facebook : How to place save to Facebook button on your website
+24.1k Golang : Find biggest/largest number in array
+33.7k Golang : How to check if slice or array is empty?