用于插入排序的Python程序
插入排序是一种简单的排序算法,其工作方式类似于我们对手中的扑克牌进行排序。
# Python program for implementation of Insertion Sort
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])
# This code is contributed by Mohit Kumra
输出:
Sorted array is:
5
6
11
12
13
有关更多详细信息,请参阅有关插入排序的完整文章!