Selection sorts are a very common method of sorting. Here is a selection sort that is implemented in Python.
def selection_sort(items): for i in range(len(items) - 1): # Assume that the smallest item is located at index i smallest = i # Now loop through the rest of the list for j in range(i + 1, len(items)): # Is our item at index j smaller than our smallest item? if items[j] < items[smallest]: smallest = j # Now swap elements to perform the sort temp = items[smallest] items[smallest] = items[i] items[i] = temp if __name__ == '__main__': items = ['Bob Belcher', 'Linda Belcher', 'Gene Belcher', 'Tina Belcher', 'Louise Belcher'] print(items, '\n') print('Sorting...') selection_sort(items) print(items)
Selection sorts use nested loops to iterate over a list. We check if the item at index j is less than the current smallest item. If j is smaller than smaller, we assign smaller to j.
Once we complete the nested loop, we can perform a swap. Our driver program demonstrates this with strings, but thanks to Python's duck typing system, this will sort any object that implements __lt__
.
When run, we get this output
['Bob Belcher', 'Linda Belcher', 'Gene Belcher', 'Tina Belcher', 'Louise Belcher'] Sorting... ['Bob Belcher', 'Gene Belcher', 'Linda Belcher', 'Louise Belcher', 'Tina Belcher']