Professional Documents
Culture Documents
The basic idea of insertion sort is that one element from the
input elements is consumed in each iteration to find its correct
position i.e., the position to which it belongs in a sorted array.
It iterates the next element in the array (It compares the current element with the
largest value in the sorted array):
If the current element is greater than the largest value in the sorted array, then it
leaves the element in its place and moves on to the next element.
Else
It finds its correct position in the sorted array and moves it to that position. This is
done by shifting all the elements, which are larger than the current element, in the
sorted array to one position ahead.
Insertion Sort Steps
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
# Insertion Sort-Python
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Shift array elements greater than the key to the right
#These elements are: arr[0..i-1.
j = i-1
while j >= 0 and key < arr[j] :
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# test the program
arr = [5, 6, 1, 9, 3, 4]
insertionSort(arr)
for i in range (len(arr)):
print ("% d" % arr[i])
Complexity of Insertion Sort