Algorithm
As of now, we have a rough understanding of the selection sort. Let us now have a look at the
algorithm followed by the code for a better understanding:
1. Create a function Selection_Sort that takes an array as an argument
2. Create a loop with a loop variable i that counts from 0 to the length of the array – 1
3. Declare smallest with the initial value i
4. Create an inner loop with a loop variable j that counts from i + 1 up to the length of
the array – 1.
5. if the elements at index j are smaller than the element at index smallest, then set
smallest equal to j
6. swap the elements at indexes i and smallest
7. Print the sorted list
Python Program
As discussed above in the algorithm, let us now dive into the programming part of the
Selection Sort operation influenced by the algorithm. In this program user can input the list
by giving whitespace in the console part:
def Selection_Sort(array):
for i in range(0, len(array) - 1):
smallest = i
for j in range(i + 1, len(array)):
if array[j] < array[smallest]:
smallest = j
array[i], array[smallest] = array[smallest], array[i]
array = input('Enter the list of numbers: ').split()
array = [int(x) for x in array]
Selection_Sort(array)
print('List after sorting is : ', end='')
print(array)