public class BubbleSortTest { public static void main(String[] args) { int[] arr = {5, 3, 8, 4, 2}; bubbleSort(arr); for (int num : arr) { System.out.print(num + " "); } } public static void bubbleSort(int[] array) { int n = array.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } } }
The bubble sort algorithm compares adjacent elements and swaps them if the left element is greater than the right. After each pass, the largest unsorted element moves to its correct position at the end. After sorting, the array becomes sorted in ascending order: 2 3 4 5 8.
Bubble sort performs n-1 passes in the worst case because after each pass, the largest unsorted element is placed at the end. After n-1 passes, all elements are sorted.
public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i <= n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
The inner loop runs with j from 0 to n - i, so when j = n - i - 1, accessing arr[j + 1] causes an index out of bounds error because arr[n] does not exist.
int[] arr = {7, 2, 9, 4}; int n = arr.length; for (int j = 0; j < n - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } for (int num : arr) { System.out.print(num + " "); }
One pass compares adjacent pairs and swaps if needed. After one pass, the largest element 9 moves to the last position. The array becomes 2 7 4 9.
Adding a boolean flag to track swaps during a pass allows the algorithm to stop early if no swaps happen, indicating the array is already sorted. This optimization improves best-case performance.
