Java Program to Implement Bubble Sort

Java Program to Implement Bubble Sort

Sorting is one of the most fundamental concepts in programming. It allows us to arrange data in a specific order, which can make searching, analyzing, and managing information much easier. One of the simplest and most beginner-friendly sorting techniques is Bubble Sort. Bubble Sort repeatedly compares adjacent elements in an array and swaps them if they are out of order. While it is not the most efficient algorithm for very large datasets, it is a great starting point for beginners learning about arrays, loops, and basic algorithmic thinking.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

In real-world scenarios, sorting is used everywhere, from arranging student grades to organizing products in an online store. Learning Bubble Sort in Java not only helps you understand how sorting works but also strengthens your foundation in programming concepts like nested loops, conditionals, and recursion.

Program 1: Bubble Sort Using Simple Loops

This program demonstrates the classic approach to Bubble Sort using nested loops. It sorts an array of integers in ascending order.

public class BubbleSort1 {

    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 = {64, 34, 25, 12, 22, 11, 90};

        System.out.println("Original Array:");

        for (int num : numbers) System.out.print(num + " ");
        System.out.println();

        bubbleSort(numbers);

        System.out.println("Sorted Array:");

        for (int num : numbers) System.out.print(num + " ");

    }

}

This version uses two nested loops: the outer loop tracks the passes, while the inner loop compares adjacent elements and swaps them if necessary. With each pass, the largest unsorted element “bubbles” to its correct position. This approach is simple, making it ideal for beginners to grasp the concept of sorting step by step.

Program 2: Optimized Bubble Sort

Sometimes, the array may already be sorted before completing all passes. This optimized version adds a flag to detect whether any swaps occurred. If no swaps happen during a pass, the array is sorted, and the algorithm can exit early.

public class BubbleSort2 {

    public static void optimizedBubbleSort(int[] arr) {

        int n = arr.length;

        for (int i = 0; i < n - 1; i++) {

            boolean 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;

        }

    }

    public static void main(String[] args) {

        int[] numbers = {5, 1, 4, 2, 8};

        System.out.println("Original Array:");

        for (int num : numbers) System.out.print(num + " ");
        System.out.println();

        optimizedBubbleSort(numbers);

        System.out.println("Sorted Array:");

        for (int num : numbers) System.out.print(num + " ");

    }

}

This small modification can save unnecessary iterations, making the algorithm slightly more efficient. Beginners can understand the value of optimization while keeping the overall logic unchanged.

Program 3: Bubble Sort in Descending Order

If we need the largest elements first, we can easily adjust Bubble Sort to sort in descending order.

public class BubbleSort3 {

    public static void bubbleSortDescending(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 = {10, 3, 15, 7, 8};

        System.out.println("Original Array:");

        for (int num : numbers) System.out.print(num + " ");
        System.out.println();

        bubbleSortDescending(numbers);

        System.out.println("Sorted Array (Descending):");

        for (int num : numbers) System.out.print(num + " ");

    }

}

Changing the comparison from > to < allows sorting in reverse order. This helps beginners understand how small changes can modify algorithm behavior.

Program 4: Recursive Bubble Sort

Bubble Sort can also be implemented recursively. This version introduces recursion, which is a common programming concept that beginners need to understand.

public class BubbleSort4 {

    public static void recursiveBubbleSort(int[] arr, int n) {

        if (n == 1) return;

        for (int i = 0; i < n - 1; i++) {

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

        }

        recursiveBubbleSort(arr, n - 1);

    }

    public static void main(String[] args) {

        int[] numbers = {64, 34, 25, 12, 22};

        System.out.println("Original Array:");

        for (int num : numbers) System.out.print(num + " ");
        System.out.println();

        recursiveBubbleSort(numbers, numbers.length);

        System.out.println("Sorted Array:");

        for (int num : numbers) System.out.print(num + " ");

    }

}

Here, the recursive function performs one pass and then calls itself with a smaller portion of the array. Beginners can observe how recursion replaces loops while achieving the same effect.

Program 5: Bubble Sort Using Comparator

Sometimes, we may want to define our own sorting rules, such as sorting by absolute values, descending order, or any other custom logic. We can make our Bubble Sort flexible by allowing a comparator to be passed in.

import java.util.Comparator;

public class BubbleSort5 {

    public static void bubbleSortWithComparator(int[] arr, Comparator<Integer> comparator) {

        int n = arr.length;

        for (int i = 0; i < n - 1; i++) {

            for (int j = 0; j < n - i - 1; j++) {

                if (comparator.compare(arr[j], arr[j + 1]) > 0) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }

            }

        }

    }

    public static void main(String[] args) {

        int[] numbers = {-3, 1, -7, 4, 2};

        System.out.println("Original Array:");

        for (int num : numbers) System.out.print(num + " ");
        System.out.println();

        // Sort by absolute values
        bubbleSortWithComparator(numbers, (a, b) -> Integer.compare(Math.abs(a), Math.abs(b)));

        System.out.println("Sorted by Absolute Values:");

        for (int num : numbers) System.out.print(num + " ");
        System.out.println();

        // Sort in descending order
        bubbleSortWithComparator(numbers, (a, b) -> Integer.compare(b, a));

        System.out.println("Sorted in Descending Order:");

        for (int num : numbers) System.out.print(num + " ");

    }

}

By using a Comparator, we can easily define how the elements should be compared. This makes Bubble Sort much more flexible, allowing it to adapt to different sorting needs.

Frequently Asked Questions (FAQ)

Here are some common questions beginners often have about Bubble Sort in Java.

Q1: What is Bubble Sort?
Bubble Sort is a simple sorting algorithm that repeatedly compares adjacent elements and swaps them until the array is sorted.

Q2: Is Bubble Sort efficient for large arrays?
Bubble Sort is not very efficient for large datasets because its time complexity is O(n²). Algorithms like Merge Sort or Quick Sort are better for large arrays.

Q3: Can Bubble Sort be used for objects in Java?
Yes, Bubble Sort can be adapted to sort objects if you provide a way to compare their properties, similar to using a comparator.

Q4: What is the advantage of Bubble Sort?
The main advantage is its simplicity and ease of implementation, which makes it ideal for beginners.

Q5: How can Bubble Sort be optimized?
Adding a flag to detect swaps allows the algorithm to exit early if the array is already sorted, improving efficiency.

Conclusion

Bubble Sort in Java is a great starting point for beginners to understand sorting and fundamental programming concepts. By exploring different variations — including simple loops, optimized versions, descending order, recursion, and custom comparisons — learners can see how small adjustments can change the algorithm’s behavior. Practicing Bubble Sort helps build confidence in handling arrays, loops, and conditional logic, paving the way to more advanced algorithms like Merge Sort, Quick Sort, and Heap Sort. Sorting is a key skill for every programmer, and mastering Bubble Sort is the first step toward stronger coding abilities.

Scroll to Top