DEV Community

Lane Wagner for Boot.dev

Posted on • Originally published at qvault.io on

Writing Bubble Sort in Go from Scratch

#go

bubbles in water

The post Writing Bubble Sort in Go from Scratch first appeared on Qvault.

Bubble sort is named for the way elements “bubble up” to the top of the list. Bubble sort repeatedly steps through a slice and compares adjacent elements, swapping them if they are out of order. It continues to loop over the slice until the whole list is completely sorted.

Full example of the bubble sort algorithm

func bubbleSort(input []int) []int {
    swapped := true
    for swapped {
        swapped = false
        for i := 1; i < len(input); i++ {
            if input[i-1] > input[i] {
                input[i], input[i-1] = input[i-1], input[i]
                swapped = true
            }
        }
    }
    return input
}
Enter fullscreen mode Exit fullscreen mode

Using the algorithm in code

func main() {
    unsorted := []int{10, 6, 2, 1, 5, 8, 3, 4, 7, 9}
    sorted := bubbleSort(unsortedInput)

    // sorted = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
Enter fullscreen mode Exit fullscreen mode

Why use bubble sort?

Bubble sort is famous for how easy it is to write. It’s one of the slowest sorting algorithms, but can be useful for a quick script or when the amount of data to be sorted is guaranteed to be small. If you need a sorting algorithm to use in a production system, I recommend not reinventing the wheel and using the built-in sort.Sort method.

Bubble sort Big-O complexity

While bubble sort is considered fast and easy to write, its actually one of the slowest sorting algorithms out there. Because bubble sort needs to move through the entire list for each element in the list, which in code is a nested for-loop, bubble sort has a complexity of O(n^2).

Thanks for reading, now take a course!

Interested in a high-paying job in tech? Land interviews and pass them with flying colors after taking my hands-on coding courses.

Start coding now

Questions?

Follow and hit me up on Twitter @q_vault if you have any questions or comments. If I’ve made a mistake in the article be sure to let me know so I can get it corrected!

Subscribe to my newsletter for more coding articles delivered straight to your inbox.

Top comments (0)