Bubble Sort Implementation

Bubble sort explained simply: repeatedly swap adjacent out-of-order items, with an early-exit optimisation. O(n^2) time, stable, in Python, Java and C++.

Problem Statement

Sort an array in ascending order using bubble sort: repeatedly step through the list, compare each pair of adjacent items, and swap them if they are in the wrong order.

Example

Input:  [5, 1, 4, 2, 8]
Pass 1: [1, 4, 2, 5, 8]
Output: [1, 2, 4, 5, 8]

Approach

Each pass "bubbles" the largest remaining element to its correct position at the end. After pass i, the last i elements are sorted, so each pass checks one fewer pair. A swapped flag lets us stop early when a pass makes no swaps (already sorted).

Complexity

  • Time: O(n^2) worst/average, O(n) best (already sorted)
  • Space: O(1)

Solution Code

Python

def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            break
    return arr

Java

void bubbleSort(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 t = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = t;
                swapped = true;
            }
        }
        if (!swapped) break;
    }
}

C++

void bubbleSort(vector<int>& arr) {
    int n = arr.size();
    for (int i = 0; i < n - 1; i++) {
        bool swapped = false;
        for (int j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break;
    }
}

Key Takeaways

  • Bubble sort is stable and in-place but too slow for large inputs.
  • The early-exit flag makes an already-sorted array run in O(n).
  • Reference: CLRS, Introduction to Algorithms; Wikipedia, "Bubble sort".
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.