python 代码实现插入排序

拥有回忆 提交于 2019-11-26 20:21:06
def insert_sort(alist):
    '''插入排序'''
    n = len(alist)
    for j in range(1,n):
        i = j
        while i > 0:
            if alist[i] < alist[i-1]:
                alist[i], alist[i-1] = alist[i-1],alist[i]
                i -= 1
            else:
                break

if __name__ == '__main__':
    li = [1, 30, -6, 0, 98, 99, 4]
    print(li)
    insert_sort(li)
    print(li)

C:\Users\user\AppData\Local\Programs\Python\Python36\python.exe “C:/Users/user/PycharmProjects/hellow python/test.py”
[1, 30, -6, 0, 98, 99, 4]
[-6, 0, 1, 4, 30, 98, 99]

Process finished with exit code 0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!