Junior — Middle
How to determine the time complexity of the bubble sort algorithm?
sobes.tech AI
Answer from AI
The time complexity of the bubble sort algorithm is determined by the number of comparisons and swaps it performs.
Bubble sort passes through the array multiple times, comparing neighboring elements and swapping them if they are in the wrong order.
- In the worst and average cases, the algorithm performs approximately n-1 passes over an array of n elements.
- Each pass involves up to n-1 comparisons.
Therefore, the time complexity is O(n²).
Example:
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
std::swap(arr[j], arr[j + 1]);
}
}
}
Thus, the algorithm is inefficient for large arrays due to its quadratic complexity.