插入排序功能的输出有问题吗?

问题描述 投票:0回答:1

我是计算大学课程的初学者编码员,我当前的课程作业是“编写一个代码,使用 python 函数对数字列表进行排序”。我一直在尝试使用插入排序方法,因为我们的教授说这是最简单的,但我在实际对代码进行排序时遇到了问题。无论我如何修复它,它要么保持数字未排序,要么减去值而不是对它们进行排序。我一直在尝试遵循在线示例代码,但没有成功。我该怎么做才能解决这个问题?

这是我目前的代码:

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 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
python python-3.x insertion-sort
1个回答
0
投票

执行此操作的一个简单方法是创建一个新的排序值列表并返回该列表。

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

随意使用上面的示例(您需要弄清楚如何实现

get_index()
🙂)

© www.soinside.com 2019 - 2024. All rights reserved.