LearnWithKiriti

Bubble Sort

Easy GitHub ↗
đź’» Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here. New: mock interview with Mr. Tock. Explain your approach out loud, he pushes you to improve it, then you code it. You get a scorecard at the end.
Play
On this page
  1. Revision notes
  2. Optimal: Shrink And Stop Early

Revision notes

Bubble Sort

Video: “Bubble Sort: why and when to use it” on LearnWithKiriti (Kodee).

Sort an array from smallest to largest by swapping neighbours that are out of order. Example: [7, 2, 8, 1, 5] -> [1, 2, 5, 7, 8]

Folder Approach Time Extra space
Optimal-ShrinkAndStopEarly/ After each pass the biggest bubble rises to sortedEnd, so the next pass stops one earlier; and if a pass made no swap, the array is sorted: stop. O(n²) worst, O(n) if already sorted O(1)

Rebuild it from the name

Bubble: the biggest bubble rises to the top. Walk the array comparing currBubble with nextBubble; if the left one is bigger, swap them. The biggest number keeps getting carried along, so after one pass it has risen to the end, sortedEnd. Each pass parks one more number, so the next pass stops one earlier (sortedEnd--). If a whole pass makes no swap, nothing is out of order: stop. That early exit is why bubble sort is O(n) on sorted input.

See Optimal-ShrinkAndStopEarly/pseudocode.md. Every program runs Example 1 and prints the answer (the part under “Run it locally”); the solution itself is the same code as the practice panel’s Start menu on learnwithkiriti.com, where Shelf Bot can act it out.

optimal

Optimal: Shrink And Stop Early

Bubble sort: shrink the end, stop early

After each pass the biggest bubble rises to sortedEnd, so the next pass stops one earlier; and if a pass made no swap, the array is sorted: stop.

for sortedEnd from size - 1 down to 1:
    swapped = false
    for currBubble from 0 to sortedEnd - 1:
        nextBubble = currBubble + 1
        if nums[currBubble] > nums[nextBubble]:
            swap nums[currBubble] and nums[nextBubble]
            swapped = true
    if not swapped:
        stop            // already sorted

Dry run on Example 1:

sortedEnd pass result swapped?
4 [2, 7, 1, 5, 8] yes
3 [2, 1, 5, 7, 8] yes
2 [1, 2, 5, 7, 8] yes
1 [1, 2, 5, 7, 8] no -> stop

Worst case (reversed input) still O(n²); best case (sorted) one pass, O(n). O(1) extra space. Stable: equal numbers never swap.

BubbleSortOptimal.java
class Solution {
    public void bubbleSort(int[] nums) {
        // after each pass, the biggest bubble rises to sortedEnd
        for (int sortedEnd = nums.length - 1; sortedEnd > 0; sortedEnd--) {
            boolean swapped = false;
            for (int currBubble = 0; currBubble < sortedEnd; currBubble++) {
                int nextBubble = currBubble + 1;
                if (nums[currBubble] > nums[nextBubble]) {
                    swap(nums, currBubble, nextBubble);
                    swapped = true;
                }
            }
            // a pass with no swaps means the array is already sorted
            if (!swapped) {
                break;
            }
        }
    }

    private void swap(int[] nums, int left, int right) {
        int held = nums[left];
        nums[left] = nums[right];
        nums[right] = held;
    }
}