2017-10-08 39 views
0

我需要排序此列表而不使用内置排序()。 我想我可以使用插入排序,但我从来没有真正使用它。 我的代码似乎没有工作。它有什么问题? 谢谢。python,插入排序,字符串

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) 
+1

你实际上是否在任何地方调用'insertion_sort'?如果你这样做了,你会得到一个NameError,因为'lens'没有被定义。 –

+0

另外 - 如果你刚刚开始 - 不要养成用''结尾的习惯 - - 它们不是必需的... –

+0

我遵循了你的建议。谢谢!仍然试图找出什么是错的 – Lexi

回答

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'] 
+0

这很有道理!感谢您的帮助 – Lexi

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 
+0

它是有道理的!谢谢你的帮助! – Lexi

0

首先更换镜头()由LEN ()。

另一方面,你不能在水果数组上应用你的函数,你只需声明函数。

最后,阵列在索引0处开始,所以Ĵ必须> = 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) 
+0

谢谢!我理解第一部分,但是如果__name__ p ==“__main__”部分做什么, 是什么? – Lexi

+0

如果__name__ ==“__main__”用于执行.py如何“主程序” – Suaro

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 =异1 j> 0 它应该是 j> -1

+0

我现在明白了。感谢您的帮助! – Lexi