Algorithms and Data Structures - Bubble Sort

Learn Bubble Sort, a comparison-based sorting algorithm with O(n²) time complexity. Covers the adjacent-element swap logic and a complete Go implementation.

Read in: ja
Algorithms and Data Structures - Bubble Sort

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

Computational Time

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))
}

References

Tags: Bubble Sort
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles