How does Python insertion sort work?

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

    To see how that implementation works, check it out visualized here: http://goo.gl/piDCnm

    However, here is a less confusing implementation of insertion sort:

    def insertion_sort(seq):
        for i in range(1, len(seq)):
            j = i
            while j > 0 and seq[j - 1] > seq[j]:
                seq[j - 1], seq[j] = seq[j], seq[j - 1]
                j -= 1
    

提交回复
热议问题