Algorithm LogbookAlgorithm Logbook

Bubble Sort

Sorting

๐Ÿ“‹ Problem Statement

Given an unsorted array of integers, sort it in ascending order using Bubble Sort. Modify the array in-place (O(1)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. After each pass, the largest remaining element is in its final position. Subsequent passes can skip the already-sorted suffix, so the comparison count reduces each round.

๐Ÿ”ง Approach

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

โšก Complexity Analysis

Time

O(N2)O(N^2) in worst and average case โ€” NN passes, each scanning up to NN elements

Space

O(1)O(1) for iterative version (in-place); O(N)O(N) for recursive version (call stack)

โš ๏ธ Common Mistakes

  • Forgetting to reduce the inner loop range each pass (the last ii elements are already sorted)
  • Not using a "swapped" flag for early termination โ€” if no swaps occur in a pass, the array is already sorted in O(N)O(N)
  • Using Bubble Sort for large arrays in production โ€” O(N2)O(N^2) is impractical beyond ~10,000 elements

๐ŸŽฏ Final Thoughts

Bubble Sort is the simplest sorting algorithm to understand but one of the least efficient. Its value is educational: it introduces sorting through repeated comparisons and swaps. In practice, use Merge Sort (O(NlogโกN)O(N \log N)) or Python's built-in Timsort.