Python中的插入排序并不起作用

时间:2016-05-10 03:39:48

标签: python sorting insertion-sort

我从这个问题尝试了这段代码 - Python insertion sort。我稍微修改了代码,摆脱了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

对于一些测试用例来说,它并不起作用。

.exe

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

1 个答案:

答案 0 :(得分: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显示的列表没有用引号

包围的元素
相关问题