python数据结构之直接插入排序

python数据结构之直接插入排序

#-*-encoding:utf-8-*-
'''
直接插入排序:
从序列的第二个元素开始,依次与前一个元素比较,如果该元素比前一个元素大,
那么交换这两个元素。该算法适用于少量数据的排序,时间复杂度为O(n^2),是稳定的排序方法。
'''
def InsertSort(L):
    for i in range(1,len(L)):
        key = L[i]
        j = i - 1
        while j >= 0:
            if L[j] > key:
                L[j+1] = L[j]
                L[j] = key
            j -= 1
    return L

L = [5,4,2,3,1]
print("原始序列:")
print(L)
print("直接插入排序:")
print(InsertSort(L))

程序输出结果:

原始序列:
[5, 4, 2, 3, 1]
直接插入排序:
[1, 2, 3, 4, 5]
原文地址:https://www.cnblogs.com/liutongqing/p/7571600.html