How does Python insertion sort work?

前端 未结 21 1506
南方客
南方客 2020-12-10 02:54

Here\'s a Python implementation of insertion sort, I tried to follow the values on paper but once the counting variable i gets bigger than len(s) I don\'t know what to do, h

21条回答
  •  囚心锁ツ
    2020-12-10 03:22

    __author__ = 'Dharmjit'  
    def InsertionSort(list):  
        for index in range(1,len(list)):  
            curr = list[index]  
            position = index  
    
            while position > 0 and list[position-1] > curr:  
                list[position] = list[position-1]  
                position = position - 1  
    
            list[position] = curr  
        return list  
    
    l = [2,1,5,3,9,6,7]  
    print(InsertionSort(l))  
    [1,2,3,5,6,7,9]  
    

    You can see the whole concept here- http://pythonplanet.blogspot.in/2015/07/sorting-algorithm-1-insertion-sort.html

提交回复
热议问题