Overview
Bubble Sort is one of the simplest sorting algorithms to understand and implement. It works by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. The algorithm gets its name because smaller elements “bubble” to the top of the list.Complexity
- Time Complexity: O(n²) in all cases (best, average, and worst)
- Space Complexity: O(1) - sorts in-place
- Stable: Yes - maintains relative order of equal elements
Implementation
Here’s the actual implementation from the Sorting Algorithms Visualiser:How It Works
- Outer Loop: Iterates through the entire array
ntimes - Inner Loop: Compares adjacent pairs from the start to
n - i - 1- The
-ioptimization exists because after each pass, the largest element is guaranteed to be in its final position
- The
- Comparison: If
nums[j] > nums[j + 1], swap them - Verification: After sorting completes, the
Verify()function highlights each element to confirm the array is sorted
Step-by-Step Example
For the array[5, 3, 8, 4, 2]:
Pass 1:
- Compare 5 & 3 → Swap →
[3, 5, 8, 4, 2] - Compare 5 & 8 → No swap
- Compare 8 & 4 → Swap →
[3, 5, 4, 8, 2] - Compare 8 & 2 → Swap →
[3, 5, 4, 2, 8](8 is now in final position)
- Compare 3 & 5 → No swap
- Compare 5 & 4 → Swap →
[3, 4, 5, 2, 8] - Compare 5 & 2 → Swap →
[3, 4, 2, 5, 8](5 is now in final position)
Watch It in Action
When running the visualiser, you’ll see:- Red highlight (highlight1): Current element at position
j - Green highlight (highlight2): Adjacent element at position
j+1 - Blue highlight: Used during the verification phase
The visualization highlights show exactly which two elements are being compared at each step (lines 91-92 in the implementation).
Best Use Cases
- Educational purposes: Excellent for teaching sorting concepts
- Small datasets: Acceptable performance for very small arrays (< 10 elements)
- Nearly sorted data: Can be optimized with an early exit flag
- Simple requirements: When code simplicity is more important than performance