美文网首页
插入排序算法

插入排序算法

作者: Cichar | 来源:发表于2017-06-05 21:59 被阅读0次
    def insertion_sort(arr, reverse=False):
        if not reverse:
            for j in range(len(arr)):
                key = arr[j]
                i = j - 1
                while i >= 0 and arr[i] > key:
                    arr[i + 1] = arr[i]
                    i -= 1
                arr[i + 1] = key
        else:
            for j in range(len(arr)):
                key = arr[j]
                i = j - 1
                while i >= 0 and arr[i] < key:
                    arr[i + 1] = arr[i]
                    i -= 1
                arr[i + 1] = key
        return arr
    
    if __name__ == '__main__':
        print(insertion_sort([5, 2, 4, 6, 1, 3]))               # 输出 [1, 2, 3, 4, 5, 6]
        print(insertion_sort([5, 2, 4, 6, 1, 3], reverse=True)) # 输出 [6, 5, 4, 3, 2, 1]
    

    相关文章

      网友评论

          本文标题:插入排序算法

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