Startup Data scientist Blog

データ分析系のテック情報を発信します

pythonの挿入ソート(insertion sort)

シンプルで直感的なソートアルゴリズム

def InsertionSort(A):
    for j in range(1, len(A)):
        key = A[j]
        i = j - 1
        while (i >= 0) and (A[i] > key):
            i = i - 1
            A[i+1] = key
input = [8, 3, 9, 15, 29, 7, 10]
InsertionSort(input)
print(input)

Output

>>

[3, 3, 7, 7, 7, 7, 10]