INSERTION SORT

Introduction

Insertion sort works in a similar way we sort the playing cards in our hands. Insertion sort is a simple and efficient comparison sort.

In this algorithm we first partition the array into two parts and consider that the left sub array is sorted and right sub array is unsorted. In every iteration an element is removed from the input data and is inserted into the correct position in the list being sorted.

This algorithm falls under Decrease & Conquer Technique which is based on exploiting the relationship between a solution to a given instance of a problem and a solution to its smaller instance. Let's look at the working of this algorithm.

Working Procedure

Do refer the code available the end of this section to understand the following theory.

  1. Consider an array,arr of n elements. Let key be the element which gets placed in it's position in the array being sorted for every iteration(i.e. the elements before this key are considered to be sorted and the elements after the key will be unsorted).
  2. Loop from i = 1 to n-1
  3. Assign key = arr[i].
  4. Loop from j = i-1 to 0.
  5. If arr[j] > key then assign arr[j+1]=arr[j] and decrement j by 1 (i.e shift all the elements in the sorted sub array that are greater than the key).
  6. Else break the loop at step 4.
  7. After the step 4 loops get over, assign arr[j+1] = key(i.e. insert key at its position among the sorted sub array).
  8. After the loop at step 2 gets over, we have our required sorted array.

Time Complexity

PS: We give random inputs because the no. of input will generally be 100 or 1000 to find the time complexity and manually giving so many inputs is cumbersome work.

There exists two recursive calls in which the elements gets partitioned in each call. The basic operation in this algorithm is the comparison between at step 5 in the above working procedure. So increment the count variable above this if condition to get the count of no. of times the basic operation has been performed.

Insertion Sort

Time Complexity: O(n2)

Code file

Please open this in your pc or with a compatible app in your mobile.

C++ Implementation for INSERTION SORT

That's it from this blog post. If you liked it then do share this blog with your friends or people who wanna get into programming world. Thank You!

Copyright © NStF Blogs 2021