REST API Tutorial

Simple Bubble Sort with Time Complexity In Golang

Summary of learning

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.

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 (
	"fmt"
	_ "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)
}
If you have requirements that needs our attentioN

Please feel free to contact us

We would love to hear from you

Share with your network

Facebook
Twitter
LinkedIn
WhatsApp
Email

This tutorial is intended to cover all the essentials steps and insights to understand Simple Bubble Sort with Time Complexity In Golang

Genislab Technologies

Learn further