Bubble Sort: Solution and Explanation

Easy
Array
Sorting

Given an array of integers, sort it in ascending order using bubble sort, which repeatedly compares neighboring elements and swaps any pair that is out of order. The array is sorted in place and returned.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Imagine you are only allowed to look at two neighboring elements at a time. If the left one is bigger than the right one, they are in the wrong order, so you swap them. If you sweep from the start of the array to the end doing this, something useful happens: the largest value gets picked up by every comparison it takes part in and carried all the way to the last position, the same way a bubble rises to the surface. After one full sweep, the maximum is guaranteed to be in its final place.

That observation tells you how to finish the job. A second sweep pushes the second largest value into the second to last slot, a third sweep handles the third largest, and so on. After n - 1 sweeps, every element is where it belongs. Because the tail of the array is already sorted after each pass, there is no reason to compare inside it again, which is why the inner loop shrinks by one each time and runs only up to n - 1 - i.

The last idea is an early exit. If a whole sweep finishes without a single swap, every neighboring pair is already in order, and an array where every neighboring pair is in order is sorted. The reference code tracks this with a swapped flag and breaks out of the outer loop as soon as a pass makes no changes. That turns an already sorted input from a quadratic job into a single linear scan, which is the main practical advantage bubble sort has over selection sort.

Approach: Optimized bubble sort with early exit

  1. Store the array length in n.
  2. Run the outer loop for i from 0 to n - 2. Each iteration is one pass that settles the next largest element at the end.
  3. At the start of each pass, set swapped = False.
  4. Run the inner loop for j from 0 to n - 2 - i, comparing arr[j] with arr[j + 1].
  5. When arr[j] > arr[j + 1], swap the two values and set swapped = True.
  6. After the inner loop, if swapped is still false, the array is sorted, so break out early.
  7. Return arr, which has been sorted in place.

Step-by-step example

arr = [5, 1, 4, 2, 8]
  1. Pass i = 0: 5 > 1 so swap to [1, 5, 4, 2, 8]; 5 > 4 so swap to [1, 4, 5, 2, 8]; 5 > 2 so swap to [1, 4, 2, 5, 8]; 5 < 8, no swap. The 8 is now fixed at the end.
  2. Pass i = 1 compares only up to index 2: 1 < 4, no swap; 4 > 2 so swap to [1, 2, 4, 5, 8]; 4 < 5, no swap. swapped is true, so we continue.
  3. Pass i = 2 compares indices 0 to 1: 1 < 2 and 2 < 4, so no swaps happen and swapped stays false.
  4. The early exit triggers and the function returns [1, 2, 4, 5, 8] without running the final pass.

Code: Python, Java, C++

1class Solution:
2    def bubbleSort(self, arr: List[int]) -> List[int]:
3        n = len(arr)
4        for i in range(n - 1):
5            swapped = False
6            for j in range(n - 1 - i):
7                if arr[j] > arr[j + 1]:
8                    arr[j], arr[j + 1] = arr[j + 1], arr[j]
9                    swapped = True
10            if not swapped:
11                break
12        return arr

Time and space complexity

Time

O(n²)

In the worst case (a reverse sorted array) every pass makes swaps, so the inner loop runs (n - 1), then (n - 2), and so on down to 1 times, which is n(n - 1)/2 comparisons. In the best case, an already sorted array, the first pass makes no swaps and the early exit gives O(n).

Space

O(1)

The sort happens in place. Apart from the loop counters and the swapped flag, no extra memory is used regardless of input size.

Other approaches

Insertion sort (time O(n²), space O(1))

Also quadratic and in place, but it shifts each new element left into an already sorted prefix instead of swapping neighbors across the whole array. It usually does fewer writes than bubble sort and is the better choice for small or nearly sorted arrays.

Merge sort (time O(n log n), space O(n))

Splits the array in half, sorts each half recursively and merges them. It guarantees O(n log n) on every input and is stable, at the cost of an auxiliary buffer. Prefer it whenever the input can be large.

Common mistakes

  • Letting the inner loop run to n - 1 instead of n - 1 - i. It still sorts correctly, but it wastes comparisons on the tail that is already sorted, and an upper bound of n instead of n - 1 reads past the end with arr[j + 1].
  • Resetting the swapped flag outside the outer loop. It must be set to false at the start of every pass, otherwise one swap in an early pass disables the early exit forever.
  • Using >= instead of > in the comparison. Swapping equal elements makes the algorithm unstable and does pointless work.
  • Claiming bubble sort is always O(n²). Without the swapped check that is true, but with it the best case on sorted input is O(n).

Frequently asked questions

What is the time complexity of bubble sort?

The worst and average cases are O(n²) because the nested loops perform about n²/2 comparisons. With the early exit flag used here, the best case on an already sorted array is O(n), since one pass with no swaps ends the sort.

Is bubble sort stable?

Yes. It only swaps neighbors when the left value is strictly greater than the right one, so two equal values never pass each other and keep their original relative order.

Why is it called bubble sort?

On every pass the largest remaining value is carried toward the end of the array one swap at a time, much like a bubble rising through water. Smaller values drift toward the front more slowly.

Is bubble sort ever used in practice?

Rarely. It is mainly a teaching tool because it is easy to reason about. For real workloads, insertion sort beats it on small inputs and O(n log n) algorithms like merge sort or quicksort beat it everywhere else.