Selection Sort in Python

The selection sort algorithm begins by finding the smallest value in the list and then places this smallest value in the first position in the list. And then algorithm is repeated for remaining items in the list.

Finding smallest value in the list is accomplished by a linear search through the list. The user defined function selection() in our program finds the index of the smallest element. And, function selection_sort() takes the value from index given by selection() and places in order.

Python Source Code: Selection Sort


# Select function for selection sort
def selection(sequence, start):
    min_index = start
    
    for i in range(start+1, len(sequence)):
        if sequence[min_index] > sequence[i]:
            min_index = i
    return min_index

# selection sort algorithm
def selection_sort(sequence):
    for i in range(len(sequence)-1):
        min_index = selection(sequence, i)
        temp = sequence[i]
        sequence[i] = sequence[min_index]
        sequence[min_index] = temp

# list to check
lst = [35, 18, 43, 66, 39, 11, 10, 117]

# calling selection_sort algorithm
selection_sort(lst)

# displaying result
print('Sorted list is: ', lst)

Output: Selection Sort

Sorted list is:  [10, 11, 18, 35, 39, 43, 66, 117]