Selection Sort in Python

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]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s