Bubble Sort in Java: Program and Logic
Sort an integer array in ascending order using bubble sort.
- Time
O(n^2) worst, O(n) best - Space
O(1) - Hints3
- Read3 min
Bubble sort in Java compares neighbouring elements and swaps them when they are in the wrong order. After each pass, the largest remaining value reaches the end. Stop when a pass makes no swap. The worst time is O(n^2), the best is O(n) with the early stop, and the extra space is O(1).
Problem statement
Write a program for bubble sort in Java. Given an int array, sort it in
ascending order in place, without Arrays.sort.
Large values move to the right one step at a time, like bubbles rising in water.
An integer array arr of length n.
The same array in ascending order.
Examples
[5, 1, 4, 2, 8][1, 2, 4, 5, 8]Two passes put the values in order. A third pass makes no swap, so the sort stops.
[3, -2, 3, 0][-2, 0, 3, 3]Negative and repeated values need no special code.
Constraints
- 0 <= n <= 5000, as the worst time is quadratic
- Duplicates and negative numbers are allowed
Think before you code
Reveal the questions to ask yourself first
- After one full pass, which element is surely in its final place?
- How far must the next pass go?
- What does it mean if a pass makes no swap?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
- Run up to
n - 1passes. - In each pass, compare neighbours from the left up to the sorted part.
- Swap if the left one is larger.
- If no swap happened, stop. The array is sorted.
A swap needs a temporary variable, or one of the ideas in swap without a third variable.
Dry run
Walk through the example step by step
Bubble sort in Java example with [5, 1, 4, 2, 8]:
Pass | after the pass | swaps
-----+-------------------+--------
1 | [1, 4, 2, 5, 8] | 3
2 | [1, 2, 4, 5, 8] | 1
3 | [1, 2, 4, 5, 8] | 0, stop
In pass 1, 5 is swapped with 1, then 4, then 2. It stays before 8.
Solution
Reveal the full Java solution
import java.util.Arrays;
public class BubbleSort {
static void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
boolean swapped = false;
for (int j = 0; j < n - 1 - i; 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[] a = {5, 1, 4, 2, 8};
sort(a);
System.out.println(Arrays.toString(a));
int[] b = {3, -2, 3, 0};
sort(b);
System.out.println(Arrays.toString(b));
}
}Output of this bubble sort in Java code:
[1, 2, 4, 5, 8]
[-2, 0, 3, 3]
n - 1 - iskips the sorted part at the end.swappedgives the O(n) best case on an array that is already sorted.- The test is
>, not>=, so equal values keep their order. The sort is stable.
Bubble sort in Java: simple program
Beginners can start with two plain loops and no flag.
public class SimpleBubble {
public static void main(String[] args) {
int[] a = {9, 3, 7, 1};
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
for (int x : a) {
System.out.print(x + " ");
}
}
}
1 3 7 9
Bubble sort in Java: descending order
Change one sign. Now the smallest value moves to the end of each pass.
import java.util.Arrays;
public class BubbleDescending {
public static void main(String[] args) {
int[] a = {5, 1, 4, 2, 8};
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] < a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
System.out.println(Arrays.toString(a));
}
}
[8, 5, 4, 2, 1]
Complexity
| Case | Input | Comparisons |
|---|---|---|
| Best | Already sorted, with the flag | n - 1, so O(n) |
| Average | Random order | O(n²) |
| Worst | Reverse order | n(n - 1) / 2, so O(n²) |
This bubble sort in Java program is for learning. Real code uses Arrays.sort.
Compare it with selection sort and
insertion sort, then study
merge sort, which is much faster on large arrays.
The Java full stack course teaches Java from the basics.
O(n^2) worst, O(n) bestO(1)Review before the interview
Common mistakes
- Letting j reach n - 1 and reading arr[j + 1], which goes out of bounds.
- Declaring swapped outside the outer loop and never resetting it.
- Comparing arr[i] with arr[j], which is not bubble sort.
- Using >=, which swaps equal values and makes the sort unstable.
Edge cases to test
- Empty array or one element: nothing to do.
- Already sorted: stops after one pass.
- All elements equal: no swap, stops after one pass.
- Reverse order: the most swaps.
Interview follow-ups
- How do you count the total swaps?
- Why is bubble sort stable?
- Why is insertion sort often preferred for small arrays?
Keep practising
Selection Sort in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemInsertion Sort in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemCheck Whether an Array Is Sorted
Hints · Dry run · SolutionSolve Related learningArrays
TutorialLearn Related learningLoops
TutorialLearn Related learningCoding Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
