【问题标题】:reverse numerical sort for list in pythonpython中列表的反向数字排序
【发布时间】:2013-05-14 09:18:39
【问题描述】:

我正在尝试从我正在阅读的算法书中创建 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]

除了前 2 个数字外,最后的数组几乎已排序。我哪里出错了?

【问题讨论】:

  • 为什么不直接使用sort_this[i] &lt; key?这里不需要循环往另一个方向。

标签: python algorithm list sorting reverse


【解决方案1】:

range 不包括结束值。当您执行range(len(sort_this)-2, 0, -1) 时,您的迭代将从len(sort_this)-2 变为1,因此您永远不会碰到第一个元素(在索引0 处)。将您的范围更改为range(len(sort_this)-2, -1, -1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    相关资源
    最近更新 更多