Go Program to Implement Bubble Sort

Bubble sort is a straightforward sorting algorithm that operates by repeatedly traversing a list and comparing adjacent items. If the items are in the wrong order, they're swapped. This process continues until no more swaps are needed, which indicates that the list is sorted.

In this blog post, we'll explore an implementation of the bubble sort algorithm using the Go programming language.

Program Steps

The basic steps of the bubble sort algorithm are: 

Input: An unsorted list of elements. 

Processing: 

  • Traverse the entire array. 
  • Compare adjacent elements. 
  • If they are in the wrong order, swap them. 
  • Continue this process for each element, reducing the number of elements to check by one with each full pass through the list. 

Output: A sorted list of elements. 

Code Program

package main

import "fmt"

// BubbleSort function sorts an array using the bubble sort algorithm.
func BubbleSort(arr []int) []int {
    n := len(arr)
    for i := 0; i < n-1; i++ {
        swapped := false
        for j := 0; j < n-i-1; j++ {
            if arr[j] > arr[j+1] {
                arr[j], arr[j+1] = arr[j+1], arr[j]  // Swap adjacent elements if they are in the wrong order.
                swapped = true
            }
        }
        if !swapped {
            break  // If no two elements were swapped in the inner loop, then the array is sorted.
        }
    }
    return arr
}

// Main function to execute the sorting.
func main() {
    array := []int{64, 34, 25, 12, 22, 11, 90}
    fmt.Println("Original Array:", array)

    sortedArray := BubbleSort(array)
    fmt.Println("Sorted Array:", sortedArray)
}

Output:

Original Array: [64 34 25 12 22 11 90]
Sorted Array: [11 12 22 25 34 64 90]

Explanation

Looping Through the Array: Bubble sort repeatedly traverses the unsorted part of the array. With each iteration, the largest element "bubbles up" to its correct position, which is why the name "bubble sort" was coined. 

Swapping Elements: For each pair of adjacent elements, if they are in the wrong order, they get swapped. This is the core of the algorithm. 

Optimization with swapped: A small optimization is added to improve the algorithm's performance in the best-case scenario. If during a full pass through the list, no swaps are made, it means the list is already sorted, and there's no need to continue. 

Function Execution: The main function initializes an array, displays it, sorts it using the BubbleSort function, and then displays the sorted array. 

In summary, while bubble sort may not be the most efficient sorting algorithm for practical use, it's a great starting point for understanding how sorting algorithms work. The Go implementation is straightforward, highlighting the algorithm's simplicity.

Comments