You are on page 1of 2

Practical-2

Aim:- Algorithm and Implementation of


Insertion Sort.
Algorithm:-
Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
Program:-
def InsertionSort(a):
for i in range(1, len(a)):
temp = a[i]
j = i-1
while j >=0 and temp < a[j] :
a[j+1] = a[j]
j -= 1
a[j+1] = temp
# array to be sorted
a = [10, 5, 13, 8, 2]
InsertionSort(a)
print("Array after sorting:")
print(a)
Output:-
Array after sorting:
[2, 5, 8, 10, 13]
Time Complexity:-
 The worst case time complexity of Insertion sort is O(N2).
 The average case time complexity of Insertion sort is O(N2).
 The time complexity of the best case is O(N).

You might also like