Java Program to Sort an Array Using Bubble Sort

In this Java program, we will learn how to sort an array in ascending order using the Bubble Sort algorithm.

What is Bubble Sort?

Bubble Sort is a simple sorting algorithm that repeatedly compares two adjacent elements and swaps them if they are in the wrong order.

For example:

Input  : {50, 20, 40, 10, 30}
Output : {10, 20, 30, 40, 50}

During each pass, the largest unsorted element moves to the end of the array.

1. Traditional Java Program Using Bubble Sort

public class BubbleSort {

    public static void main(String[] args) {
        int[] arr = {50, 20, 40, 10, 30};
        System.out.println("Before Sorting:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        // Bubble Sort
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        System.out.println("\nAfter Sorting:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Output

Before Sorting:
50 20 40 10 30

After Sorting:
10 20 30 40 50

Explanation

The outer for loop controls the number of passes:

for (int i = 0; i < arr.length - 1; i++)

The inner loop compares adjacent elements:

for (int j = 0; j < arr.length - 1 - i; j++)

If the current element is greater than the next element, they are swapped:

if (arr[j] > arr[j + 1]) {
    int temp = arr[j];
    arr[j] = arr[j + 1];
    arr[j + 1] = temp;
}

For example:

50 20 40 10 30
↑  ↑
Compare 50 and 20 → Swap

20 50 40 10 30
   ↑  ↑
Compare 50 and 40 → Swap

20 40 50 10 30
      ↑  ↑
Compare 50 and 10 → Swap

20 40 10 50 30
         ↑  ↑
Compare 50 and 30 → Swap

20 40 10 30 50

After the first pass, the largest value 50 reaches the end.


2. Java 8 Program Using Lambda Expression

Java 8 provides Lambda expressions and the Stream API. For learning purposes, we can use a lambda expression to perform the swapping operation.

import java.util.Arrays;
import java.util.stream.IntStream;

public class BubbleSortJava8 {
    public static void main(String[] args) {
        int[] arr = {50, 20, 40, 10, 30};
        System.out.println("Before Sorting: "
                + Arrays.toString(arr));
        IntStream.range(0, arr.length - 1)
                .forEach(i -> IntStream.range(0, arr.length - 1 - i)
                        .forEach(j -> {
                            if (arr[j] > arr[j + 1]) {
                                int temp = arr[j];
                                arr[j] = arr[j + 1];
                                arr[j + 1] = temp;
                            }
                        }));
        System.out.println("After Sorting: "
                + Arrays.toString(arr));
    }
}

Output

Before Sorting: [50, 20, 40, 10, 30]
After Sorting: [10, 20, 30, 40, 50]

Explanation of Java 8 Program

The Java 8 version uses IntStream.range() instead of traditional for loops:

IntStream.range(0, arr.length - 1)

The forEach() method processes each pass:

.forEach(i -> ...)

The inner IntStream compares adjacent elements:

IntStream.range(0, arr.length - 1 - i)

The lambda expression:

i -> ...

and:

j -> ...

are Java 8 features.

The actual Bubble Sort logic remains the same:

if (arr[j] > arr[j + 1]) {
    int temp = arr[j];
    arr[j] = arr[j + 1];
    arr[j + 1] = temp;
}

Difference Between Traditional Java and Java 8

FeatureTraditional JavaJava 8
Sorting algorithmBubble SortBubble Sort
Loopfor loopIntStream
Lambda expressionNoYes
Stream APINoYes
Easy for beginnersVery easyModerate
Best for learning Bubble SortYesAfter understanding basics

Time Complexity

Bubble Sort has:

  • Best case: O(n) with an optimized implementation
  • Average case: O(n²)
  • Worst case: O(n²)
  • Space complexity: O(1)

The simple implementation above performs O(n²) comparisons.

Which Method Should You Use?

For beginners, the traditional for loop version is strongly recommended because it makes the Bubble Sort algorithm easy to understand.

The Java 8 version is useful for learning how Streams and Lambda expressions can be used with existing algorithms.

Conclusion

Bubble Sort is one of the easiest sorting algorithms to understand. It repeatedly compares adjacent elements and swaps them when necessary. The traditional Java approach clearly demonstrates the sorting logic, while the Java 8 version demonstrates a functional programming style.

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *