我需要在不使用内置sort()的情况下对此列表进行排序。 我想我可以使用插入排序,但我以前从未真正使用它。 我的代码似乎没有用。这有什么问题? 谢谢。
fruits = ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']
for i in range(1, len(fruits)):
tmp = fruits[i]
j = i-1;
while (j>0 and fruits[j] > tmp):
fruits[j+1] = fruits[j]
j = j-1
fruits[j+1] = tmp
print(fruits)
答案 0 :(得分:0)
我改变了两件事并且有效。不完全是一个答案,但可能会帮助你前进。
fruits = ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']
for i in range(0, len(fruits)):
tmp = fruits[i]
j = i-1;
print(fruits)
while (j>-1 and fruits[j] > tmp):
fruits[j+1] = fruits[j]
j = j-1
fruits[j+1] = tmp
print(fruits)
可以通过这种方式变小:
fruits = ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']
for i in range(len(fruits)):
tmp = fruits[i]
j = i-1 # stop index
while (j > -1 and fruits[j] > tmp):
fruits[j:j+2] = tmp,fruits[j] #swap places
j -= 1
print(fruits)
返回:
['apple', 'banana', 'cherry', 'grape', 'peach', 'strawberry']
答案 1 :(得分:0)
内循环中出现的交换操作似乎很奇怪。如果我是一个投注者,我会说这是错误发生的地方。
尝试做一个干净的“交换”,就像你为三个变量做的那样:
a = 10
b = 20
tmp = a
a = b
b = tmp
print(a) # prints 20
print(b) # prints 10
您的代码将变为:
for i in range(1, len(fruits)):
j = i-1
while j >= 0 and fruits[j] > fruits[j+1]:
# Swap the two consecutive elements which are unsorted
tmp = fruits[j]
fruits[j] = fruits[j+1]
fruits[j+1] = tmp
# Prepare to process previous two consecutive elements
j = j-1
答案 2 :(得分:0)
首先用len()替换镜头()。
另一方面,你没有在fruits数组上应用你的函数,你只声明函数。
最后,数组从索引0开始,因此j必须是> = 0。
更正后的代码:
fruits = ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']
def insertion_sort(fruits):
for i in range(1, len(fruits)):
tmp = fruits[i]
j = i-1;
while (j>=0 and fruits[j] > tmp):
fruits[j+1] = fruits[j];
j = j-1;
fruits[j+1] = tmp;
return fruits
if __name__ == "__main__":
fruits2 = insertion_sort(fruits)
print(fruits2)
答案 3 :(得分:0)
fruits = ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']
for i in range(1,len(fruits))
temp=fruits[i]
k = i
while k > 0 and tmp < fruits[k - 1]:
fruits[k] = fruits[k - 1]
k -= 1
fruits[k] = tmp
print fruits
你的循环将执行少一次 J = I-1 J&大于0 它应该是 J&-1个
答案 4 :(得分:0)
这也完美!
Fruits= ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']
def insertionSortFruits():
for i in range(1,len(Fruits)):
key=Fruits[i]
j=i-1
while j>=0 and key<Fruits[j]:
Fruits[j+1]=Fruits[j]
j=j-1
Fruits[j+1]=key
print(Fruits)
#Testing
insertionSortFruits()