How does Python insertion sort work?

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

    a recursive implementation

    def insert(x, L):
        if [] == L:      return [x]
        elif x <= L[0]:  return [x] + L
        else:            return [L[0]] + insert(x,L[1:])
    
    def insertion_sort(L):
        if [] == L:  return []
        else:        return insert(L[0], insertion_sort(L[1:]))
    
    # test
    import random
    
    L = [random.randint(1,50) for _ in range(10)]
    
    print L
    print insertion_sort(L)
    
    0 讨论(0)
  • 2020-12-10 03:38

    Consider [3, 2, 1]

    The loop starts with 3. Since it is the first item in the list there is nothing else to do.

    [3, 2, 1]
    

    The next item is 2. It compares 2 to 3 and since 2 is less than 3 it swaps them, first putting 3 in the second position and then placing 2 in the first position.

    [2, 3, 1]
    

    The last item is 1. Since 1 is less than 3 it moves 3 over.

    [2, 3, 3]
    

    Since 1 is less than 2 it swaps moves 2 over.

    [2, 2, 3]
    

    Then it inserts 1 at the beginning.

    [1, 2, 3]
    
    0 讨论(0)
  • 2020-12-10 03:38
    def sort_numbers(list):
        for i in range(1, len(list)):
            val = list[i]
            j = i - 1
            while (j >= 0) and (list[j] > val):
                list[j+1] = list[j]
                j = j - 1
            list[j+1] = val
    
    n = int(input("Enter the no. of elements"))
    list = []
    for i in range(0,n):
      t = int(input())
      list.append(t)
    
    sort_numbers(list)
    
    print list
    
    0 讨论(0)
提交回复
热议问题