Which of the following sorting algorithm has a worst case time complexity but performs well when the array is nearly sorted?
Which of the following sorting algorithm has a worst case time complexity but performs well when the array is nearly sorted?
Solution
Insertion sort takes each element and shifts it left past larger elements until it reaches its place. The number of shifts equals the number of inversions, so the running time is . For a nearly sorted array there are very few inversions, so it runs close to . For a reverse-sorted array it does the maximum shifting, giving in the worst case.
Selection Sort: always does about comparisons, so it is even on a sorted array.
Bubble Sort: the basic version is on every input. Only the optimised version with a swapped flag stops early, and even then a small element far from its place needs many passes.
Quick Sort: a nearly sorted array with a first or last element pivot gives the worst case , so it performs badly here.
Related questions:
2026: 13 May Shift 2
2026: 19 May Shift 1
2026: 18 May Shift 2