Let's break down the time complexity of Bubble Sort.
The worst-case time complexity of the Bubble Sort algorithm is O(n²) (pronounced "Big O of n-squared" or "quadratic time").
Here’s the detailed explanation of why.
The worst-case scenario for Bubble Sort occurs when the input array is sorted in reverse order.
For example, if we want to sort in ascending order, the worst-case input would be an array like: [5, 4, 3, 2, 1]
.
In this situation, every element is as far as possible from its correct sorted position. This forces the algorithm to perform the maximum number of comparisons and swaps.
Bubble Sort works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. This process is repeated until the list is sorted. This behavior is achieved with two loops:
n-1
times to ensure every element is placed correctly.Let's analyze the number of comparisons the inner loop performs for an array of size n
in the worst-case scenario.
Pass 1: The inner loop compares all adjacent elements from the beginning to the end. It performs n-1
comparisons. After this pass, the largest element is guaranteed to be in its correct final position at the end of the array.
Example [5,4,3,2,1]
*: 5 gets swapped with 4, then 3, then 2, then 1, moving all the way to the end.
Pass 2: Since the largest element is now sorted, the inner loop only needs to check up to the second-to-last element. It performs n-2
comparisons. After this pass, the second-largest element is in its correct position.
Pass 3: The inner loop performs n-3
comparisons.
... and so on ...
Final Pass: The last pass performs only 1 comparison.
To find the total number of comparisons, we need to sum the work done in each pass:
Total Comparisons = (n-1) + (n-2) + (n-3) + ... + 2 + 1
This is a well-known arithmetic series, and the sum can be calculated with the formula:
Sum = k * (k+1) / 2
, where k = n-1
Total Comparisons = (n-1) * ((n-1) + 1) / 2
= (n-1) * n / 2
= (n² - n) / 2
= (1/2)n² - (1/2)n
When determining Big O complexity, we focus on how the runtime grows as n
(the input size) becomes very large. To do this, we:
1. Identify the fastest-growing term (the dominant term).
2. Ignore constants and lower-order terms.
In the expression (1/2)n² - (1/2)n
:
The dominant term is n²
.
We drop the constant 1/2
and the lower-order term (1/2)n
.
This leaves us with O(n²).
The worst-case time complexity of Bubble Sort is O(n²) because, for a reverse-sorted array of size n
, the algorithm must perform a number of comparisons proportional to n²
due to its nested loop structure. This quadratic growth makes Bubble Sort very inefficient for large datasets compared to more advanced algorithms like Merge Sort or Quick Sort (which have an average-case complexity of O(n log n)).