【问题标题】:Insertion sort in Python doesn't workPython中的插入排序不起作用
【发布时间】:2016-05-10 03:39:47
【问题描述】:

我从这个问题尝试了这段代码 - Python insertion sort。我稍微修改了代码,去掉了eval()

def sort_numbers(s):
    for i in range(1, len(s)):
        val = s[i]
        j = i - 1
        while (j >= 0) and (s[j] > val):
            s[j+1] = s[j]
            j = j - 1
        s[j+1] = val
    print s

x = raw_input("Enter numbers to be sorted: ").split()
sort_numbers(x)

它不适用于太多的测试用例。

In: 1001 101 20 24 2000 Out: 1001 101 20 2000 24

我也尝试了一些负数。代码不起作用。为什么会这样?

【问题讨论】:

    标签: python sorting insertion-sort


    【解决方案1】:

    这是因为x 是一个字符串列表,而不是整数。您可以通过将此代码放在sort_numbers 之前来更正您的输入示例:

    x = [ int(v) for v in x ]
    

    原始结果

    Enter numbers to be sorted: 1001 101 20 24 2000
    ['1001', '101', '20', '2000', '24']
    

    添加该行后的结果

    Enter numbers to be sorted: 1001 101 20 24 2000
    [20, 24, 101, 1001, 2000]
    

    请注意,现在从print s 显示的列表没有被引号包围的元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多