NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Bubble Sort

Bubble sort is a simple comparison sorting algorithm that repeatedly steps through a list, compares adjacent elements, and swaps them if out of order. After each pass, the largest unsorted element settles at the end. It takes O(n²) average/worst time and


Theory & Explanation

Bubble Sort: Definition, Stepwise Working, Complexity & Code

1. Definition & Key Characteristics

Bubble Sort is a simple comparison-based sorting algorithm that repeatedly traverses a list, compares adjacent elements (arr[j] and arr[j+1]), and swaps them whenever they are out of the desired order (for example, when arr[j] > arr[j+1] in ascending order). In every pass, the largest unsorted element "bubbles" up to its final position at the right end of the unsorted portion.

  • In-Place Algorithm: Sorts the array directly using only a temporary variable for swapping, requiring O(1) auxiliary space.
  • Stable Sorting Algorithm: Preserves the relative order of equal elements because swapping occurs only when arr[j] > arr[j+1] (strict inequality).
  • Adaptive (With Swap Flag): If a full pass completes with zero swaps, the array is already sorted and the algorithm can terminate early, giving O(n) best-case time.

2. How Bubble Sort Works (Step-by-Step Algorithm)

  1. Let the input array have n elements at indices 0 to n - 1.
  2. Run an outer pass loop i from 0 to n - 2 (at most n - 1 passes are needed). Initialize a flag swapped = false at the start of each pass.
  3. Run an inner comparison loop j from 0 to n - i - 2 (since the last i elements are already in their final sorted positions).
  4. Compare arr[j] with arr[j + 1]:
    • If arr[j] > arr[j + 1], swap arr[j] and arr[j + 1], and set swapped = true.
  5. After the inner loop ends, if swapped == false, break out of the outer loop early because no swaps were needed.

3. Step-by-Step Example & Graphical Representation

Sort arr = [40, 20, 30, 10] (n = 4) in ascending order:

  • Pass 1 (i = 0, compares j = 0..2):
    • j = 0: Compare 40 & 20 → 40 > 20 → Swap → [20, 40, 30, 10]
    • j = 1: Compare 40 & 30 → 40 > 30 → Swap → [20, 30, 40, 10]
    • j = 2: Compare 40 & 10 → 40 > 10 → Swap → [20, 30, 10, 40] (40 settles at index 3)
  • Pass 2 (i = 1, compares j = 0..1):
    • j = 0: Compare 20 & 30 → 20 ≤ 30 → No swap → [20, 30, 10, 40]
    • j = 1: Compare 30 & 10 → 30 > 10 → Swap → [20, 10, 30, 40] (30 settles at index 2)
  • Pass 3 (i = 2, compares j = 0):
    • j = 0: Compare 20 & 10 → 20 > 10 → Swap → [10, 20, 30, 40] (20 and 10 settled)

Graphical Representation: Stepwise Passes of Bubble Sort on [40, 20, 30, 10]

Bubble Sort Pass-by-Pass Trace (Ascending): [40, 20, 30, 10] → [10, 20, 30, 40] Initial: 40 20 30 10 Unsorted array of size n = 4 Pass 1: 20 30 10 40 40 bubbled to index 3 (sorted) Pass 2: 20 10 30 40 30 bubbled to index 2 (sorted) Pass 3: 10 20 30 40 Array completely sorted! Amber = active unsorted elements | Green = element settled in its final sorted position

4. Time & Space Complexity Analysis

Case Condition Comparisons / Operations Time Complexity
Best Case Array is already sorted (with swap flag) 1 pass of n - 1 comparisons, 0 swaps O(n)
Average Case Randomly ordered elements ~n(n - 1)/4 swaps, n(n - 1)/2 comparisons O(n2)
Worst Case Array is sorted in reverse (descending) order n(n - 1)/2 comparisons and n(n - 1)/2 swaps O(n2)

Auxiliary Space Complexity: O(1) (in-place sorting).

5. C Program: Bubble Sort

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int swapped = 0; // Flag to detect if any swap occurred in this pass
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = 1;
            }
        }
        if (swapped == 0) {
            break; // Already sorted; stop early
        }
    }
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {40, 20, 30, 10};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Original array: ");
    printArray(arr, n);

    bubbleSort(arr, n);

    printf("Sorted array (Ascending): ");
    printArray(arr, n);

    return 0;
}

Expected Output (C):

Original array: 40 20 30 10 
Sorted array (Ascending): 10 20 30 40 

6. Python Program: Bubble Sort

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


if __name__ == "__main__":
    data = [40, 20, 30, 10]
    print("Original array:", data)
    sorted_data = bubble_sort(data[:])
    print("Sorted array (Ascending):", sorted_data)

Expected Output (Python):

Original array: [40, 20, 30, 10]
Sorted array (Ascending): [10, 20, 30, 40]
Advertisement
Advertisement