Which one of the following in place sorting algorithms needs the minimum number of swaps?
(A) Quick sort
(B) Insertion sort
(C) Selection sort
(D) Heap sort
Let’s try to analyse the number of swaps in each of the given sorting algorithms.
Quick sort – Worst Case input for maximum number of swaps will be already sorted array in decreasing order.
Recurrence for Total number of swaps in this case :
T(n) = T(n-1) + O(n) // O(n) swaps will occur in alternate calls to partition algorithm.
Insertion sort – Worst Case input for maximum number of swaps will be already sorted array in ascending order.When a new element is inserted into an already sorted array of k size, it can lead to k swaps (in case it is the smallest of all) in worst case. For n-1 iterations of insertion sort, total swaps will be O(n2).
Selection sort – There is no Worst case input for selection sort. Since it searches for the index of kth minimum element in kth iteration and then in one swap, it places that element into its orrect position. For n-1 iterations of selection sort, it can have O(n) swaps.
Heap sort – Total number of swaps in Heap sort can be O(nlogn) as after performing Build-heap which may require O(n) swaps, it performs n-1 extract-min operations resulting into O(nlogn) swaps.
See Question 3 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-7/
This solution is contributed by Pranjul Ahuja
Quiz of this Question