Junior — Middle
What is the time complexity of the bubble sort algorithm?
sobes.tech AI
Answer from AI
The bubble sort algorithm has a time complexity:
- In the worst and average case: O(n²), where n is the number of elements in the array.
- In the best case (if the array is already sorted): O(n), thanks to an optimization with a flag that stops the sorting if no swaps were made during a pass.
Example in Java:
void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
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 = true;
}
}
if (!swapped) break; // array is already sorted
}
}