-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 に答える