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)
- Let the input array have
nelements at indices0ton - 1. - Run an outer pass loop
ifrom0ton - 2(at mostn - 1passes are needed). Initialize a flagswapped = falseat the start of each pass. - Run an inner comparison loop
jfrom0ton - i - 2(since the lastielements are already in their final sorted positions). - Compare
arr[j]witharr[j + 1]:- If
arr[j] > arr[j + 1], swaparr[j]andarr[j + 1], and setswapped = true.
- If
- 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, comparesj = 0..2):j = 0: Compare40 & 20→40 > 20→ Swap →[20, 40, 30, 10]j = 1: Compare40 & 30→40 > 30→ Swap →[20, 30, 40, 10]j = 2: Compare40 & 10→40 > 10→ Swap →[20, 30, 10, 40](40settles at index 3)
- Pass 2 (
i = 1, comparesj = 0..1):j = 0: Compare20 & 30→20 ≤ 30→ No swap →[20, 30, 10, 40]j = 1: Compare30 & 10→30 > 10→ Swap →[20, 10, 30, 40](30settles at index 2)
- Pass 3 (
i = 2, comparesj = 0):j = 0: Compare20 & 10→20 > 10→ Swap →[10, 20, 30, 40](20and10settled)
Graphical Representation: Stepwise Passes of Bubble Sort on [40, 20, 30, 10]
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]