Bubble Sort with Golang

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.

package main

import (
    "fmt"
)

func main() {
    var nums = []int{5, 8, 2, 4, 0, 1, 3, 7, 9, 6}

    fmt.Println("Before", nums)

    for i := 0; i < len(nums); i++ {
        for j := i+1; j < len(nums); j++ {
            if nums[i] > nums[j] {
                temp := nums[i]
                nums[i] = nums[j]
                nums[j] = temp
            }
        }
    }

    fmt.Println("After", nums)
}
Bubble Sort with Golang output

Leave a Comment