GoLang Program to Implement Bubble Sort

GoLang Program to Implement Bubble Sort

If you are new to programming, learning how to sort data is one of the first important steps. Sorting allows you to arrange data in a specific order, which can make it easier to search, organize, or display information efficiently. Bubble Sort is one of the simplest sorting algorithms, making it perfect for beginners who want to understand the logic behind sorting.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Bubble Sort works by repeatedly stepping through a list, comparing adjacent items, and swapping them if they are in the wrong order. This process continues until the entire list is sorted. While it is not the most efficient sorting algorithm for large datasets, it is an excellent way to understand basic algorithmic thinking, loops, and comparisons. Bubble Sort is often used in teaching programming and can be applied in small-scale programs where simplicity is more important than speed.

Program 1: Bubble Sort Using Simple Loops

In this first example, we implement Bubble Sort using simple for loops. This is the most common and straightforward approach to understanding how Bubble Sort works.

package main

import "fmt"

func main() {

    numbers := []int{64, 34, 25, 12, 22, 11, 90}

    for i := 0; i < len(numbers)-1; i++ {

        for j := 0; j < len(numbers)-i-1; j++ {

            if numbers[j] > numbers[j+1] {
                numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
            }

        }

    }

    fmt.Println("Sorted array:", numbers)

}

This program uses nested loops to repeatedly compare each pair of adjacent elements and swap them if they are in the wrong order. Beginners can see the logic clearly: the largest numbers “bubble” to the end of the list with each iteration. This method is simple and a great way to understand how sorting works step by step.

Program 2: Optimized Bubble Sort with Early Exit

Sometimes, the array may become sorted before completing all passes. In this approach, we add a flag to detect whether any swaps happened during a pass. If no swaps occurred, the program exits early, making it slightly more efficient.

package main

import "fmt"

func main() {

    numbers := []int{5, 1, 4, 2, 8}

    for i := 0; i < len(numbers)-1; i++ {

        swapped := false

        for j := 0; j < len(numbers)-i-1; j++ {

            if numbers[j] > numbers[j+1] {

                numbers[j], numbers[j+1] = numbers[j+1], numbers[j]

                swapped = true

            }

        }

        if !swapped {
            break
        }

    }

    fmt.Println("Sorted array:", numbers)

}

By adding a simple swapped variable, this version avoids unnecessary passes when the array is already sorted. For beginners, this shows how small optimizations can improve performance without making the code complex. It also teaches the idea of checking conditions to make programs smarter and faster.

Program 3: Bubble Sort Using Recursion

Recursion is a concept where a function calls itself. While loops are common, using recursion to implement Bubble Sort can help beginners understand how algorithms can be expressed differently.

package main

import "fmt"

func bubbleSortRec(arr []int, n int) {

    if n == 1 {
        return
    }

    for i := 0; i < n-1; i++ {

        if arr[i] > arr[i+1] {
            arr[i], arr[i+1] = arr[i+1], arr[i]
        }

    }

    bubbleSortRec(arr, n-1)

}

func main() {

    numbers := []int{64, 34, 25, 12, 22, 11, 90}

    bubbleSortRec(numbers, len(numbers))

    fmt.Println("Sorted array:", numbers)

}

Here, the function bubbleSortRec sorts the array by performing one pass and then calling itself with a smaller portion of the array. This version teaches beginners how recursive thinking can replace loops and helps them understand breaking problems into smaller parts. It’s also a gentle introduction to recursion in GoLang.

Program 4: Bubble Sort in Descending Order

Usually, Bubble Sort is shown in ascending order, but sometimes we want to sort in descending order. This program demonstrates how small changes in the comparison can reverse the sorting order.

package main

import "fmt"

func main() {

    numbers := []int{64, 34, 25, 12, 22, 11, 90}

    for i := 0; i < len(numbers)-1; i++ {

        for j := 0; j < len(numbers)-i-1; j++ {

            if numbers[j] < numbers[j+1] {
                numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
            }

        }

    }

    fmt.Println("Sorted array in descending order:", numbers)

}

This version is almost identical to the standard Bubble Sort but flips the comparison from > to <. Beginners can quickly understand that sorting logic depends on how we compare elements. This demonstrates the flexibility of algorithms and how minor tweaks can achieve different goals.

Frequently Asked Questions (FAQ)

Sorting algorithms can be confusing at first, so here are some common questions beginners often ask.

Q1: What is Bubble Sort?
Bubble Sort is a simple sorting algorithm that repeatedly compares adjacent elements in a list and swaps them if they are in the wrong order until the list is fully sorted.

Q2: Why is Bubble Sort important for beginners?
Bubble Sort helps beginners understand basic algorithm concepts like loops, comparisons, and swaps. It’s simple to implement and visually easy to follow.

Q3: Is Bubble Sort efficient for large datasets?
No, Bubble Sort is not efficient for large datasets. Its average and worst-case time complexity is O(n²), making it slower than other algorithms like QuickSort or MergeSort.

Q4: Can Bubble Sort be used in real applications?
While not suitable for large-scale applications, Bubble Sort can still be used in small programs, educational projects, or cases where simplicity is more important than speed.

Q5: How can I improve Bubble Sort?
You can optimize it by using a flag to exit early if no swaps occur, or by learning other algorithms like Insertion Sort or MergeSort, which are more efficient.

Conclusion

Bubble Sort is a beginner-friendly algorithm that introduces essential programming concepts like loops, comparisons, and recursion. By exploring different variations, from simple loops to recursion and descending order sorting, beginners can gain confidence in understanding and implementing sorting algorithms in GoLang.

Practicing these programs helps solidify algorithmic thinking and prepares you for more advanced topics. The best way to learn is by trying these examples, tweaking them, and observing how the sorting changes. Keep experimenting, and soon sorting algorithms will feel intuitive and easy to apply in your own projects.

Scroll to Top