Monday 11 November 2013

Question 6: Number of swaps Selection sort

6. Which one of the following is the tightest upper bound that represents the number of swaps required to sort n numbers using selection sort?

(A) O(log n)
(B) O(n)
(C) O(n log n)
(D) O(n^2)

Ans : (B)

Explanation :
One important thing to observe in the question is that, they have not asked the complexity of the selection sort, but instead they have asked the number of swaps required only.

Lets try to recollect what Selection Sort does.
The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.
Pseudo Code
For N times.
        Find the smallest element in the rest of the unsorted array. {Complexity : O(N)}
        Swap the smallest number with the first unsorted element.
        Adjust sorted and unsorted arrays.
Done.

You can clearly see, each iteration corresponds to O(N) of work. So, complexity would be O(N^2). But we need to do swap only N times in the worst case. So, the number of swaps required would be O(N).

Concepts to Revise :
Sorting Algorithms
Selection Sort
Searching Algorithms

References :

1 comment: