I'm a beginner coder in a computational college class and my current assignment for class is to "Make a code that, using python functions, sorts a list of number." I've been trying to use the insertion sorting method as our professor said it was the easiest, but I've been having issues with actually getting the code to sort. No matter what I fix about it, it either keeps the numbers unsorted or it subtracts values rather than sorting them. What would I do to fix this problem?
This is the code I have at the moment:
def sorting_by_insertion(numbers):
for var in range(1,len(numbers)):
sorting = numbers[var]
index = var-1
while var > 0 and numbers[index] > sorting:
numbers[index], sorting = sorting, numbers[index]
sorting = numbers[var+1]
numbers = [8, 5, 1, 3, 7]
print('The list of numbers will be', numbers, 'when unsorted')
sorting_by_insertion(numbers)
print('The list of numbers will be', numbers, 'when sorted')
The current output I keep receiving is:
The list of numbers will be [8, 5, 1, 3, 7] when unsorted
The list of numbers will be [1, 1, 1, 3, 7] when sorted
An easy way to do this would be to create a new list of sorted values and return that.
Feel free to use the above example (you'll need to figure out how to implement
get_index())Or if you'd like an implementation that modifies the existing list: