Easy Array Problems Java

Bubble Sort in Java: Program and Logic

Sort an integer array in ascending order using bubble sort.

  • TimeO(n^2) worst, O(n) best
  • SpaceO(1)
  • Hints3
  • Read3 min
Quick answer

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).

Bubble sortAdjacent swapsEarly exit
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.

Input

An integer array arr of length n.

Output

The same array in ascending order.

Examples

Example 1
Input[5, 1, 4, 2, 8]
Output[1, 2, 4, 5, 8]

Two passes put the values in order. A third pass makes no swap, so the sort stops.

Example 2
Input[3, -2, 3, 0]
Output[-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
2

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?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Compare arr[j] with arr[j + 1], not with arr[i].
2 Hint 2
After pass i (counted from 0), the last i + 1 elements are fixed, so the inner loop can be shorter.
3 Hint 3
A boolean flag set to true on every swap lets you stop early.
4

Approach

Reveal the step-by-step approach
  1. Run up to n - 1 passes.
  2. In each pass, compare neighbours from the left up to the sorted part.
  3. Swap if the left one is larger.
  4. 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.

5

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.

6

Solution

Reveal the full Java solution
Solution.java
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 - i skips the sorted part at the end.
  • swapped gives 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.

TimeO(n^2) worst, O(n) best
SpaceO(1)
7

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

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us