이것은 Cormen, Leiserson, Rivest 서적에 설명 된대로 삽입 정렬을 구현 한 것입니다. 유일한 차이점은 while 루프 대신 inner for 루프를 사용하고 있다는 것입니다. 나는 그것이 다소 clunky다고 느낀다. 어떻게 이것을 단순화 할 수 있습니까? 대신 for index, item in enumerate(list)
을 range(len(list)
을 통해 반복의이 삽입 정렬 루틴은 어떻게 개선 될 수 있습니까?
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
"어떻게 이것을 간단하게 할 수 있습니까?" 목록에서'.sort()'를 호출하십시오. – robert
@robert OP는 분명히 삽입 정렬 알고리즘을 이해하고 특정 목록을 정렬하는 데 관심이 없습니다. – mjv
삽입 정렬 및 파이썬을 배우고 있습니다. 그래서 이것은 교육적인 운동입니다. –