Python Insertion Sort

Document 对象参考手册Python3 Examples

Insertion Sort is a simple and intuitive sorting algorithm. Its working principle is to build an ordered sequence. For unsorted data, scan from back to front in the sorted sequence, find the corresponding position and insert.

Example

def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key arr = [12, 11, 13, 5, 6] insertionSort(arr) print ("Sorted array:") for i in range(len(arr)): print ("%d" %arr[i])

Executing the above code produces the following output:

排序后的数组:
5
6
11
12
13

Document 对象参考手册Python3 Examples

Other Extensions