简体   繁体   English

插入排序问题——如何遍历每个数字?

[英]Insertion Sort problem -- How do I loop through every number?

I wrote an insertion sort, but it doesn't sort all the numbers.我写了一个插入排序,但它没有对所有数字进行排序。

When I take out ' y = x - 1 ' and just put ' x - 1 ' in there on it's own, the algorithm works.当我取出 ' y = x - 1 ' 并自行将 ' x - 1 ' 放在那里时,算法就起作用了。 With the variable, the algorithm doesn't work.对于变量,算法不起作用。

Please tell me the issue with this algorithm.请告诉我这个算法的问题。

def insertsort(alist):
    for x in range(1, len(alist)):
        y = x-1
        while alist[y] > alist[x]:
            alist[y], alist[x] = alist[x], alist[y]
            x -= 1
            print(alist)



insertsort([1,2,5,7,4,11,8,75,54,101,99])

You probably should be doing your own homework, but, here you go:您可能应该做自己的功课,但是,在这里:

def insertsort(a):
    print(a)
    # finish the sort from left to right
    for fin in range(1, len(a)):
        tst = fin
        # sort from tst down to zero, swapping curr tst w/ lower as needed
        while(tst > 0 and a[tst] < a[tst-1]):
            # swap
            a[tst], a[tst-1] = a[tst-1], a[tst]
            # follow tst down
            tst -= 1
            print(a)

insertsort([9,8,7,6,5,4,3,2,1])

1.It is unnecessary for x -= 1 ,maybe you can delete and run again. 1. x -= 1 没有必要,也许你可以删除并重新运行。 2.Your sorting only done once. 2.您的排序只完成一次。 3. (print(alist) ),this sentence should be aligned with (for...) ,it will get only one list. 3. (print(alist) ),这句话应该与 (for...) 对齐,它只会得到一个列表。 The code is as follows, for reference only.代码如下,仅供参考。

def insertsort(alist):
    for x in range(1,len(alist)):
        for y in range(1,len(alist)):
            z = y-1
            while alist[z] > alist[y]:
                alist[z], alist[y] = alist[y], alist[z]
    print(alist)
insertsort([3,2,5,7,4,11,8,75,54,101,99])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM