Overview
Bubble Sort is one of the simplest sorting algorithms that works by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. The pass through the list is repeated until the list is sorted.Implementation
How It Works
- Compare Adjacent Elements: Start at the beginning of the array and compare each pair of adjacent elements
- Swap if Necessary: If the elements are in the wrong order, swap them
- Repeat Until Sorted: Continue making passes through the array until no more swaps are needed
- Largest Elements “Bubble Up”: In each pass, the largest unsorted element moves to its correct position at the end
The algorithm gets its name because smaller elements gradually “bubble” to the top (beginning) of the list, while larger elements sink to the bottom (end).
Complexity Analysis
Time Complexity
- Best Case: O(n) - when array is already sorted
- Average Case: O(n²)
- Worst Case: O(n²) - when array is reverse sorted
Space Complexity
- Space: O(1) - sorts in place
- Auxiliary: O(1) - only uses a few variables
Usage Example
Characteristics
Stability
Stability
Bubble Sort is stable - it maintains the relative order of equal elements.
In-Place
In-Place
Yes, Bubble Sort is an in-place algorithm. It only requires a constant amount O(1) of additional memory space.
Adaptive
Adaptive
Bubble Sort can be made adaptive by detecting if no swaps were made in a pass, indicating the array is sorted.
Online
Online
No, Bubble Sort is not online. It needs the entire dataset before it can start sorting.
When to Use
Good for:- Educational purposes to understand sorting algorithms
- Very small datasets (n < 10)
- Nearly sorted data where only a few passes are needed
- When simplicity and ease of implementation are priorities
- Working with large datasets
- Performance is critical
- Better alternatives like Quick Sort or Merge Sort are available
Comparison with Other Sorts
| Algorithm | Best Case | Average Case | Worst Case | Space | Stable |
|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |