2013-02-07 37 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