2013-05-19 61 views
4

我想从我正在经历的算法书创建python实现。虽然我确信python可能具有内置的这些功能,但我认为这是学习该语言的一个很好的练习。反向数字排序列表在python

给出的算法是为数值数组创建一个插入排序循环。这是我能够工作得很好。然后我试着修改它来执行反向排序(从最大到最小)。输出几乎在那里,但我不确定它出错的地方。

首先,排序为越来越多:

sort_this = [31,41,59,26,41,58] 
print sort_this 

for j in range(1,len(sort_this)): 
    key = sort_this[j] 
    i = j - 1 
    while i >= 0 and sort_this[i] > key: 
     sort_this[i + 1] = sort_this[i] 
     i -= 1 
    sort_this[i + 1] = key 
    print sort_this 

现在,逆向排序不工作:

sort_this = [5,2,4,6,1,3] 
print sort_this 

for j in range(len(sort_this)-2, 0, -1): 
    key = sort_this[j] 
    i = j + 1 
    while i < len(sort_this) and sort_this[i] > key: 
     sort_this[i - 1] = sort_this[i] 
     i += 1 
     print sort_this 
    sort_this[i - 1] = key 
    print sort_this 

对于上面的输出是:

[5, 2, 4, 6, 1, 3] 
[5, 2, 4, 6, 3, 3] 
[5, 2, 4, 6, 3, 1] 
[5, 2, 4, 6, 3, 1] 
[5, 2, 6, 6, 3, 1] 
[5, 2, 6, 4, 3, 1] 
[5, 6, 6, 4, 3, 1] 
[5, 6, 4, 4, 3, 1] 
[5, 6, 4, 3, 3, 1] 
[5, 6, 4, 3, 2, 1] 

最后一个数组除了前两个数字之外几乎排序。我哪里错了?

+1

为什么不使用'sort_this [i]

回答

8

range不包括最终值。当你做range(len(sort_this)-2, 0, -1)时,你的迭代从len(sort_this)-2变为1,所以你永远不会碰到第一个元素(在索引0处)。改变你的范围到range(len(sort_this)-2, -1, -1)