insertion sort problem code example

Example 1: program for insertion sort

# another method similar to 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]:  # if the key element is smaller than elements before it
                temp = arr[k]  # swapping the two numbers
                arr[k] = arr[j]
                arr[j] = temp

                k = j  # assigning the current index of key value to k
        

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)

Example 2: Insertion sort algorithm

INSERTION-SORT(A)
   for i = 1 to n
   	key ← A [i]
    	j ← i – 1
  	 while j > = 0 and A[j] > key
   		A[j+1] ← A[j]
   		j ← j – 1
   	End while 
   	A[j+1] ← key
  End for

Tags:

Misc Example