Write a Golang program to sort an array using Bubble Sort


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

Examples

Input arr = [7, 5, 1, 6, 3]

  • 1st iteration => swap(7, 5) => swap(7, 1) => swap(7, 6) => swap(7, 3) => [5, 1, 6, 3, 7]
  • 2nd iteration => [1, 5, 3, 6, 7]
  • 3rd iteration => [1, 3, 5, 6, 7]
  • 4th iteration => [1, 3, 5, 6, 7]
  • 5th iteration => [1, 3, 5, 6, 7]

Approach to solve this problem

Step 1: Iterate the array from 0th index to n-1.

Step 2: Iterate the array from the 0th index to n-1-i, where i is the index of the above loop.

Step 3: Swap if the highest element is at the starting position of an array, else leave.

Step 3: At the end, return the array.

Time Complexity: O(n2)

Program

Live Demo

package main
import "fmt"
func bubbleSort(arr []int) []int{

   for i:=0; i<=len(arr)-1; i++{
      for j:=0; j<len(arr)-1-i; j++{
         if arr[j]> arr[j+1]{
            arr[j], arr[j+1] = arr[j+1], arr[j]
         }
      }
   }
   return arr
}

Output

[0 1 2 5 6]
[2 3 4 5 6]
[1 2 3 4 5]

Updated on: 04-Feb-2021

425 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements