How does Python insertion sort work?

前端 未结 21 1697
南方客
南方客 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
    2020-12-10 03:26

    +An alternative with two for loops and descriptive names.

    def insertionSort(list):
      for outerIndex in range(len(list)):
        for innerIndex in range(outerIndex, 0, -1):
          if list[innerIndex] >= list[innerIndex - 1]:
            break
          list[innerIndex], list[innerIndex - 1] = list[innerIndex - 1], list[innerIndex]
      return list
    
    print insertionSort([3, 1e-10, 7e5, 2.3, 100, -2.5, 12.1])
    # => [-2.5, 1e-10, 2.3, 3, 12.1, 100, 700000.0]
    

提交回复
热议问题