This is my implementation of the insertion sort as described in that Cormen, Leiserson, Rivest book. The only difference is that I'm using an inner for loop instead of a while loop. I feel it is a bit clunky. How can I simplify this ?
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
range(len(list)
do for index, item in enumerate(list)
. In that case index will be your index and item will be the value of the item you're looking at. BTW, Franck Ribery is one of my favorite soccer players.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.