Skip to content

Instantly share code, notes, and snippets.

@davidejones
Created October 6, 2016 19:03
Show Gist options
  • Select an option

  • Save davidejones/35c6dba6762db221e638a4aa581d62db to your computer and use it in GitHub Desktop.

Select an option

Save davidejones/35c6dba6762db221e638a4aa581d62db to your computer and use it in GitHub Desktop.
selection sort
def selection_sort(u, s=[]):
unsorted = list(u)
sorted = [] if not s else s
minimum = None
index = -1
# loop over every number
for i, item in enumerate(unsorted):
# if the number is less than the minimum or we have no minimum yet set it
if not minimum or item < minimum:
minimum = item
index = i
# put minimum in sorted
sorted.append(minimum)
# delete from unsorted
del unsorted[index]
return sorted if len(unsorted) == 0 else selection_sort(unsorted, sorted)
if __name__ == '__main__':
print(selection_sort([1, 12, 4, 7, 3, 5, 2, 6, 11, 10, 9, 13, 8]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment