Bubble Sort Algorithm: Principle and Java Implementation¶
Sorting is a fundamental and common task in programming. Bubble Sort is one of the simplest sorting algorithms, whose core idea is to repeatedly compare adjacent elements and swap their positions, allowing larger elements to “bubble up” to the end of the array (for ascending order) or smaller elements to “bubble up” to the beginning (for descending order).
Step-by-Step Explanation of Sorting¶
Using the array [5, 2, 9, 1, 5] as an example, let’s demonstrate the ascending sorting process:
-
First Pass (Unsorted portion:
[5, 2, 9, 1, 5])
- Compare5and2:5 > 2, swap →[2, 5, 9, 1, 5]
- Compare5and9:5 < 9, no swap
- Compare9and1:9 > 1, swap →[2, 5, 1, 9, 5]
- Compare9and5:9 > 5, swap →[2, 5, 1, 5, 9]
- Result: The largest element9has “bubbled up” to the end; the unsorted portion becomes[2, 5, 1, 5] -
Second Pass (Unsorted portion:
[2, 5, 1, 5])
- Compare2and5:2 < 5, no swap
- Compare5and1:5 > 1, swap →[2, 1, 5, 5]
- Compare5and5:5 = 5, no swap
- Result: The second largest element5has “bubbled up” to the second last position; the unsorted portion becomes[2, 1, 5] -
Third Pass (Unsorted portion:
[2, 1, 5])
- Compare2and1:2 > 1, swap →[1, 2, 5]
- Compare2and5:2 < 5, no swap
- Result: The third largest element5has “bubbled up” to the third last position; the unsorted portion becomes[1, 2] -
Fourth Pass (Unsorted portion:
[1, 2])
- Compare1and2:1 < 2, no swap
- Result: Sorting completed; the array becomes[1, 2, 5, 5, 9]
Java Code Implementation¶
public class BubbleSort {
/**
* Implementation of the Bubble Sort algorithm (ascending order)
* @param arr Array to be sorted
*/
public static void bubbleSort(int[] arr) {
// Outer loop: Controls the number of passes (at most n-1 passes)
for (int i = 0; i < arr.length - 1; i++) {
boolean swapped = false; // Optimization flag: Did any swap occur in this pass?
// Inner loop: Controls comparisons per pass (sorted elements are no longer compared)
for (int j = 0; j < arr.length - 1 - i; j++) {
// If current element > next element, swap positions
if (arr[j] > arr[j + 1]) {
int temp = arr[j]; // Temporary variable to store current element
arr[j] = arr[j + 1]; // Swap next element to current position
arr[j + 1] = temp; // Swap current element to next position
swapped = true; // Mark that a swap occurred in this pass
}
}
// If no swaps in this pass, the array is already sorted; exit early
if (!swapped) {
break;
}
}
}
public static void main(String[] args) {
// Test array
int[] arr = {5, 2, 9, 1, 5};
System.out.println("Before sorting: " + java.util.Arrays.toString(arr));
// Call bubble sort
bubbleSort(arr);
System.out.println("After sorting: " + java.util.Arrays.toString(arr));
}
}
Key Code Explanations¶
- Outer Loop: Controls the number of passes. For an array of length
n, at mostn-1passes are needed (the last element is already sorted). - Inner Loop: Compares adjacent elements. The number of comparisons decreases by
ieach pass (sinceielements are already sorted). - Swap Logic: Uses a temporary variable
tempto swap adjacent elements, ensuring stable sorting. - Optimization: The
swappedflag terminates the algorithm early if no swaps occur in a pass (ideal for nearly sorted arrays).
Time and Space Complexity¶
- Time Complexity:
- Worst case (completely reversed):
O(n²)(all passes and comparisons are performed). - Average case:
O(n²). - Best case (already sorted):
O(n)(optimized with theswappedflag to exit early). - Space Complexity:
O(1)(only temporary variables are used; in-place sorting).
Conclusion¶
Bubble Sort is simple and intuitive, making it suitable for beginners to understand core sorting concepts. However, due to its high time complexity (O(n²)), it is rarely used for large datasets. It is typically taught or applied to small-scale sorting scenarios. After mastering Bubble Sort, one can further explore more efficient algorithms like Quick Sort or Merge Sort.