0
0
JavaProgramBeginner · 2 min read

Java Program for Bubble Sort with Example and Explanation

A Java program for bubble sort repeatedly compares adjacent elements and swaps them if they are in the wrong order using nested for loops; for example, 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; } } } sorts the array in ascending order.
📋

Examples

Input[5, 3, 8, 4, 2]
Output[2, 3, 4, 5, 8]
Input[1, 2, 3, 4, 5]
Output[1, 2, 3, 4, 5]
Input[9]
Output[9]
🧠

How to Think About It

To sort an array using bubble sort, think of repeatedly passing through the list and comparing each pair of neighbors. If the left one is bigger than the right one, swap them. This way, the largest unsorted number 'bubbles' to the end each pass. Repeat this until no swaps are needed or the list is fully sorted.
📐

Algorithm

1
Get the array to sort and find its length.
2
Repeat from the first element to the last unsorted element:
3
Compare each pair of adjacent elements.
4
If the left element is greater than the right, swap them.
5
After each full pass, the largest element moves to its correct position at the end.
6
Repeat passes until the whole array is sorted.
💻

Code

java
public class BubbleSort {
    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;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] numbers = {5, 3, 8, 4, 2};
        bubbleSort(numbers);
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}
Output
2 3 4 5 8
🔍

Dry Run

Let's trace the array [5, 3, 8, 4, 2] through the bubble sort code.

1

Initial array

[5, 3, 8, 4, 2]

2

First pass comparisons and swaps

Compare 5 and 3, swap -> [3, 5, 8, 4, 2]; compare 5 and 8, no swap; compare 8 and 4, swap -> [3, 5, 4, 8, 2]; compare 8 and 2, swap -> [3, 5, 4, 2, 8]

3

Second pass

Compare 3 and 5, no swap; compare 5 and 4, swap -> [3, 4, 5, 2, 8]; compare 5 and 2, swap -> [3, 4, 2, 5, 8]

4

Third pass

Compare 3 and 4, no swap; compare 4 and 2, swap -> [3, 2, 4, 5, 8]

5

Fourth pass

Compare 3 and 2, swap -> [2, 3, 4, 5, 8]

6

Sorted array

[2, 3, 4, 5, 8]

PassArray State After Pass
1[3, 5, 4, 2, 8]
2[3, 4, 2, 5, 8]
3[3, 2, 4, 5, 8]
4[2, 3, 4, 5, 8]
💡

Why This Works

Step 1: Compare adjacent elements

The code uses if (arr[j] > arr[j + 1]) to check if two neighbors are out of order.

Step 2: Swap if needed

If the left element is bigger, it swaps them using a temporary variable to hold one value.

Step 3: Repeat passes

Each pass moves the largest unsorted element to the end, shrinking the unsorted part.

🔄

Alternative Approaches

Optimized Bubble Sort with Early Stop
java
public class BubbleSortOptimized {
    public static void bubbleSort(int[] arr) {
        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 (!swapped) break;
        }
    }
}
Stops early if no swaps happen in a pass, improving performance on nearly sorted arrays.
Using Java Arrays.sort()
java
import java.util.Arrays;
public class SortUsingBuiltIn {
    public static void main(String[] args) {
        int[] arr = {5, 3, 8, 4, 2};
        Arrays.sort(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
Uses Java's built-in efficient sort, much faster and recommended for real use.

Complexity: O(n^2) time, O(1) space

Time Complexity

Bubble sort uses nested loops, each running up to n times, so it takes about n squared steps in the worst and average cases.

Space Complexity

It sorts the array in place, using only a few extra variables, so space is constant O(1).

Which Approach is Fastest?

The optimized bubble sort can stop early if sorted, but built-in sorts like Arrays.sort() use faster algorithms like TimSort.

ApproachTimeSpaceBest For
Basic Bubble SortO(n^2)O(1)Learning and small arrays
Optimized Bubble SortO(n) best, O(n^2) worstO(1)Nearly sorted arrays
Java Arrays.sort()O(n log n)O(n) or O(1) depending on typeReal-world sorting
💡
Add a flag to stop early if no swaps occur in a pass to make bubble sort faster on sorted data.
⚠️
Forgetting to reduce the inner loop range each pass causes unnecessary comparisons and slows the sort.