🧼 Ending the Day with Bubble Sort and a Practical Task

kasumbi philkasumbi phil
2 min read

🧠 What is Bubble Sort?

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. It’s called "bubble" because the largest values "bubble up" to the end of the list.


🔄 How It Works

  • Start from the beginning of the list.

  • Compare each pair of adjacent elements.

  • Swap them if they're in the wrong order.

  • Repeat the process n times until the list is sorted.


🧪 My Bubble Sort Implementation

def bubble_sort(arr):
    n = len(arr)

    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

    return arr

my_list = [7, 3, 5, 1, 8, 2, 4, 6]

print(bubble_sort(my_list))

✅ Output:

[1, 2, 3, 4, 5, 6, 7, 8]

📌 Time Complexity:

  • Best case: O(n) – when already sorted (if optimized)

  • Average and Worst case: O(n²)

  • Not the most efficient for large lists, but great for understanding how sorting works.


✅ Final Thoughts

This wrapped up my data structures deep dive for the day:

  • I started with heaps

  • Moved to heap sort and tasks

  • Tackled hash tables and duplicate detection

  • Learned graphs and traversals

  • Finished strong with bubble sort!

0
Subscribe to my newsletter

Read articles from kasumbi phil directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

kasumbi phil
kasumbi phil