DAA-1.2 -
DAA-1.2 -
Insertion sort is based on the idea 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
def insert_srt(a):
for k in range(1, len(a)):
curr_val = a[k]
x = k - 1
while x >= 0 and a[x] >
curr_val:
a[x+1] = a[x]
x -= 1
a[x+1] = curr_val
return a
Code language: Python (python)
To use the algorithm, call the insertion_sort
function and pass in the list that you want to sort as an
argument. For example:
srt_arr=[22,6,15,48,1]
print("List before insertion sort\
n",srt_arr)
sort_list = insert_srt(srt_arr)
print("List after insertion sort\
n",sort_list) Code language: Python
(python)
Insertion Sort Time Complexity
For a general explanation of what time complexity is,
visit this page.
For a more thorough and detailed explanation of
Insertion Sort time complexity, visit this page.
Insertion Sort sorts an array of n values.
On average, each value must be compared to about n2
other values to find the correct place to insert it.
Insertion Sort must run the loop to insert a value in its
correct place approximately n
times.
We get time complexity for Insertion Sort:
O(n2⋅n)=O(n2)––––––––––––––
The time complexity for Insertion Sort can be
displayed like this: