DEV Community

Cover image for Algorithms and Data Structures - Bubble Sort
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Algorithms and Data Structures - Bubble Sort

This article was originally published on bmf-tech.com.

Overview

Learn algorithms and data structures with reference to the Algorithm Encyclopedia.

The implementation is also available on github - bmf-san/road-to-algorithm-master.

Bubble Sort

  • A sorting method that arranges data in ascending or descending order
  • For all elements, compare adjacent elements and swap them if they are in the wrong order, repeating this operation number of elements - 1 times

Computational Time

  • Worst-case, best-case, and average-case computational time
    • O(n²)

Implementation

package main

import "fmt"

func bubbleSort(n []int) []int {
    for i := 0; i < len(n)-1; i++ {
        for j := 0; j < len(n)-i-1; j++ {
            // Compare adjacent values
            if n[j] > n[j+1] {
                // Swap adjacent values
                n[j], n[j+1] = n[j+1], n[j]
            }
        }
    }

    return n
}

func main() {
    n := []int{2, 1, 5, 7, 9}
    fmt.Println(bubbleSort(n))
}
Enter fullscreen mode Exit fullscreen mode
  • Loop through all elements, and within that, loop and compare adjacent elements

References

Top comments (0)