美文网首页程序开发
插入排序 Insertion Sort (Python)

插入排序 Insertion Sort (Python)

作者: Zentopia | 来源:发表于2017-12-14 02:29 被阅读15次

    Python 3 实现:

    def insertion_sort(nums):
        for i in range(len(nums) - 1):
            for j in range(i + 1, 0, -1):
                if nums[j] < nums[j - 1]:
                    tmp = nums[j]
                    nums[j] = nums[j - 1]
                    nums[j - 1] = tmp
                else:
                    break
    
    
    if __name__ == '__main__':
        nums = [4, 0, 1, 2, 3, 5, 6, 7, 8, 9, 1]
        insertion_sort(nums)
        print(nums)
    

    相关文章

      网友评论

        本文标题:插入排序 Insertion Sort (Python)

        本文链接:https://www.haomeiwen.com/subject/aomtwxtx.html