简体   繁体   English

插入排序:错误的输出

[英]Insertion Sort: Incorrect output

I am trying to learn more about the insertion sort algorithm by writing a little script, however I got stuck. 我试图通过编写一些脚本来了解有关插入排序算法的更多信息,但是我陷入了困境。

Everything works great, except one number is being displayed multiple times. 一切正常,除了一个数字被多次显示。

My Code: 我的代码:

#
# Insertion Sort
#

def _ord(l):
 lst=[]
 for k in l:
  if not lst:
   lst.append(k)
   continue

  for a,b in enumerate(reversed(lst)):
   if k <= lst[a]:
    lst.insert(a,k)

   if a == len(lst)-1:
    lst.append(k)

 return lst

if __name__ == '__main__':
 l = [3,2,4,6,5,1]
 print _ord(l)

Output: 输出:

[1, 1, 1, 1, 1, 2, 3, 4, 5, 6]
def _ord(l):
    lst=[]
    for k in l:
        print k
        if not lst:
            lst.append(k)
            continue

        for a,b in enumerate(reversed(lst)):
            print a, b
            if k <= lst[a]:
                lst.insert(a,k)
                break  # <-- add this

            if a == len(lst)-1:
                lst.append(k)
        print lst
        print '-' * 80

    return lst


l = [3,2,4,6,5,1]
print _ord(l)

You can use print or pdb to debug your code. 您可以使用printpdb调试代码。

The issue here is when k=1 , k <= lst[a] is True for every other integers in the list, so it inserted five times. 这里的问题是,对于列表中的所有其他整数,当k=1k <= lst[a]True ,它将插入五次。

A quick fix to the fragment is to introduce break point: 对该片段的快速修复是引入break

def _ord(l):
 lst=[]
 for k in l:
  if not lst:
   lst.append(k)
   continue

  for a,b in enumerate(reversed(lst)):
   if k <= lst[a]:
    lst.insert(a,k)
    break
   if a == len(lst)-1:
    lst.append(k)

 return lst

if __name__ == '__main__':
 l = [3,2,4,6,5,1]
 print _ord(l)

EDIT: Have a look at this link in order to check out the execution of your fragment. 编辑:看看这个链接 ,以检查您的片段的执行。

def _old(l): for i in range(1, len(l)): tmp = l[i] for j in reversed(range(i)): if l[j] > tmp: l[j+1] = l[j] l[j] = tmp else: break return l if __name__ == '__main__': l = [3,2,4,6,5,1] print(_old(l))

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

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