The basic bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process continues until the array is sorted.
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] data = {5, 8, 6, 3, 9, 2, 1, 7};
basicSort(data);
System.out.println(Arrays.toString(data));
}
public static void basicSort(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;
}
}
}
}
}
An optimized version introduces a flag to detect whether any swaps occurred during a pass. If no swaps happen, the array is already sorted, and the algorithm terminates early.
import java.util.Arrays;
public class OptimizedBubbleSort {
public static void main(String[] args) {
int[] data = {5, 8, 6, 3, 9, 2, 1, 7};
earlyExitSort(data);
System.out.println(Arrays.toString(data));
}
public static void earlyExitSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
boolean swapped = true;
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;
swapped = false;
}
}
if (swapped) break;
}
}
}
A further refinement tracks the last position where a swap occurred. Elements beyond this boundary are already sorted, so subsequent passes only need to process up to this point.
import java.util.Arrays;
public class AdvancedBubbleSort {
public static void main(String[] args) {
int[] data = {5, 8, 6, 3, 9, 2, 1, 7};
boundarySort(data);
System.out.println(Arrays.toString(data));
}
public static void boundarySort(int[] arr) {
int n = arr.length;
while (n > 1) {
int newBoundary = 0;
for (int i = 1; i < n; i++) {
if (arr[i - 1] > arr[i]) {
int temp = arr[i - 1];
arr[i - 1] = arr[i];
arr[i] = temp;
newBoundary = i;
}
}
n = newBoundary;
}
}
}