-
Notifications
You must be signed in to change notification settings - Fork 0
BubbleSort
krishanthan4 edited this page Dec 16, 2025
·
1 revision
Implement bubble sort, a simple comparison-based sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they're in the wrong order.
Bubble sort is a simple sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. Larger elements "bubble up" to the end of the array.
-
Time Complexity:
- Worst case: O(n²)
- Average case: O(n²)
- Best case: O(n) with optimization
- Space Complexity: O(1) - sorts in place
- Stability: Stable (preserves relative order of equal elements)
- Adaptive: Can be optimized to detect if array is already sorted
- Compare adjacent elements
- Swap them if they're in wrong order
- After each pass, the largest unsorted element reaches its correct position
- Repeat until no swaps are needed
Pass 1: [5, 2, 8, 1] → [2, 5, 8, 1] → [2, 5, 1, 8]
Pass 2: [2, 5, 1, 8] → [2, 1, 5, 8]
Pass 3: [2, 1, 5, 8] → [1, 2, 5, 8]
Implement the following methods in BubbleSort.java:
-
sort(int[] arr)- Basic bubble sort -
sortOptimized(int[] arr)- Optimized version with early termination
- Already sorted array (best case for optimized version)
- Reverse sorted array (worst case)
- Array with duplicates
- Single element array
- Empty array
- Random unsorted array
- Use nested loops: outer loop for passes, inner loop for comparisons
- After each pass, you can reduce the inner loop range by 1
- For optimization: use a flag to detect if any swaps occurred in a pass
- If no swaps in a pass, the array is sorted
- Early termination: If no swaps in a pass, array is sorted
- Reduced range: After each pass, reduce inner loop by 1
- Cocktail sort: Alternate between forward and backward passes
- Off-by-one errors in loop bounds
- Not reducing inner loop range (inefficient)
- Swapping incorrectly
Use when:
- Educational purposes (easy to understand)
- Array is nearly sorted (with optimization)
- Small datasets
- Simplicity is more important than efficiency
Avoid when:
- Large datasets (use QuickSort, MergeSort, or HeapSort)
- Performance is critical
- How would you modify bubble sort to sort in descending order?
- Can you implement a bidirectional bubble sort (Cocktail sort)?
- How many swaps does bubble sort make in the worst case?
- Is bubble sort stable? Why or why not?
| Algorithm | Time (Avg) | Time (Worst) | Space | Stable |
|---|---|---|---|---|
| Bubble Sort | O(n²) | O(n²) | O(1) | Yes |
| Selection Sort | O(n²) | O(n²) | O(1) | No |
| Insertion Sort | O(n²) | O(n²) | O(1) | Yes |
| Quick Sort | O(n log n) | O(n²) | O(log n) | No |
| Merge Sort | O(n log n) | O(n log n) | O(n) | Yes |
- Selection Sort
- Insertion Sort
- Cocktail Shaker Sort