What is the worst-case time complexity of bubble sort?
Practice Questions
Q1
What is the worst-case time complexity of bubble sort?
O(n)
O(n log n)
O(n^2)
O(1)
Questions & Step-by-Step Solutions
What is the worst-case time complexity of bubble sort?
Step 1: Understand what bubble sort is. It is a sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
Step 2: Know that the worst-case scenario occurs when the array is sorted in reverse order. This means every element needs to be compared and swapped.
Step 3: In bubble sort, for each element in the array, we need to compare it with every other element. If there are n elements, we will have to do this n times.
Step 4: The number of comparisons in the worst case is n (for the first pass) + (n-1) (for the second pass) + (n-2) (for the third pass) and so on, which adds up to n + (n-1) + (n-2) + ... + 1.
Step 5: This sum equals n(n-1)/2, which simplifies to O(n^2) in big O notation.
Step 6: Therefore, the worst-case time complexity of bubble sort is O(n^2).