Question #153: In the inner loop of bubble sort algorithm [refer Q55], let’s say we add a check to break the outer loop if there were no interchanges in the full run of the inner loop. Will the worst case of bubble sort improve?
Options:
- There will be improvement in running time but not asymptotically.
- Yes, from O(n2) to O(n log(n))
- Yes, from O(n log(n)) to O(n)
- Yes, from O(n2) to O(n)
Solution: The correct option is the first one. The worst case is when all of the elements are in the descending order and we need to sort them in ascending order. In this case, even for the last run of the outer loop, there will be one exchange, so it won’t benefit from the added check optimization.
You may also want to checkout Q56.