DEV Community

Cover image for [Golang] How to Implement Bubble Sort Algorithm
Kuldeep Singh
Kuldeep Singh

Posted on

[Golang] How to Implement Bubble Sort Algorithm

Today we are going to work on bubble sort implementation.

What is Bubble Sort?

Bubble sort is a sorting algorithm that works by repeatedly stepping through lists that need to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. This passing procedure is repeated until no swaps are required, indicating that the list is sorted. Bubble sort gets its name because smaller elements bubble toward the top of the list.

Bubble sort is also referred to as sinking sort or comparison sort.

Explanation

Bubble sort has a worst-case and average complexity of O(n2), where n is the number of items sorted. Unlike the other sorting algorithms, bubble sort detects whether the sorted list is efficiently built into the algorithm. Bubble sort performance over an already sorted list is O(n).

The position of elements in bubble sort plays an important role in determining performance. Large elements at the beginning do not pose a problem as they are easily swapped. The small elements toward the end move to the beginning slowly. As such, these elements are called rabbits and turtles.

The bubble sort algorithm can be optimized by placing larger elements in the final position. After every pass, all elements after the last swap are sorted and do not need to be checked again, thereby skipping the tracking of swapped variables.

So now we know what bubble sort is, So let's start writing code

Code:

    arr := []int{5, 3, 4, 9, 6, 8, 0, 1, 2}
    fmt.Println(arr)

    // Way 1 next index checking with current index
    // 1. x pointer is on index 0
    // 2. y pointer in on index 1
    // each time whenever y execution finishes it increment values for both
    // whenever x starts again for next index
    for x := range arr {
        var swapped bool
        y := x + 1
        for y = range arr {
            if arr[x] < arr[y] {
                arr[x], arr[y] = arr[y], arr[x]
                swapped = true
            }
        }
        if !swapped {
            break
        }
    }


Enter fullscreen mode Exit fullscreen mode

Checkout Here for more methods on bubble sort implementation:
https://kdsingh4.blogspot.com/2021/10/golang-how-to-sort-array-slice-using.html

Checkout More Algorithms Solutions: https://kdsingh4.blogspot.com/search/label/algorithm?&max-results=5/feed/

Don't Forget To Subscribe My Youtube Channel as well:
https://www.youtube.com/channel/UCXhmNqWQ50zitqIdTgS7s8Q

Top comments (0)