python中列表的反向数字排序

mar*_*der 4 python sorting algorithm reverse list

我正在尝试从我正在经历的算法书中创建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
Run Code Online (Sandbox Code Playgroud)

现在,反向排序不起作用:

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
Run Code Online (Sandbox Code Playgroud)

上面的输出是:

[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]
Run Code Online (Sandbox Code Playgroud)

除了前两个数字之外,最终的数组几乎是排序的.我哪里出错了?

Bre*_*arn 8

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