Skip to content

Instantly share code, notes, and snippets.

@ana-balica
Last active August 29, 2015 14:14
Show Gist options
  • Save ana-balica/dbabf683db4cb37e7bfb to your computer and use it in GitHub Desktop.
Save ana-balica/dbabf683db4cb37e7bfb to your computer and use it in GitHub Desktop.
# Selection Sort Algorithm - sorts a sequence in place, for additional
# convenience returns the sequence.
# Time complexity: n^2
# Script is intended to be run with Python3, but is Python2 compatible.
# If running the script with Python2, range() function will return a list.
# Consider changing it to xrange() if using Python3.
from __future__ import print_function
def selection_sort(seq):
length = len(seq)
for j in range(length - 1):
min_index = j
for i in range(j+1, length):
if seq[i] < seq[min_index]:
min_index = i
if min_index != j:
seq[j], seq[min_index] = seq[min_index], seq[j]
return seq
if __name__ == '__main__':
seq = [4, 10, 1, 6, 3, 8, 20, 7]
print(selection_sort(seq))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment