插入排序实现

时间:2013-02-07 00:17:32

标签: python sorting

我不确定为什么我的插入排序不起作用。它用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)

2 个答案:

答案 0 :(得分:3)

不要自己实现。使用sorted()内置:

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

答案 1 :(得分: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