sample code example for insertion sort in python
Example 1: insertion sort python
def insertionSort(alist):
for i in range(1,len(alist)):
current = alist[i]
while i>0 and alist[i-1]>current:
alist[i] = alist[i-1]
i = i-1
alist[i] = current
return alist
print(insertionSort([5,2,1,9,0,4,6]))
Example 2: program for insertion sort
def insertionSort(arr):
for i in range(1, len(arr)):
k = i
for j in range(i-1, -1, -1):
if arr[k] < arr[j]:
temp = arr[k]
arr[k] = arr[j]
arr[j] = temp
k = j
arr = [5, 2, 9, 1, 10, 19, 12, 11, 18, 13, 23, 20, 27, 28, 24, -2]
print("original array \n", arr)
insertionSort(arr)
print("\nSorted array \n", arr)