Simple Bubble Sort with Time Complexity In Golang

Simple Bubble Sort with Time Complexity In Golang

This tutorial helps to create bubble sort in golang, The bubble sort help to sort the elements using the comparison between the current node with the immediate next node, based on condition.

The element will swap according to the requirement and goes down to the last element one by one. At the end of the first phase, the last element has maximized the element of the list.

The Bubble sort follows the following rule:

  • Step 1: Start from the left-hand side of the array
  • Step 2: Compare the first two numbers of 0 and 1 index
  • Step 3: If a[0] > a[1] than swap both number positions. And if a[0] < a[1] than do now swap and compare the next two numbers i.e. a[1] and a[2].
  • Step 4: Step-3 process repeats until there are no more numbers left to compare.

The time complexity is Ω(n) and worst is O(n^2).

package main

import (
        _ "os"

func main() {
        a := []int{31, 8, 6, 54, 95, 84, 71, 67}
        fmt.Printf("%v\n", a)

        len_arr := len(a) - 1
        fmt.Printf("The length of array : %v\n", len_arr)

        for i := 0; i < len_arr; i++ {
                for j := 0; j < len_arr-i; j++ {
                        fmt.Printf("first index:%v The value : %v\n", a[j], a[j+1])
                        if a[j] > a[j+1] {
                                tmp := a[j]
                                a[j] = a[j+1]
                                a[j+1] = tmp

                fmt.Println("Iteration=======================", i+1)

                fmt.Printf("\nYour sort Array : %v\n", a)


        fmt.Printf("Your sort Array : %v", a)