What are the number of swaps required in selection sort for each case?

user3126632 picture user3126632 · Nov 1, 2014 · Viewed 27.7k times · Source

I believe that selection sort has the following behavior:

Best case: No swaps required as all elements are properly arranged

Worst case: n-1 swaps required i.e a swap required for each pass and there are n-1 passes as we know where n is number of elements in array

Average case: Not able to find out this. What is the procedure for finding it out?

Is the above information correct?

This says time complexity of swaps in best case is O(n) http://ocw.utm.my/file.php/31/Module/ocwChp5SelectionSort.pdf

Answer

templatetypedef picture templatetypedef · Aug 27, 2015

Each iteration of selection sort consists of scanning across the array, finding the minimum element that hasn't already been placed yet, then swapping it to the appropriate position. In a naive implementation of selection sort, this means that there will always be n - 1 swaps made regardless of distribution of elements in the input array.

If you want to minimize the number of swaps, though, you can implement selection sort so that it doesn't perform a swap in the case where the element to be moved is already in the right place. If you add in this restriction, then you're correct that zero swaps would be made in the best case. (I'm not sure whether it's worthwhile to modify selection sort this way, since swaps are pretty fast in most cases).

Really, it depends on the implementation. You could potentially have a weird implementation of selection sort that constantly swaps the candidate minimum element to its tentative final spot on each iteration, which would dramatically increase the number of swaps in the worst case. I'm not sure why you'd do this, though. It's little details like this that accounts for why your explanation seems at odds with what you've found online - depending on how the code is put together, the number of swaps can be different.