Hello everyone, in this tutorial, we will learn how to write a simple Bubble Sort in Golang programming language. This example program has been tested and shared in the same post.
What is Bubble Sort?
The bubble sort is one of the easiest sorting algorithm that works by iteratively swapping an elements if they are in the wrong order. The below example will give you an idea about swapping based on the iteration.

[4, 2, 1, 5, 3] [4, 2, 1, 5, 3] [4, 2, 1, 5, 3] -> Iteration 1 [5, 2, 1, 4, 3] [5, 2, 1, 4, 3] [2, 5, 1, 4, 3] [2, 5, 1, 4, 3] [2, 5, 1, 4, 3] -> Iteration 2 [2, 5, 1, 4, 3] [2, 5, 1, 4, 3] [1, 5, 2, 4, 3] [1, 2, 5, 4, 3] [1, 2, 5, 4, 3] -> Iteration 3 [1, 2, 5, 4, 3] [1, 2, 5, 4, 3] [1, 2, 5, 4, 3] [1, 2, 5, 4, 3] [1, 2, 4, 5, 3] -> Iteration 4 [1, 2, 4, 5, 3] [1, 2, 4, 5, 3] [1, 2, 4, 5, 3] [1, 2, 4, 5, 3] [1, 2, 3, 5, 4] -> Iteration 5 [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
Function – Bubble Sort in Golang
The below function is responsible to sort a given numbers array by using Bubble Sort algorithm.
// function to sort number using Bubblesort Algorithm func bubbleSort(numbers []int) []int { if numbers != nil && len(numbers) > 0 { for i := 0; i < len(numbers); i++ { for j := 0; j < len(numbers); j++ { if numbers[i] < numbers[j] { // swapping the numbers temp := numbers[i] numbers[i] = numbers[j] numbers[j] = temp } } } } else { fmt.Println("Empty or Null Array") } return numbers }
Full Example
package main import "fmt" // function to sort number using Bubblesort Algorithm func bubbleSort(numbers []int) []int { if numbers != nil && len(numbers) > 0 { for i := 0; i < len(numbers); i++ { for j := 0; j < len(numbers); j++ { if numbers[i] < numbers[j] { // swapping the numbers temp := numbers[i] numbers[i] = numbers[j] numbers[j] = temp } } } } else { fmt.Println("Empty or Null Array") } return numbers } // main function func main() { fmt.Println("Bubble Sort \n") // creating an integer array with values numbers := []int{4, 2, 1, 5, 3} fmt.Println("Before Sorting:", numbers) // calling the bubbleSort function numbers = bubbleSort(numbers) fmt.Println("\nAfter Sorting:", numbers) }
Output
Bubble Sort Before Sorting: [4 2 1 5 3] After Sorting: [1 2 3 4 5]
References
- https://www.hackerearth.com/practice/algorithms/sorting/bubble-sort/tutorial/
- https://en.wikipedia.org/wiki/Bubble_sort
- https://idineshkrishnan.com/python-bubble-sort-example/
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No Responses