2013-02-07 47 views
-1

我不知道为什么我的插入排序不起作用。它是用python编码的。当我尝试测试输入时,我得到[4]。插入排序实现

def insertion_sort(list): 
     q =0 
     temp = [] #list to hold sorted values 
     size = len(list) 
     while(q < size): 
      if not temp: #if empty add first element of list 
       temp.append(list[0]) 
      list = list[1:len(list)] #update list so it doesn't include first element 
      for i in range(1,len(temp)): #insertion step 
       if(len(temp)==1): 
        if(list[0] > temp[0]): #if temp is size 1 insert element before/after 
         temp.append(list[0]) 
        else: 
         temp.insert(0,list[0]) 

       else: 
        if(list[0] >= temp[i-1] and list[0] <= temp[i]): #insert value between two values 
         temp.insert(i,list1[0]) 
        if(list[0] <= temp[0]):   # if less than min insert first 
         temp.insert(0,list1[0]) 
        if(list[0] >= temp[len(temp)-1]): # if greater than max, insert last 
         temp.insert(len(temp),list[0]) 
      q=q+1 
     return temp 

    list = [4,3,2,1] 
    print insertion_sort(list) 
+0

...这就是这样的地狱太复杂了插入排序。简化逻辑... – nneonneo

+0

另外,请不要使用'list'作为变量名称。这已经是内建的了。 – nneonneo

+0

你想做什么? – Greg

回答

3

请勿自行实施。使用sorted()内置:

>>> mylist = [4,5,6,7,8,9,1] 
>>> sorted(mylist) 
[1,4,5,6,7,8,9] 
+1

OP可能需要实现插入排序出于某种原因(例如作业)。但是,这是最好的一般建议。 – nneonneo

+0

如果它是作业,它应该是一个downvote,因为他没有明确地告诉我们发布时的问题 – Greg

+0

这不是为了好奇才做作业 – phil12

0

你需要创建一个新的插入排序的代码还是你只是兴趣,为什么它不工作? 这里是那种红粉由DaniWeb插入:

def insertion_sort(list2): 
for i in range(1, len(list2)): 
    save = list2[i] 
    j = i 
    while j > 0 and list2[j - 1] > save: 
     list2[j] = list2[j - 1] 
     j -= 1 
     list2[j] = save 
return list2 
+0

我仍然想知道为什么我的不工作 – phil12