Created
August 9, 2018 07:03
-
-
Save TomColBee/f90d406cb4960a3bc315a471754ba7e6 to your computer and use it in GitHub Desktop.
Selection Sort Algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# selection sort | |
def selection_sort(n): | |
moves = 0 | |
print("Unsorted list: {}".format(unsorted_list)) | |
length_of_list = len(unsorted_list) | |
for i in range(0,length_of_list-1): | |
# get min of list [i .... length_of_list] | |
min_val = min(unsorted_list[i:length_of_list]) | |
# get the index of the min value | |
# in the new list unsorted_list[i:length_of_list] | |
# add i again to get the original index of the value | |
min_val_index = unsorted_list[i:length_of_list].index(min_val)+i | |
# save the value at the ith index | |
save_i_index_value = unsorted_list[i] | |
# make the ith index equal to the min value | |
unsorted_list[i] = min_val | |
# make the min value index equal to the previous ith value | |
unsorted_list[min_val_index] = save_i_index_value | |
# record moves taken | |
moves += 1 | |
print("Sorted list : {}".format(unsorted_list)) | |
print("Number of iterations made : {}".format(moves)) | |
unsorted_list = [5, 1, 3, 2, 6, 16, 17, 29, 0.1] | |
selection_sort(unsorted_list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment