# Golang : Bubble sort example

Tags : golang sorting bubble-sort

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]

Tags : golang sorting bubble-sort

##### 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

+18.1k Golang : How to redirect to new page with net/http?

+3.9k Golang : Resolve domain name to IP4 and IP6 addresses.

+1.6k Javascript : Empty an array example

+4.9k Golang : How to parse plain email text and process email header?

+8.2k Golang : Compare floating-point numbers

+12.3k Golang : Get and Set User-Agent examples

+4.8k Golang : Calculations using complex numbers example

+3.5k Golang : How to determine a prime number?

+5.5k Golang : Encrypt and decrypt data with x509 crypto

+1.4k Golang : Populate slice with sequential integers example

+5.1k Golang : Convert(cast) string to int64

+2k Golang : Find relative luminance or color brightness