如何进行范围缩小的插入排序

时间:2018-11-30 16:30:32

标签: python sorting

由于列表上的前2个数字排序不正确,我想在插入范围的递减范围内加上什么使之起作用?

def insertion_sort(list):    
     for index in range(len(list)-1,0,-1):    
       current_value = list[index]         
       position = index 

       while position > 0 and list[position - 1] > current_value:             
          list[position] = list[position - 1]           
          position = position - 1 

       list[position] = current_value 

list = [87,95,6,18,25,42,1,78,61]
insertion_sort(list) 
print(list)

1 个答案:

答案 0 :(得分:0)

尝试此代码。

def insertionSort(list):       
    for j in xrange(1,len(list)):
        valToInsert = list[j]
        i = j-1
        while 0 <= i and valToInsert>list[i]:
            list[i+1] = list[i]
            i -= 1
        list[i+1] = valToInsert
    return list

list = [54,26,93,17,77,31,44,55,20]
insertionSort(list)
print(list)