Like bubble sort, selection sort is implemented with one loop nested inside another. This suggests that the efficiency of selection sort, like bubble sort, is n2. To understand why this is indeed correct, consider how many comparisons must take place. The first iteration through the data require n - 1 comparisons to find the minimum value to swap into the first position. Because the first position can then be ignored when finding the next smallest value, the second iteration requires n - 2 comparisons and third requires n - 3. This progression continues as follows:
(n - 1) + (n - 2) + ... +2 + 1 = n(n - 1)/2 = O(n2)
Unlike other quadratic tests, the efficiency of selection sort is independent of the data. Bubble sort, for example, can sort sorted and some nearly-sorted lists in linear time because it is able to identify when it has a sorted list. Selection sort does not do anything like that because it is only seeking the minimum value on each iteration. Therefore, it cannot recognize (on the first iteration) the difference between the following two sets of data: 1 2 3 4 5 6 7 8 9 and 1 9 8 7 6 5 4 3 2. In each case, it will identify the 1 as the smallest element and then go on to sorting the rest of the list. Because it treats all data sets the same and has no ability to short-circuit the rest of the sort if it ever comes across a sorted list before the algorithm is complete, insertion sort has no best or worst cases. Selection sort always takes O(n2) operations, regardless of the characteristics of the data being sorted.
Take a Study Break!