-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)
4

2 回答 2

3

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

>>> mylist = [4,5,6,7,8,9,1]
>>> sorted(mylist)
[1,4,5,6,7,8,9]
于 2013-02-07T00:26:37.063 回答
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
于 2013-02-07T00:32:46.743 回答