View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Bubble Sort Program in Java: A Comprehensive Guide

Updated on 24/04/20254,855 Views

Sorting algorithms are foundational in computer science, often serving as a rite of passage for budding programmers. Among them, Bubble Sort is one of the simplest and most intuitive, making it a popular choice for educational purposes. 

Despite its simplicity, Bubble Sort opens the door to understanding algorithmic thinking, complexity analysis, and optimization techniques.

In this blog, we’ll cover everything from the theoretical underpinnings of Bubble Sort to a practical Java implementation, along with a comparative analysis against similar content found online.

Build a strong foundation in Java and beyond. Join the Software Engineering course by upGrad to accelerate your tech journey.

What Is Bubble Sort Program in Java?

Bubble Sort is a simple comparison-based sorting algorithm that organizes a list of elements by repeatedly swapping adjacent elements if they are in the wrong order. It continues to "bubble" the largest (or smallest) values to their correct position at the end (or beginning) of the list through multiple passes until the entire list is sorted.

The algorithm gets its name because smaller elements gradually "rise" to the top of the list, like bubbles in water, while larger elements "sink" to the bottom with each pass.

How Does Bubble Sort Work?

Bubble Sort works by repeatedly scanning the array, comparing each pair of adjacent elements, and swapping them if they are in the wrong order. Each full pass through the array moves the largest unsorted element to its correct position — like a bubble rising to the top (or the largest number sinking to the bottom, depending on your view).

This process is repeated for all elements until the list is completely sorted.

Step-by-Step Working Process of Bubble Sort Program in Java

Let’s say we want to sort the array: [4, 3, 1, 5, 2]

Pass 1:

We compare adjacent elements from left to right:

  • Compare 4 and 3 → swap → [3, 4, 1, 5, 2]
  • Compare 4 and 1 → swap → [3, 1, 4, 5, 2]
  • Compare 4 and 5 → no swap
  • Compare 5 and 2 → swap → [3, 1, 4, 2, 5]

Largest element (5) is now in the correct position.

Pass 2:

Now we repeat the process for the remaining elements (excluding the sorted last element):

  • Compare 3 and 1 → swap → [1, 3, 4, 2, 5]Compare 3 and 4 → no swap
  • Compare 4 and 2 → swap → [1, 3, 2, 4, 5]

Second-largest (4) is now in place.

Pass 3:

  • Compare 1 and 3 → no swap
  • Compare 3 and 2 → swap → [1, 2, 3, 4, 5]

Third-largest (3) is in place.

Pass 4:

  • Compare 1 and 2 → no swap

All sorted! The algorithm can now terminate.

Visualization of Each Round

Initial: [4, 3, 1, 5, 2]

Pass 1 → [3, 1, 4, 2, 5]

Pass 2 → [1, 3, 2, 4, 5]

Pass 3 → [1, 2, 3, 4, 5]

Pass 4 → [1, 2, 3, 4, 5] (No swaps → done)

Already know Java? Expand your skill set with data science and AI through IIIT-B’s Executive Diploma program on upGrad.

Bubble Sort Program in Java: Implementation

Here’s a simple, complete Java program for Bubble Sort:

public class BubbleSortExample {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 8, 4, 2};
        bubbleSort(numbers);
        System.out.println("Sorted array:");
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        boolean swapped;
        // Outer loop runs for each element
        for (int i = 0; i < n - 1; i++) {
            swapped = false;
            // Inner loop performs comparisons
            for (int j = 0; j < n - i - 1; j++) {
                // Swap if current element is greater than next
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }
            // No swaps means array is already sorted
            if (!swapped) break;
        }
    }
}

Output:

Sorted array:

2 3 4 5 8 

Mastering Java is a great start. Expand your expertise in Cloud and DevOps with this professional certificate course and stay ahead in the tech industry.

Is Bubble Sort Stable?

A stable sorting algorithm is one that preserves the relative order of records with equal keys. In other words, if two elements have the same value in the input, and one appears before the other, then they should remain in the same order in the output after sorting.

This property becomes crucial in scenarios where the records have multiple fields, and sorting needs to be done based on more than one criterion, often in a multi-pass or layered fashion.

For example, if a list of students is sorted first by grade and then by name, a stable sort ensures that when sorting by grade, the order of students with the same grade (previously sorted by name) remains unchanged.

Boundary Case for Bubble Sort Program in Java

The boundary case for Bubble Sort is when the array is already sorted. In this scenario, Bubble Sort arrays its best-case behavior, as no swapping is required during any pass. With an O(n) time complexity, where n is the number of items in the array, the algorithm will run through the array once to ensure that no swapping is required and end early.

Consider the following array: [1, 2, 3, 4, 5].

Applying Bubble Sort to this array results in the following comparisons and swaps:

  • Pass 1: Comparisons: 4 Swaps: 0
  • Pass 2: Comparisons: 3 Swaps: 0
  • Pass 3: Comparisons: 2 Swaps: 0
  • Pass 4: Comparisons: 1 Swaps: 0

The algorithm completes in a single pass, as no swapping is required, and the array is already sorted.

Bubble Sort vs Other Sorting Algorithms

Algorithm

Time Complexity (Avg)

Space

Stable

Bubble Sort

O(n²)

O(1)

Yes

Insertion Sort

O(n²)

O(1)

Yes

Merge Sort

O(n log n)

O(n)

Yes

Quick Sort

O(n log n)

O(log n)

No

Bubble Sort is the slowest among the popular algorithms but the simplest to implement and understand, making it invaluable for learning.

Best Practices for Bubble Sort in Java

While Bubble Sort is a simple sorting algorithm, it's often used for educational purposes rather than performance-critical applications. 

However, writing it well teaches important lessons in algorithm design, optimization, and clean coding. Here are some best practices:

1. Use an Optimized Version of Bubble Sort

The naive version of Bubble Sort always performs n-1 passes, even if the array becomes sorted early. Optimize it by adding a "swapped" flag to terminate early when no swaps are needed.

2. Use Meaningful Variable Names

Avoid generic names like i, j, temp in final implementations. For educational code, it's fine, but in real projects, descriptive names enhance readability.

3. Make the Method Reusable

Encapsulate the method in a utility class, and consider using generics if sorting objects. Keep the method static if it doesn't require instance data.

4. Support Descending Order (Optional Enhancement)

Allow users to specify the sort order by adding a parameter or comparator.

5. Avoid Using Bubble Sort for Large Datasets

Explain in comments that Bubble Sort is not ideal for large lists due to its O(n²) time complexity in average and worst cases.

Use Arrays.sort() or efficient algorithms like Merge Sort, Quick Sort, or TimSort for real-world applications.

Concluding Words

While Bubble Sort in Java won’t help you sort millions of records in real time, its simplicity is its strength. It builds your foundation in algorithm design and logic formulation. Understanding Bubble Sort prepares you for more advanced topics like divide-and-conquer sorting (Merge Sort), in-place partitioning (Quick Sort), and even sorting networks in parallel computing.

If you’re just starting with algorithms in Java, mastering Bubble Sort gives you a strong mental model to reason about loops, swaps, complexity, and data transformations — the building blocks of computer science.

FAQs

1. What is Bubble Sort in Java?

Bubble Sort is a simple sorting technique where adjacent elements are compared and swapped if they are in the wrong order. This process is repeated until the entire array is sorted. It's mainly used in educational contexts due to its simplicity.

2. How does Bubble Sort work?

Bubble Sort works by performing multiple passes through the array. On each pass, it pushes the largest unsorted element to the end by comparing and swapping adjacent values. This continues until no swaps are needed.

3. What is the time complexity of Bubble Sort?

The best case occurs when the array is already sorted, resulting in O(n) time. The average and worst-case time complexity is O(n²), which makes it inefficient for large datasets. It’s only practical for small or nearly sorted data.

4. Is Bubble Sort stable?

Yes, Bubble Sort is a stable sorting algorithm. It preserves the relative order of equal elements by only swapping elements when the left one is strictly greater. This makes it useful when sorting complex data by multiple attributes.

5. What is the space complexity of Bubble Sort?

Bubble Sort has a space complexity of O(1) because it sorts the array in-place using a constant amount of extra memory. This makes it memory-efficient even though it's time-inefficient.

6. When should I use Bubble Sort?

Use Bubble Sort for small datasets, or when the data is nearly sorted and stability is required. It’s also great for beginners to learn the fundamentals of sorting algorithms, iterations, and condition-based logic.

7. Can Bubble Sort be optimized?

Yes, you can improve Bubble Sort by adding a flag to check if any swaps were made during a pass. If no swaps occur, the algorithm can terminate early, improving performance in nearly sorted arrays.

8. How is Bubble Sort different from other algorithms?

Compared to more advanced algorithms like Quick Sort or Merge Sort, Bubble Sort is much slower but significantly easier to understand and implement. It’s ideal for grasping the basics, not for high-performance sorting.

9. Can Bubble Sort sort objects in Java?

Absolutely. Bubble Sort can be used to sort objects by comparing specific fields using the Comparable interface or a custom Comparator. This allows flexibility in sorting based on any object attribute.

10. Does Java’s Arrays.sort() use Bubble Sort?

No, Java’s Arrays.sort() is optimized and uses Dual-Pivot QuickSort for primitives and TimSort for objects. These are faster and more efficient than Bubble Sort and are used in production environments.

11. Why is Bubble Sort still taught?

Bubble Sort is still taught because it provides a clear understanding of basic algorithmic concepts like comparisons, swaps, and control flow. It’s often a stepping stone before learning more advanced and efficient sorting methods.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.