What is the time complexity of bubble sort in the average case?
Practice Questions
Q1
What is the time complexity of bubble sort in the average case?
O(n)
O(n log n)
O(n^2)
O(log n)
Questions & Step-by-Step Solutions
What is the time complexity of bubble sort in the average case?
Step 1: Understand what bubble sort does. It repeatedly goes through a list of numbers, compares adjacent pairs, and swaps them if they are in the wrong order.
Step 2: Realize that bubble sort has two main loops. The outer loop goes through the entire list, and the inner loop compares each pair of adjacent numbers.
Step 3: Note that in the average case, the inner loop will run about n times for each of the n iterations of the outer loop.
Step 4: Calculate the total number of comparisons. Since there are n iterations of the outer loop and n comparisons in the inner loop, the total is n * n, which is n^2.
Step 5: Conclude that the average case time complexity of bubble sort is O(n^2) because we focus on the highest order term and ignore constants.