Bubble Sort Algorithm in Java: Array Sorting Program & Example
โก Smart Summary
Bubble Sort Algorithm in Java repeatedly compares adjacent array elements and swaps them until the sequence is ordered. This article explains the working mechanism, pseudocode, complete Java implementation, optimized variant, complexity analysis, and practical comparisons with other sorting techniques.

What is Bubble Sort?
Bubble Sort is a simple comparison-based sorting algorithm that compares the first element of the array to the next one. If the current element of the array is numerically greater than the next one, the elements are swapped. Likewise, the algorithm will traverse the entire element of the array.
The algorithm takes its name from the way the largest value in the unsorted region steadily rises to its final position, much like a bubble rising to the surface of water. After the first complete pass, the largest element occupies the last index. After the second pass, the second largest element is locked in place, and the process repeats until the array is fully ordered.
In this article, we will create a Java program to implement Bubble Sort. Check the output of the code that will help you understand the program logic, and then review the optimized version and the complexity analysis that follow.
How Does the Bubble Sort Algorithm Work?
Bubble Sort works through repeated passes over the array. Each pass walks from the first index to the end of the currently unsorted region, comparing neighbouring values and swapping them whenever they appear in the wrong order. Because the largest remaining value always travels to the far right of the unsorted region, the region shrinks by exactly one position after every pass.
The complete process can be broken down into four repeatable steps:
- Compare: Examine the element at index j-1 against the element at index j.
- Swap: If the left element is greater than the right element, exchange the two values using a temporary variable.
- Advance: Move one position to the right and repeat until the end of the unsorted region is reached.
- Repeat: Start a new pass over a region that is one element shorter, and stop after n-1 passes or when a pass performs no swaps.
The table below traces the sample array {860, 8, 200, 9} used in the program later on this page. It shows exactly which value settles into its final position at the end of every pass.
| Pass | Array at Start of Pass | Comparisons Performed | Array at End of Pass | Element Locked |
|---|---|---|---|---|
| 1 | 860, 8, 200, 9 | 3 | 8, 200, 9, 860 | 860 |
| 2 | 8, 200, 9, 860 | 2 | 8, 9, 200, 860 | 200 |
| 3 | 8, 9, 200, 860 | 1 | 8, 9, 200, 860 | 9 |
| 4 | 8, 9, 200, 860 | 0 | 8, 9, 200, 860 | 8 |
Notice that the third pass performs a comparison but no swap. An optimized implementation detects that condition and stops immediately, which is the single most valuable improvement you can apply to this algorithm.
Bubble Sort Algorithm Pseudocode
Before writing Java syntax, it helps to express the logic in language-neutral pseudocode. The version below includes the early exit flag, so it covers both the classic and the optimized behaviour.
procedure bubbleSort(array A, integer n) for i from 0 to n - 2 do swapped := false for j from 1 to n - i - 1 do // compare the adjacent pair if A[j - 1] > A[j] then swap A[j - 1] and A[j] swapped := true end if end for // no swap in a full pass means the array is sorted if swapped = false then break end if end for end procedure
The outer loop controls the number of passes, and the inner loop controls the comparisons inside a single pass. The upper bound of the inner loop is n – i – 1 because the last i positions already hold their final values.
Java Program to Implement Bubble Sort
The following program sorts an integer array in ascending order. Extra print statements have been kept inside the loops on purpose, because reading the pass-by-pass trace is the quickest way for a beginner to understand how the swaps accumulate.
package com.guru99; public class BubbleSort { public static void main(String[] args) { int arr[] = {860, 8, 200, 9}; System.out.println("---Array BEFORE Bubble Sort---"); printArray(arr); bubbleSort(arr); //sorting array elements using bubble sort System.out.println("---Array AFTER Bubble Sort---"); printArray(arr); } static void bubbleSort(int[] array) { int n = array.length; int temp = 0; for(int i = 0; i < n; i++) // Looping through the array length { System.out.println("Sort Pass Number " + (i + 1)); for(int j = 1; j < (n - i); j++) { System.out.println("Comparing " + array[j - 1] + " and " + array[j]); if(array[j - 1] > array[j]) { //swap elements temp = array[j - 1]; array[j - 1] = array[j]; array[j] = temp; System.out.println(array[j] + " is greater than " + array[j - 1]); System.out.println("Swapping Elements: New Array After Swap"); printArray(array); } } } } static void printArray(int[] array){ for(int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); } }
Output:
---Array BEFORE Bubble Sort--- 860 8 200 9 Sort Pass Number 1 Comparing 860 and 8 860 is greater than 8 Swapping Elements: New Array After Swap 8 860 200 9 Comparing 860 and 200 860 is greater than 200 Swapping Elements: New Array After Swap 8 200 860 9 Comparing 860 and 9 860 is greater than 9 Swapping Elements: New Array After Swap 8 200 9 860 Sort Pass Number 2 Comparing 8 and 200 Comparing 200 and 9 200 is greater than 9 Swapping Elements: New Array After Swap 8 9 200 860 Sort Pass Number 3 Comparing 8 and 9 Sort Pass Number 4 ---Array AFTER Bubble Sort--- 8 9 200 860
Code explanation: The bubbleSort method receives the array by reference, so the caller sees the sorted result without any return value. The variable temp holds one value during the three-line swap, which is why the algorithm needs only O(1) extra memory. The expression n – i in the inner loop condition guarantees that already-sorted positions at the tail are never revisited.
Optimized Bubble Sort Program in Java
The program above always performs n-1 passes, even when the array becomes sorted early. Adding a single boolean flag fixes that inefficiency. If a complete pass finishes without a single swap, the array is guaranteed to be sorted and the outer loop can stop immediately.
package com.guru99; public class OptimizedBubbleSort { public static void main(String[] args) { int arr[] = {5, 12, 33, 47, 58}; bubbleSort(arr); System.out.println(java.util.Arrays.toString(arr)); } static void bubbleSort(int[] array) { int n = array.length; int passes = 0; for (int i = 0; i < n - 1; i++) { boolean swapped = false; for (int j = 1; j < n - i; j++) { if (array[j - 1] > array[j]) { int temp = array[j - 1]; array[j - 1] = array[j]; array[j] = temp; swapped = true; } } passes++; // Early exit: the array is already sorted if (!swapped) { break; } } System.out.println("Passes executed: " + passes); } }
Output:
Passes executed: 1 [5, 12, 33, 47, 58]
The input array was already sorted, so the optimized version finished after a single pass instead of four. On nearly sorted data this change turns a quadratic workload into an almost linear one, which is the main reason Bubble Sort still appears in real code from time to time.
Time Complexity and Space Complexity of Bubble Sort
Complexity describes how the running time grows as the input size grows. For Bubble Sort the count of comparisons in the unoptimized version is fixed at n(n-1)/2, which places it firmly in the quadratic class.
| Scenario | Input Condition | Time Complexity | Space Complexity |
|---|---|---|---|
| Best case | Array already sorted, optimized version | O(n) | O(1) |
| Average case | Elements in random order | O(nยฒ) | O(1) |
| Worst case | Array sorted in reverse order | O(nยฒ) | O(1) |
Because every exchange happens inside the original array and only one temporary variable is used, Bubble Sort is an in-place algorithm with O(1) auxiliary space. It is also a stable sort, meaning that two records holding the same key keep their original relative order after sorting.
Advantages and Disadvantages of Bubble Sort
Understanding both sides helps you decide when the algorithm is an acceptable choice and when it should be replaced.
Advantages
- Simplicity: The logic fits in roughly ten lines, which makes it easy to write correctly under interview conditions.
- In-place operation: No auxiliary array is allocated, so memory usage does not grow with input size.
- Stability: Equal keys retain their original order, which matters when sorting records by a secondary field.
- Early exit detection: The swapped flag identifies an already sorted array in a single pass.
Disadvantages
- Quadratic growth: Sorting 10,000 elements requires nearly 50 million comparisons in the worst case.
- Excessive writes: The algorithm performs far more swaps than Selection Sort, which is costly on memory with slow write operations.
- Poor scalability: Production workloads almost always favour Quicksort, Merge Sort, or the built-in Arrays.sort method.
๐ก Tip: In production Java code, prefer Arrays.sort() for primitives and Collections.sort() for lists. Both use highly tuned algorithms, Dual-Pivot Quicksort and TimSort respectively, that outperform a hand-written Bubble Sort by orders of magnitude.
Bubble Sort vs Other Sorting Algorithms
The table below compares Bubble Sort with the sorting techniques that beginners meet next, so you can see exactly where each one wins.
| Algorithm | Best Case | Average Case | Worst Case | Space | Stable |
|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(nยฒ) | O(nยฒ) | O(1) | Yes |
| Selection Sort | O(nยฒ) | O(nยฒ) | O(nยฒ) | O(1) | No |
| Insertion Sort | O(n) | O(nยฒ) | O(nยฒ) | O(1) | Yes |
| Quicksort | O(n log n) | O(n log n) | O(nยฒ) | O(log n) | No |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
Bubble Sort and Insertion Sort share the same linear best case, but Insertion Sort performs fewer swaps on partially sorted data. Selection Sort always performs exactly n-1 swaps, which makes it attractive when writes are expensive, although it sacrifices stability. For any array larger than a few hundred elements, Quicksort or Heap Sort is the correct choice.
Once you are comfortable with array traversal patterns used here, the same loop structure appears in many classic exercises such as the Fibonacci series in Java and the Java palindrome program. Reviewing Java arrays and the wider Java tutorial will strengthen the fundamentals this algorithm depends on.
