插入排序算法
2017-06-05 本文已影响0人
Cichar
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]