这是我在Cormen,Leiserson,Rivest书中描述的插入排序的实现。唯一的区别是我使用内部for循环而不是while循环。我觉得它有点笨重。我该如何简化这个?
def isort(list):
if len(list) <= 1:
return list
# pick the next item for insertion from LEFT to RIGHT
for j in range(1, len(list)):
current = list[j]
# invariant: [0:j-1] is sorted
# range(0,j) returns everything up j-1
# Pick the next item to compare from RIGHT TO LEFT
ip = j-1
inorder = False
moved = False
for i in reversed(range(0,j)):
ip = i
if list[i] > current:
# move it to the right
list[i+1] = list[i]
moved = True
else:
inorder = True
break;
if moved:
if inorder:
list[ip+1] = current
else:
list[ip] = current
return list
答案 0 :(得分:0)
range(len(list)
执行for index, item in enumerate(list)
。在这种情况下,索引将是您的索引,而项目将是您正在查看的项目的值。