Bubble Sort Program in Java - With Examples
Learn how to implement Bubble Sort in Java. Understand the algorithm with step-by-step explanation and optimized version.
Method 1: Basic Bubble Sort
Standard implementation of bubble sort.
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original array:");
printArray(arr);
// Bubble Sort
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]) {
// Swap
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("Sorted array:");
printArray(arr);
}
static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}Original array: 64 34 25 12 22 11 90 Sorted array: 11 12 22 25 34 64 90
Explanation
Bubble Sort algorithm:
1. Compare adjacent elements
2. Swap if left > right
3. Largest element "bubbles up" to end
4. Repeat for remaining elements
5. After each pass, one more element is sorted
Method 2: Optimized Bubble Sort
Early termination if array is already sorted.
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
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 = true;
}
}
// If no swapping occurred, array is sorted
if (!swapped) {
break;
}
}
System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}Sorted array: 11 12 22 25 34 64 90
Explanation
Optimization: Track if any swaps occurred.
If no swaps in a pass, array is already sorted.
Best case becomes O(n) instead of O(n²).
Frequently Asked Questions
What is Bubble Sort?
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.
When should I use Bubble Sort?
Bubble Sort is good for educational purposes and small datasets. For larger datasets, use more efficient algorithms like Quick Sort or Merge Sort.
Try This Program
Copy this code and run it in our free online Java compiler.
Open Java Compiler