Given an integer array, sort it using the selection sort algorithm.

Selection Sort Overview

Selection sort is an unstable, in-place sorting algorithm known for its simplicity. It has performance advantages over more complicated algorithms in certain situations, particularly where the auxiliary memory is limited. It can be implemented as a stable sort and requires O(n2) time to sort n items, making it inefficient to use on large lists. Among simple average-case O(n2) algorithms, selection sort almost always outperforms bubble sort and generally performs worse than the insertion sort.

The biggest advantage of using a selection sort is that it does a maximum of n swaps (memory write). The insertion sort, on the other hand, does O(n2) number of writes. This can be critical if memory-write operation is significantly more expensive than memory-read operation, such as flash memory, where every write lessens the memory’s lifespan.

How Selection Sort works?

The idea is to divide the array into two subsets – sorted subset and unsorted subset. Initially, the sorted subset is empty, and the unsorted subset is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted subset, swapping it with the leftmost unsorted element (putting it in sorted order), and moving the subset boundaries one element to the right. The following example explains it all:

            3  5  8  4  1  9 -2
i = 0      -2  5  8  4  1  9  3
i = 1      -2  1  8  4  5  9  3
i = 2      -2  1  3  4  5  9  8
i = 3      -2  1  3  4  5  9  8
i = 4      -2  1  3  4  5  9  8
i = 5      -2  1  3  4  5  8  9

 

Practice this algorithm

 
Following is an iterative implementation of the selection sort algorithm in C, Java, and Python:

C


Download  Run Code

Output:

-2 1 3 4 5 8 9

Java


Download  Run Code

Output:

[-2, 1, 3, 4, 5, 8, 9]

Python


Download  Run Code

Output:

[-2, 1, 3, 4, 5, 8, 9]

Both the worst-case and best-case time complexity of selection sort is O(n2), where n is the input size, and it doesn’t require any extra space.

 
The selection sort algorithm can be implemented recursively. Following is the recursive implementation of the selection sort algorithm in C, Java, and Python:

C


Download  Run Code

Output:

-2 1 3 4 5 8 9

Java


Download  Run Code

Output:

[-2, 1, 3, 4, 5, 8, 9]

Python


Download  Run Code

Output:

[-2, 1, 3, 4, 5, 8, 9]

The time complexity of the selection sort recursive algorithm remains the same as the iterative version. However, the auxiliary space used by the recursive version is O(n) for the call stack.

 
References: https://en.wikipedia.org/wiki/Selection_sort