Skip to content

Instantly share code, notes, and snippets.

@uncompiled
Last active October 29, 2017 23:03
Show Gist options
  • Save uncompiled/c4095b03c14b8f553710c939c9ab9b04 to your computer and use it in GitHub Desktop.
Save uncompiled/c4095b03c14b8f553710c939c9ab9b04 to your computer and use it in GitHub Desktop.
Selection Sort (Imperative)
def selection_sort(input_list):
# Save the length of the list
n = len(input_list)
# NOTE: In Python, enumerate returns an index, value pair.
# The _ means that we're ignoring the value.
for current_index, _ in enumerate(input_list):
# Save the location of the smallest item in the list
smallest_index = current_index
# Search the rest of the list for the smallest element
for find_min_index in range(current_index + 1, n):
if input_list[find_min_index] < input_list[smallest_index]:
smallest_index = find_min_index
# smallest_index = location of smallest element in the rest of the list
swap(input_list, current_index, smallest_index)
# The swap function shuffles the values of the array in-place
return input_list
def swap(my_list, a, b):
"""
swap is a helper method that swaps two elements in a list.
WARNING: This operation mutates (changes) the list!
"""
temp = my_list[a] # save the value in position a
my_list[a] = my_list[b] # because this line overwrites it
my_list[b] = temp # and use it to replace position b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment