What is the worst-case time complexity of insertion sort?
Practice Questions
Q1
What is the worst-case time complexity of insertion sort?
O(n)
O(n log n)
O(n^2)
O(log n)
Questions & Step-by-Step Solutions
What is the worst-case time complexity of insertion sort?
Step 1: Understand what insertion sort does. It sorts an array by building a sorted section one element at a time.
Step 2: Identify the worst-case scenario for insertion sort. This happens when the array is sorted in reverse order.
Step 3: In the worst case, for each element, the algorithm has to compare it with all the elements in the sorted section.
Step 4: If there are n elements in the array, the first element takes 0 comparisons, the second takes 1, the third takes 2, and so on, up to n-1 comparisons for the last element.
Step 5: Calculate the total number of comparisons. This is 0 + 1 + 2 + ... + (n-1), which equals n(n-1)/2.
Step 6: Simplify the total comparisons. This is approximately n^2/2, which is O(n^2) in big O notation.
Step 7: Conclude that the worst-case time complexity of insertion sort is O(n^2).