Scrivio Interview library
Sorting and intervalsSorting and searchingReported 30 times · 15 min read · updated 14 November 2026

Write a bubble sort and state its time complexity.

1What it means to sort by swapping neighbours

Picture a row of children standing in a school assembly, and a teacher who wants them in order of height, shortest on the left. The teacher has one simple rule. She walks along the row from the left, looks at two neighbouring children at a time, and if the one on the left is taller, she asks them to change places. She never compares children who stand far apart. Bubble sort is exactly this teacher's walk, done on an array of numbers.

Let us be clear about the words. An array is a row of boxes holding values, and the neighbour of a box is the box just to its right. A pass is one walk along the array from left to right, comparing each value with its neighbour and swapping the two when the left one is bigger. Bubble sort simply repeats passes until the array is in order.

The whole algorithm is two loops and one swap, so the question is smaller than it looks. The real work is the second half, stating the time complexity, and we will reach that by counting, not by memorising.

We will keep one example for the whole article, [5, 1, 4, 2, 8], which must become [1, 2, 4, 5, 8]. Let us do the first pass on paper. Compare 5 and 1: the left one is bigger, so swap, giving [1, 5, 4, 2, 8]. Compare 5 and 4: swap, giving [1, 4, 5, 2, 8]. Compare 5 and 2: swap, giving [1, 4, 2, 5, 8]. Compare 5 and 8: they are in order, so leave them. Four comparisons and three swaps, and notice the 5: once it started winning, it was carried right along until it met something bigger, the way a bubble rises through water. That is where the name comes from.

PictureThe example array before and after sorting

Top row: the array we are given. Bottom row: the same five numbers in ascending order, which is what bubble sort must produce.

  1. 5142812458
    values
    5
    goal
    smallest first

    1The top row is the input [5, 1, 4, 2, 8]. The bottom row is the answer [1, 2, 4, 5, 8], made only by swapping neighbours.

What to assume

Do we sort in place, inside the given array?
We assume yes.
Ascending or descending?
Ascending.
Are the values plain ints, or objects where equal keys must keep their original order?
We write it for ints, and equal values must never pass each other, which is the property called stability.
Which time complexity is wanted?
The worst, average and best cases, because the answer depends on the input.

A careful candidate asks a few questions before writing anything. Do we sort in place, inside the given array? We assume yes. Ascending or descending? Ascending. Are the values plain ints, or objects where equal keys must keep their original order? We write it for ints, but we will make sure equal values never pass each other, which is the property called stability. Which time complexity is wanted? We give the worst, average and best cases, because the answer depends on the input.

2How to recognise what a sorting question is really testing

When a beginner reads this question, the first feeling is often relief. The algorithm is named for us, so what is there to work out? Usually the beginner writes two loops from memory, says O(n squared), and stops. The interviewer is listening for more: correct loop bounds, knowing when the work can stop, and why the cost is what it is. So let us treat each part of the question as a clue.

The first clue is the name, bubble sort. It tells us the only operation allowed is comparing and swapping two neighbours. So a value far from its place can only travel one box per swap, like a child who may only trade places with the child next to them, and that decides the cost.

The second clue is the phrase state its time complexity. Time complexity is a description of how the number of steps grows as the array grows, written with the letter O, read as order of. To state it honestly we count comparisons and swaps on our example, then on an array of any size n.

These clues place the question in the sorting and intervals family, and the pattern of thinking it rewards has a name worth learning, the invariant. An invariant is a sentence that stays true after every step of a loop. For bubble sort it is this: after k passes, the last k boxes hold their final values. The rule to carry to every sorting question is to find the sentence that stays true after each step, because it tells you why the algorithm is correct and how much work you can skip.

A second idea explains the cost. Call a pair of values an inversion when the bigger one stands to the left of the smaller one. In [5, 1, 4, 2, 8] the inversions are 5 with 1, 5 with 4, 5 with 2 and 4 with 2, four in all. One neighbour swap fixes exactly one inversion, so a neighbour-swapping sort makes exactly as many swaps as there are inversions.

Some sorts look similar. Selection sort also uses passes, but makes one long-distance swap per pass, so it cannot stop early. Insertion sort also swaps neighbours and has the same costs. Merge sort and quicksort escape the n squared cost precisely because they move values far in one step, which bubble sort is not allowed to do.

3The brute force, every pass over every pair

The most direct way to write the teacher's rule is to walk the whole row again and again. How many walks is enough? Each pass carries the largest value not yet placed to its final box, so after n - 1 passes, n - 1 values are placed, and the one value left over must be the smallest, already at the front. So the plain version runs n - 1 passes, and each pass compares every neighbouring pair from the first box to the last.

This brute force is a good first attempt, because it is correct and easy to check by hand.

Step throughThe plain version on an array that is already sorted

Dimmed cells are positions the passes so far have already proved final, yet the plain version keeps comparing them.

  1. 1021324354pass
    pass
    1 of 4
    comparisons
    4
    swaps
    0

    1The plain version is handed an array that is already sorted. Pass 1 compares all four neighbouring pairs and swaps nothing.

  2. 1021324354pass
    pass
    2 of 4
    comparisons
    8
    swaps
    0

    2Pass 2 compares the same four pairs again, including 4 and 5 at the end, which pass 1 already proved are in order.

  3. 1021324354pass
    pass
    4 of 4
    comparisons
    16
    swaps
    0
    useful work
    none after pass 1

    3Passes 3 and 4 repeat the same checks. Sixteen comparisons in all, and not one of them changed the array.

Java
static void bubbleSortPlain(int[] a) {
for (int pass = 0; pass < a.length - 1; pass++) {
for (int i = 0; i < a.length - 1; i++) { // always the whole array
if (a[i] > a[i + 1]) {
int tmp = a[i]; a[i] = a[i + 1]; a[i + 1] = tmp;
}
}
}
}

Let us count on our example. Five values means four passes, and each pass compares the four pairs (0, 1), (1, 2), (2, 3) and (3, 4). That is 4 times 4, sixteen comparisons. For an array of n values it is (n - 1) times (n - 1) comparisons, which grows like n squared. For a thousand values that is almost a million comparisons, whatever the input looks like. The extra memory is one temporary variable, so the space is O(1).

A beginner might reasonably ask why we should care about extra comparisons if the answer is correct. Because some of them can never change anything, and we can prove it in advance. There are two kinds of waste.

The first kind is the finished tail. After pass 1, the largest value is in the last box for good. Pass 2 still compares the last pair, though nothing can ever be bigger than the value sitting there. The second kind is running after the work is done. Hand the plain version an array that is already sorted, [1, 2, 3, 4, 5], and it still makes all sixteen comparisons, swapping nothing. The picture shows this second kind of waste.

4Getting to the better version, one observation at a time

Let us remove the first kind of waste using our invariant. After pass 1 the last box is final, so pass 2 only needs to compare pairs up to the second-to-last box. After pass 2 the last two boxes are final, so pass 3 can stop one box earlier still. We express this with a variable called end, the last index a pass may reach. It starts at n - 1, and after each pass we lower it by one. The inner loop then compares a[i] with a[i + 1] only while i is less than end. On our example this cuts sixteen comparisons to 4 + 3 + 2 + 1, which is ten.

Now the second kind of waste. Suppose a whole pass goes by without a single swap. That tells us every neighbouring pair is in order. So we keep a boolean variable called swapped, a yes or no flag, set it to false at the start of every pass, set it to true whenever we swap, and if it is still false when the pass ends, we break out of the outer loop.

Here is the question that worries many beginners at this point. When a pass finds every neighbour in order, how can we be sure that two values far apart are not still out of order? If every value is at most the one to its right, then the first is at most the second, which is at most the third, and so on along the row. Order between neighbours links up into order along the whole row, like a chain where every link holds the next, so no far pair can be out of order when all the near pairs are in order.

A second question is about equal values. Should we swap when a[i] equals a[i + 1]? It would hurt stability. Stability means that two equal values keep the order they had in the input. That matters when the values are keys of larger records, such as orders sorted by price. If we swap only when a[i] is strictly greater than a[i + 1], equal values never pass each other, and bubble sort is stable for free.

The mistake most beginners make is in the loop bounds. It is tempting to write i <= end, to reach the last box. But the loop reads a[i + 1], so i must stop one short, or a[i + 1] runs past the array and Java throws an ArrayIndexOutOfBoundsException.

5Watching the passes on 5, 1, 4, 2, 8

The picture plays the better version on our example, one comparison per frame. Watch the pair being compared, marked by i, and notice how a big value that starts winning is carried along. Then watch end move left after each pass while the finished cells on the right grow, which is the invariant made visible.

The panel shows the pass, the pair, whether this pass has swapped yet, and running counts that let you check the costs we work out later.

Step throughBubble sort on [5, 1, 4, 2, 8], one comparison at a time

i is the left cell of the pair being compared, end is the last index the pass may reach. Cells marked done are in their final place.

  1. 5011422384end
    pass
    1
    end
    4
    swapped
    false
    comparisons
    0
    swaps
    0

    1We start with [5, 1, 4, 2, 8]. end is 4, the last index pass 1 may reach, and nothing is known to be in its final place yet.

  2. 1051422384iend
    pass
    1
    comparing
    5 and 1
    swapped
    true
    comparisons
    1
    swaps
    1

    2Pass 1, i = 0: we compare 5 with its right neighbour 1. The left one is bigger, so we swap them. The array is now [1, 5, 4, 2, 8].

  3. 1041522384iend
    pass
    1
    comparing
    5 and 4
    swapped
    true
    comparisons
    2
    swaps
    2

    3Pass 1, i = 1: 5 meets 4. Again the left one is bigger, so we swap. Notice that 5 is being carried along to the right.

  4. 1041225384iend
    pass
    1
    comparing
    5 and 2
    swapped
    true
    comparisons
    3
    swaps
    3

    4Pass 1, i = 2: 5 meets 2 and is bigger, so we swap once more. Three swaps so far, all of them moving the 5.

  5. 1041225384iend
    pass
    1
    comparing
    5 and 8
    swapped
    true
    comparisons
    4
    swaps
    3

    5Pass 1, i = 3: 5 meets 8. 5 is smaller, so no swap. The pass is over, and 8, the largest value, sits in its final place.

  6. 1041225384iend
    pass
    2
    comparing
    1 and 4
    swapped
    false
    comparisons
    5
    swaps
    3

    6Pass 2 stops one place earlier, since 8 is final. At i = 0 we compare 1 and 4. They are in order, so nothing moves.

  7. 1021425384iend
    pass
    2
    comparing
    4 and 2
    swapped
    true
    comparisons
    6
    swaps
    4

    7Pass 2, i = 1: 4 meets 2. The left one is bigger, so we swap, and swapped becomes true. The array is now [1, 2, 4, 5, 8].

  8. 1021425384iend
    pass
    2
    comparing
    4 and 5
    swapped
    true
    comparisons
    7
    swaps
    4

    8Pass 2, i = 2: 4 meets 5, already in order. The pass ends and 5 is final too. A swap happened, so we must run another pass.

  9. 1021425384iend
    pass
    3
    comparing
    1 and 2
    swapped
    false
    comparisons
    8
    swaps
    4

    9Pass 3 only looks at the first three cells. At i = 0, 1 and 2 are in order, so there is no swap.

  10. 1021425384iend
    pass
    3
    comparing
    2 and 4
    swapped
    false
    comparisons
    9
    swaps
    4

    10Pass 3, i = 1: 2 and 4 are in order too. The whole pass made no swap, so swapped is still false and the loop breaks.

  11. 1021425384
    passes
    3
    comparisons
    9
    swaps
    4
    result
    [1, 2, 4, 5, 8]

    11The loop has stopped after three passes, nine comparisons and four swaps. The array is [1, 2, 4, 5, 8], fully sorted.

In frames two to four, the 5 wins three comparisons in a row and moves from index 0 to index 3. In the fifth frame it meets 8 and stops, and 8 is marked done.

Pass 2 is one comparison shorter, because end is now 3. It fixes the last inversion, 4 with 2, and the array is in fact sorted after frame seven. Why not stop there, a beginner asks? Because the program does not see the picture. It only knows that pass 2 made a swap, and a swap might have created a new out-of-order pair earlier, so one more pass must check.

So pass 3 compares 1 with 2 and 2 with 4, finds both in order, and leaves swapped as false. The loop breaks there, without running a fourth pass. Four swaps in all, exactly the number of inversions we counted.

6The complete Java program

Here is the full program. The method sorts the array in place and returns the number of passes it made, so that main can show the early exit at work. main sorts our example, an array that is already sorted, and an array in reverse order, which is the worst case, and each comment shows what that line prints.

Java
import java.util.Arrays;
public class BubbleSort {
// Returns the number of passes made, so we can see the early exit at work.
static int bubbleSort(int[] a) {
int passes = 0;
for (int end = a.length - 1; end > 0; end--) { // a[end+1..] is already final
boolean swapped = false;
passes++;
for (int i = 0; i < end; i++) {
if (a[i] > a[i + 1]) { // strict >, so equal values keep their order
int tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
swapped = true;
}
}
if (!swapped) break; // no swap: the array is sorted
}
return passes;
}
public static void main(String[] args) {
int[] a = {5, 1, 4, 2, 8};
int passes = bubbleSort(a);
System.out.println(Arrays.toString(a) + " passes=" + passes); // [1, 2, 4, 5, 8] passes=3
int[] sorted = {1, 2, 3, 4, 5};
passes = bubbleSort(sorted);
System.out.println(Arrays.toString(sorted) + " passes=" + passes); // [1, 2, 3, 4, 5] passes=1
int[] reversed = {5, 4, 3, 2, 1};
passes = bubbleSort(reversed);
System.out.println(Arrays.toString(reversed) + " passes=" + passes); // [1, 2, 3, 4, 5] passes=4
}
}

Let us read bubbleSort in the order it runs. The outer for loop sets end to a.length - 1, the last index of the array, and lowers it by one after each pass. Its condition end > 0 means at least one pair is left to compare.

At the top of each pass we set swapped to false and add one to passes. The inner loop runs i from 0 up to end - 1, so it compares the pairs (0, 1) up to (end - 1, end) and never reads past index end.

Inside, the comparison a[i] > a[i + 1] is strict, which is what keeps equal values in their original order. When it is true, the three lines with tmp swap the two values. tmp keeps the old a[i] safe while it is overwritten. Then we set swapped to true.

When the inner loop finishes, one more value has reached its final place. If swapped is still false, the break leaves the outer loop at once, because the array is sorted. Otherwise end goes down by one and the next pass starts. So main prints passes=3 for our example, passes=1 for the sorted array and passes=4 for the reversed one.

7How much it costs, and the cases at the edges

On the example, the better version made 4 + 3 + 2 = 9 comparisons and 4 swaps in three passes. Now let us generalise to n values.

The worst case is an array in reverse order, such as [5, 4, 3, 2, 1]. Every comparison causes a swap, so all n - 1 passes run. They compare n - 1, then n - 2, and so on down to 1 pairs. That sum is n(n - 1) / 2. For large n only the n squared part matters, so the worst case is O(n squared).

The average case, a randomly jumbled array, is also O(n squared). A random array has about n(n - 1) / 4 inversions, half of all pairs, and each swap fixes only one.

The best case is an array that is already sorted. Thanks to the swapped flag, one pass of n - 1 comparisons swaps nothing and the loop breaks, so the best case is O(n). Without the flag it would be O(n squared), a point interviewers like to hear. In every case the extra space is O(1), because we use only end, i, swapped, passes and tmp, however large the array is.

Comparing the ways to sort by swapping neighbours
ApproachBestAverage and worstExtra space
Plain version: every pass, every pairO(n^2)O(n^2)O(1)
Bubble sort with shrinking end and early exitO(n)O(n^2)O(1)
Insertion sort, for comparisonO(n)O(n^2)O(1)
Arrays.sort, for comparisonO(n log n)O(n log n)O(log n) to O(n)

The edge cases need no special code. For an empty array, end starts at -1, the condition end > 0 fails at once, and the method returns 0 passes. For a single value, end starts at 0 and the loop never runs either. For an array of equal values such as [3, 3, 3], the strict comparison never swaps, so one pass of checks ends the sort.

Because it is quadratic, real Java code uses Arrays.sort, which runs in O(n log n).

8Follow-up questions

What is the difference between bubble sort and selection sort?

Selection sort scans the unsorted part to find the smallest value and then makes one swap to put it at the front, so it makes at most n - 1 swaps in all. Bubble sort can make up to n(n - 1) / 2 swaps, one per inversion. Both make O(n squared) comparisons. Selection sort cannot stop early, because finding the minimum always needs a full scan, so even a sorted array costs O(n squared). And its long-distance swap can jump a value over an equal one, so it is not stable, while bubble sort is.

Can the passes be made shorter still?

Yes, by remembering where the last swap of a pass happened. Every pair to the right of that position was found in order, so the next pass can stop there instead of at end - 1. This helps on nearly sorted input, but the worst case stays O(n squared).

Is there any real situation where bubble sort is a reasonable choice?

Only for tiny arrays, or arrays that are known to be almost sorted, and even there insertion sort is usually the better pick, because it makes fewer comparisons and fewer writes for the same O(n) best case. In an interview, the honest answer is that bubble sort is a teaching tool, and that for real data we would call Arrays.sort or Collections.sort.

9Conclusion

We wrote bubble sort as repeated passes that swap out-of-order neighbours, just like a teacher walking along a row of children. The invariant that after k passes the last k boxes are final let us shorten every pass, and the swapped flag let us stop as soon as a pass changes nothing, because order between all neighbours means order along the whole row. The cost is O(n squared) in the worst and average cases, O(n) in the best case, with O(1) extra space and a stable result. The clue to remember is that any sort that only swaps neighbours fixes one inversion per swap, so on jumbled data it is quadratic.

What to say in the interviewAbout 90 seconds aloud

Open with

Let me confirm the setup first: I sort an int array in place, in ascending order. Bubble sort makes passes from left to right, comparing each value with its right neighbour and swapping them when the left one is bigger.

Then, if they want more

After the first pass the largest value has been carried to the end, and in general after k passes the last k positions are final. The plain version always makes about n squared comparisons, even on sorted input. I improve it in two ways.

Since the tail is final, each pass stops one position earlier, using an end index that goes down by one. And I keep a swapped flag: if a whole pass makes no swap, every neighbouring pair is in order, so the array is sorted and I break.

I compare with a strict greater than, so equal values never pass each other and the sort is stable. In the worst case, a reversed array, that is n times n minus one over two comparisons and as many swaps, so O(n squared).

The average is also O(n squared), because each swap fixes exactly one inversion and a random array has about n squared over four of them. With the early exit the best case, a sorted array, is one pass, O(n). Extra space is O(1).

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 30 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a bubble sort and state its time complexity.": https://scrivio-interview-library.netlify.app/data-structures/solutions/write-a-bubble-sort-and-state-its-time-complexity-590ea5/