How does Python insertion sort work?

前端 未结 21 1675
南方客
南方客 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:23

    I have looked through a number of these posts and i think that people are over complicating this issue. please correct me if i have done this wrong but this is my interpretation of the sort.

    def insert(L): # this creates the definition and assines the list that you input to L
        for i in range(len(L)): # this then loops the next code for the length of the list
            while i > 0 and L[i] < L[i-1]: # this is the main part of the code where it checks
            # if the value from the list is less than the one before it and if it is then it 
            # swaps them around 
                L[i-1], L[i] = L[i], L[i-1] # this code just swaps round the values
                print (L)# prints the list out at the end of each part
    
    
    
    L = [5,2,3,7,6,9,7]
    insert(L)
    

    Using this it outputs:

    [2, 5, 3, 7, 6, 9, 7]
    [2, 3, 5, 7, 6, 9, 7]
    [2, 3, 5, 6, 7, 9, 7]
    [2, 3, 5, 6, 7, 7, 9]
    

    The print function can also be removed from line and can be placed outside the for loop so that it only prints the list at the end. Which would only give the last line:

    [2, 3, 5, 6, 7, 7, 9]
    

提交回复
热议问题