The selection sort is a nice algorithm, it’s not the fastest but definitely a step up from the bubble sort. It is simple and easy to remember.
With the selection sort:
- identify the smallest item in the source list
- extract it to the new ordered list
- repeat for each item in the source list
Here is a Python implementation:
def find_smallest_index(items):
smallest = items[0]
smallest_index = 0
for i in range(1, len(items)):
if items[i] < smallest:
smallest = items[i]
smallest_index = i
return smallest_index
def selection_sort(items):
results = []
for i in range(len(items)):
index = find_smallest_index(items)
item = items.pop(index)
results.append(item)
return results
And a simple example:
print(selection_sort([53, 13, 46, 2, 10, 88, 4, 11, 14, 23])) # outputs: [2, 4, 10, 11, 13, 14, 23, 46, 53, 88]