Frontend Labs
⋯

7. Bubble Sort

🧸 ELI5: Line up your friends by height. You compare the first two — if the shorter one is standing behind the taller one, they swap. You keep walking down the line doing this, and each pass, the tallest kid "bubbles up" to the end. Repeat until nobody needs to swap anymore.

🌍 Real life: Manually sorting playing cards by comparing two adjacent cards at a time and swapping. Simple, but slow for a big deck.

📝 Pseudocode:

function bubbleSort(list):
    for i from 0 to length(list) - 1:
        for j from 0 to length(list) - i - 2:
            if list[j] > list[j+1]:
                swap(list[j], list[j+1])

🐹 Go:

package main

import "fmt"

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

func main() {
	kids := []int{140, 120, 160, 130}
	bubbleSort(kids)
	fmt.Println(kids) // [120 130 140 160]
}

🇨 C:

#include <stdio.h>

void bubble_sort(int *heights, int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (heights[j] > heights[j + 1]) {
                int tmp = heights[j];
                heights[j] = heights[j + 1];
                heights[j + 1] = tmp;
            }
        }
    }
}

int main(void) {
    int kids[] = {140, 120, 160, 130};
    bubble_sort(kids, 4);
    for (int i = 0; i < 4; i++) printf("%d ", kids[i]); // 120 130 140 160
    printf("\n");
    return 0;
}

⏱️ Complexity: O(n²) — fine for a handful of kids, terrible for a stadium of them.


Generated from real-life-ds-algo-guide.md · 8 Oct 2026 16:36