为什么不对9进行排序?我玩过循环条件,但看不到错误:
def insertionSort(L):
n = len(L)
for x in range(1,n):
tgtNum = L[x]
for y in range(x-1,-1,-1):
if L[y] > tgtNum:
L[y], L[x] = L[x], L[y]
print(L)
print()
return(L)
myList = [2,9,1,7,5]
print(insertionSort(myList))
答案 0 :(得分:3)
这是我的解决方案,你的第二个循环是你的问题
def insertionSort(L):
n = len(L)
for x in range(1,n):
tgtNum = L[x]
for y in range(0, x):
if L[y] > tgtNum:
temp = L[y]
L[y] = L[x]
L[x] = temp
print(L)
print()
return(L)
myList = [2,9,1,7,5]
print(insertionSort(myList))
输出为:[1,2,5,7,9]