Here’s the Bubble Sort implementation in Java along with a table showing each iteration when the input is [5, 4, 3, 2, 1].
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted.
In the example [5, 4, 3, 2, 1], after each iteration, the largest unsorted element moves to the right, and the array becomes more sorted with each pass.
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 4, 3, 2, 1}; // Input array
System.out.println("Original Array: " + Arrays.toString(arr));
bubbleSort(arr);
}
// Bubble Sort Method
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
// Print each iteration
System.out.println("Iteration " + (i+1) + ": ");
boolean swapped = false;
for (int j = 0; j < n - i - 1; j++) {
// Swap if the element is greater than the next element
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// Print array after each pass
System.out.println(Arrays.toString(arr));
// If no two elements were swapped in inner loop, then break
if (!swapped) {
break;
}
}
}
}
[1, 2, 3, 4, 5]
Let's break down the sorting process with the array [5, 4, 3, 2, 1]:
| Iteration | Step | Array State | Swap? |
|---|---|---|---|
| Initial | [5, 4, 3, 2, 1] | ||
| Iteration 1 | Step 1 | [4, 5, 3, 2, 1] | 5 and 4 swapped |
| Step 2 | [4, 3, 5, 2, 1] | 5 and 3 swapped | |
| Step 3 | [4, 3, 2, 5, 1] | 5 and 2 swapped | |
| Step 4 | [4, 3, 2, 1, 5] | 5 and 1 swapped | |
| Iteration 2 | Step 1 | [3, 4, 2, 1, 5] | 4 and 3 swapped |
| Step 2 | [3, 2, 4, 1, 5] | 4 and 2 swapped | |
| Step 3 | [3, 2, 1, 4, 5] | 4 and 1 swapped | |
| Iteration 3 | Step 1 | [2, 3, 1, 4, 5] | 3 and 2 swapped |
| Step 2 | [2, 1, 3, 4, 5] | 3 and 1 swapped | |
| Iteration 4 | Step 1 | [1, 2, 3, 4, 5] | 2 and 1 swapped |
[1, 2, 3, 4, 5]In Bubble Sort, the largest element "bubbles" to its correct position after each iteration, and the process continues until no swaps are needed in an iteration.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.