Master the fundamentals of sorting algorithms through hands-on implementation of Bubble Sort.
Bubble Sort is one of the simplest sorting algorithms that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. While not the most efficient algorithm, it serves as an excellent introduction to sorting concepts and algorithm analysis.
Implement the outer and inner loops for array traversal
Add a flag to detect if array is already sorted
Let's visualize how bubble sort works with the array [5, 3, 8, 4, 2]:
Pass | Array State | Comparisons & Swaps |
---|---|---|
Initial | [5, 3, 8, 4, 2] | - |
Pass 1 | [3, 5, 4, 2, 8] |
5 > 3? Yes, swap [3, 5, 8, 4, 2] 5 > 8? No, keep [3, 5, 8, 4, 2] 8 > 4? Yes, swap [3, 5, 4, 8, 2] 8 > 2? Yes, swap [3, 5, 4, 2, 8] |
Pass 2 | [3, 4, 2, 5, 8] |
3 > 5? No, keep [3, 5, 4, 2, 8] 5 > 4? Yes, swap [3, 4, 5, 2, 8] 5 > 2? Yes, swap [3, 4, 2, 5, 8] |
Pass 3 | [3, 2, 4, 5, 8] |
3 > 5? No, keep [3, 4, 2, 5, 8] 4 > 2? Yes, swap [3, 2, 4, 5, 8] |
Pass 4 | [2, 3, 4, 5, 8] | 3 > 2? Yes, swap [2, 3, 4, 5, 8] |
Final | [2, 3, 4, 5, 8] | Sorted! |
Notice how after each pass, the largest unsorted element "bubbles up" to its correct position (highlighted in green).
This variation traverses the array in both directions, pushing both the largest and smallest values to their correct positions in a single pass.
A recursive implementation of bubble sort:
Implement the basic bubble sort algorithm to sort an array in ascending order.
public void bubbleSort(int[] arr) {
// Your implementation here
}
Implement an optimized version of bubble sort that stops when the array is sorted.
public void optimizedBubbleSort(int[] arr) {
// Your implementation here
// Add optimization to break when no swaps needed
}
Modify the bubble sort algorithm to sort in descending order.
public void bubbleSortDescending(int[] arr) {
// Your implementation here
// Sort array in descending order
}
Implement the cocktail shaker sort (bidirectional bubble sort) algorithm.
public void cocktailShakerSort(int[] arr) {
// Your implementation here
// Sort array using cocktail shaker approach
}
Hint: Traverse the array from left to right, then right to left, in each iteration.
Modify the bubble sort algorithm to count and return the number of swaps performed.
public int bubbleSortAndCountSwaps(int[] arr) {
// Your implementation here
// Return the number of swaps performed
}
Hint: This is useful to measure how "unsorted" an array is.