The selection sort algorithm is one of the most intuitive sorting algorithms. It repeatedly finds the minimum element from the array and brings it to the front. Then moves on to finding the minimum element from the remaining array, and repeats this process until reaching the very end of the array.
a = [...]
for i in range(len(a)): # We should place the minimum of a[i:] at a[i]
min_idx = i # Index of the minimum element
for j in range(i + 1, len(a)): # Find the index of the minimum element
if a[j] < a[min_idx]: # If we find a smaller element
min_idx = j # Update the index of the minimum element
a[i], a[min_idx] = a[min_idx], a[i] # Swap a[i] and a[min_idx]
print(a)
On each iteration, we take the minimum from the remaining array and swap the current element and the minimum using their indices. In case the current one is the minimum, nothing will happen, as weβll swap the current one with itself, which wonβt change the array.
Β
The selection sort algorithm finds the minimum element from the array and swaps the current index with that minimum. This means that on each iteration, we loop over the whole remaining array to find the minimum (the min function iterates over the array one by one to find the minimum value). Therefore, the whole running time of the algorithm is n iterations that do around n iterations β operations in total.
Letβs simulate the algorithm on several arrays:
[4, 1, -1, 0, 2, 8]
i = 0 β val = -1 β idx = 2 β swap β [-1, 1, 4, 0, 2, 8]
i = 1 β val = 0 β idx = 3 β swap β [-1, 0, 4, 1, 2, 8]
i = 2 β val = 1 β idx = 3 β swap β [-1, 0, 1, 4, 2, 8]
i = 3 β val = 2 β idx = 4 β swap β [-1, 0, 1, 2, 4, 8]
i = 4 β val = 4 β idx = 4 β swap β [-1, 0, 1, 2, 4, 8]
i = 5 β val = 8 β idx = 5 β swap β [-1, 0, 1, 2, 4, 8]
[10, 5, 1, -1, -2, -7]
i = 0 β val = -7 β idx = 5 β swap β [-7, 5, 1, -1, -2, 10]
i = 1 β val = -2 β idx = 4 β swap β [-7, -2, 1, -1, 5, 10]
i = 2 β val = -1 β idx = 3 β swap β [-7, -2, -1, 1, 5, 10]
i = 3 β val = 1 β idx = 3 β swap β [-7, -2, -1, 1, 5, 10]
i = 4 β val = 5 β idx = 4 β swap β [-7, -2, -1, 1, 5, 10]
i = 5 β val = 10 β idx = 5 β swap β [-7, -2, -1, 1, 5, 10]
[1, 2, 3, 4, 5]
i = 0 β val = 1 β idx = 0 β swap β [1, 2, 3, 4, 5]
i = 1 β val = 2 β idx = 1 β swap β [1, 2, 3, 4, 5]
i = 2 β val = 3 β idx = 2 β swap β [1, 2, 3, 4, 5]
i = 3 β val = 4 β idx = 3 β swap β [1, 2, 3, 4, 5]
i = 4 β val = 5 β idx = 4 β swap β [1, 2, 3, 4, 5]
Challenge
Given n integers, sort them in increasing order using selection sort.
Input
The first line of the input contains a single integer n (1 β€ n β€ 1000) the number of elements in the array.
The next line contains n space-separated integers ( β€ β€ ).
Output
The program should print the array in the input sorted in increasing order.