04.selection sort
Write a Python program to sort a list of elements using the selection sort algorithm.
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
5,3,4,2,1
1,3,4,2,5
1,2,4,3,5
1,2,3,4,5
def selection_sort(items):
n = len(items)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if items[min_idx] > items[j]:
min_idx = j
# swap the found minimum element with the first element
items[i], items[min_idx] = items[min_idx], items[i]
return items
mylist = [5,3,4,2,1]
selection_sort(mylist)