How does Python insertion sort work?

前端 未结 21 1750
南方客
南方客 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 03:29

    Try this one, works for both increasing and decreasing order:

    import operator
    
    def insertion_sort(arr, reverse=False):
        # check if array is empty or not
        if arr is None:
            raise TypeError("Data cannot be none")
    
        n = len(arr)
        # if length of array is less than two it is already sorted
        if n < 2:
            return arr
    
        lgt = operator.gt if reverse else operator.lt
    
        # Traverse through 1 to len(arr)
        for i in range(1, n):
            key = arr[i]
            j = i-1
            while j >= 0 and lgt(key, arr[j]):
                arr[j+1] = arr[j]
                j -= 1
            arr[j+1] = key
        return arr
    
    li = [1, 4, 8, 9, 42, 0, 36]
    print(insertion_sort(li))
    

提交回复
热议问题