Algorithm LogbookAlgorithm Logbook

Bubble Sort

Month 1Week 4Day 1

๐Ÿ“‹ Problem Statement

Given an unsorted array of integers, sort it in ascending order using Bubble Sort. Modify the array in-place (O(1) extra space). Input: [5, 1, 4, 2, 8] โ†’ Output: [1, 2, 4, 5, 8]. Do not use built-in sort functions. Implement both iterative and recursive versions.

๐Ÿ’ก Intuition

Bubble Sort repeatedly "bubbles" the largest unsorted element to its correct position by comparing adjacent pairs and swapping if they are in the wrong order. After each full pass through the array, the largest remaining element is guaranteed to be in its final position. This means each subsequent pass can skip the last element(s). The name "bubble" comes from how larger elements float to the end.

๐Ÿ”ง Approach

1. Outer loop: run from i = 0 to n-1 (n passes). 2. Inner loop: compare adjacent elements from j = 1 to n-i (each pass has one fewer element to check). 3. If arr[k] > arr[j], swap them. 4. After n passes, the array is sorted. 5. Recursive version: replace the outer loop with recursion โ€” each recursive call represents one pass, with i incrementing.

โšก Complexity Analysis

Time
O(N^2) in worst and average case โ€” N passes, each scanning up to N elements
Space
O(1) for iterative version (in-place), O(N) for recursive version (call stack)

โš ๏ธ Common Mistakes

- Forgetting to reduce the inner loop range with each pass (the last i elements are already sorted) - Not using a "swapped" flag for early termination โ€” if no swaps occur in a pass, the array is already sorted - Confusing the indices in the recursive version, leading to incorrect or infinite recursion - Using Bubble Sort for large arrays in production โ€” it is O(N^2) and impractical beyond ~10,000 elements

๐ŸŽฏ Final Thoughts

Bubble Sort is the simplest sorting algorithm to understand and implement but one of the least efficient. Its main value is educational: it introduces the concept of sorting through repeated comparisons and swaps. In practice, use algorithms like Merge Sort (O(N log N)) or Python's built-in Timsort. However, understanding Bubble Sort is essential before tackling more efficient algorithms.