Selection Sort Algorithm
The selection sort algorithm sorts an array by repeatedly finding the minimum element (if sorting in ascending order) from the unsorted part of the array and putting it at the end of the sorted part of the array. The algorithm maintains two subarrays in a given array:
- A subarray of already sorted elements.
- A subarray of elements that remain to be sorted.
At the start of the algorithm, the first subarray is empty. In each pass through the outer loop of the selection sort, the minimum element from the unsorted subarray is selected and moved to the end of the sorted subarray.
Pseudocode
procedure selection_sort(array : list of sortable items, n : length of list)
i ← 0
while i < n - 1
min_index ← i
j ← i + 1
while j < n
if array[j] < array[min_index]
min_index ← j
end if
j ← j + 1
end while
swap array[i] and array[min_index]
i ← i + 1
end while
end procedure
Example
The following example illustrates how an array changes after each pass through the outer loop of the selection sort algorithm.
|
Original Array
|
23
|
12
|
18
|
42
|
29
|
37
|
15
|
10
|
|
|
Before 1st Pass
|
23
|
12
|
18
|
42
|
29
|
37
|
15
|
10
|
|
|
After 1st Pass
|
10
|
12
|
18
|
42
|
29
|
37
|
15
|
23
|
|
|
After 2nd Pass
|
10
|
12
|
18
|
42
|
29
|
37
|
15
|
23
|
|
|
After 3rd Pass
|
10
|
12
|
15
|
42
|
29
|
37
|
18
|
23
|
|
|
After 4th Pass
|
10
|
12
|
15
|
18
|
29
|
37
|
42
|
23
|
|
|
After 5th Pass
|
10
|
12
|
15
|
18
|
23
|
37
|
42
|
29
|
|
|
After 6th Pass
|
10
|
12
|
15
|
18
|
23
|
29
|
42
|
37
|
|
|
After 7th Pass
|
10
|
12
|
15
|
18
|
23
|
29
|
37
|
42
|
|
|
Sorted Array
|
10
|
12
|
15
|
18
|
23
|
29
|
37
|
42
|
|
Complexity
Time Complexity: O(n2)
Space Complexity: O(1)
The primary advantage of selection sort is that it never makes more than O(n) swaps, which can be useful if the array elements are large and copying them is a costly operation.