python - python中列表的反向数字排序

标签 python algorithm list sorting reverse

我正在尝试根据我正在阅读的算法书创建 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 个数字外,最终数组几乎已排序。我哪里出错了?

最佳答案

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

关于python - python中列表的反向数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16638963/

相关文章:

python - 按组计算连续重复项

c - 插入排序调试帮助

c++ - 移动数组中的元素 C++

c - 删除 C 中重复的整数对的有效方法

list - Magento "Unable to list current working directory"

Python 单元测试所有测试用例

python - 了解多模块环境中的 Python sqlite 机制

python - 如何计算 Django 多对多关系中包含特定值的项目

c# - 过滤 ListView 未触发

c++ - 是否有一种标准方法可以将容器<Type1> 转换为容器<Type2>?