Golang
Golang

 

 

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.

Go Implementation


package main

import (
    "fmt"
)

// bubbleSort function sorts an array of integers using the bubble sort algorithm.
func bubbleSort(arr []int) []int {
    n := len(arr)
    // Traverse through all elements in the array
    for i := 0; i < n-1; i++ {
        // Last i elements are already in place
        for j := 0; j < n-i-1; j++ { // Swap if the element found is greater than the next element if arr[j] > arr[j+1] {
                arr[j], arr[j+1] = arr[j+1], arr[j]
            }
        }
    }
    return arr
}

// main function is the entry point of the program
func main() {
    // Sample array to be sorted
    arr := []int{64, 34, 25, 12, 22, 11, 90}
    fmt.Println("Unsorted array:", arr)
    sortedArr := bubbleSort(arr)
    fmt.Println("Sorted array:", sortedArr)
}
    

Program Structure

  • Package Declaration: The program starts with the package declaration package main which defines the package name.
  • Import Statement: We import the fmt package to facilitate input and output operations.
  • bubbleSort Function: This function takes a slice of integers as input and sorts it using the bubble sort algorithm. It iterates through the array, comparing adjacent elements and swapping them if necessary.
  • Main Function: The entry point of the program where we define an unsorted array, call the bubbleSort function, and print both the unsorted and sorted arrays.

Documentation

The bubbleSort function sorts an array of integers in ascending order. It works by comparing each pair of adjacent elements and swapping them if they are in the wrong order. This process repeats until no swaps are needed, indicating that the array is sorted.

Complexity

  • Time Complexity: O(n2) in the average and worst case, where n is the number of items being sorted.
  • Space Complexity: O(1) as it requires only a constant amount of additional space for variables.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)