issues with output for insertion sorting function?

66 views Asked by At

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
2

There are 2 answers

0
nate-thegrate On

An easy way to do this would be to create a new list of sorted values and return that.

def get_index(sorted_list, value_to_add) -> int:
    """returns the index to insert the new value so that the new list will stay sorted"""

def insertion_sort(numbers: list):
    sorted_numbers = []
    for number in numbers:
        index = get_index(sorted_numbers, number)
        sorted_numbers.insert(index, number)
    return sorted_numbers

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:

def insertion_sort(numbers: list):
    for index in range(len(numbers)):
        value = numbers.pop(index)
        new_index = get_index(numbers[:index], value)
        numbers.insert(new_index, value)
1
Anna Andreeva Rogotulka On

var uses mistakenly where you should have used index when swapping elements

def sorting_by_insertion(numbers):
    for var in range(1, len(numbers)):
        sorting = numbers[var]
        index = var - 1
        while index >= 0 and numbers[index] > sorting:
            numbers[index + 1] = numbers[index]
            index -= 1
        numbers[index + 1] = sorting

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')