Bubble Sort
๐ Problem Statement
Given an unsorted array of integers, sort it in ascending order using Bubble Sort. Modify the array in-place ( 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
- Outer loop: run from to ( passes total).
- Inner loop: compare adjacent elements from to (each pass has one fewer element to check).
- If
arr[k] > arr[j], swap them. - After passes, the array is sorted.
- Recursive version: replace the outer loop with recursion โ each call represents one pass, with incrementing.
โก Complexity Analysis
in worst and average case โ passes, each scanning up to elements
for iterative version (in-place); for recursive version (call stack)
โ ๏ธ Common Mistakes
- Forgetting to reduce the inner loop range each pass (the last 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
- Using Bubble Sort for large arrays in production โ 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 () or Python's built-in Timsort.