Last Updated: 30 Nov, 2021

Insertion Sort

Easy
Asked in companies
Thirdware solutionsNewgen SoftwareCapegemini Consulting India Private Limited

Problem statement

You are given ‘N’ integers in the form of an array ‘ARR’. Print the sorted array using the insertion sort.

Note :
No need to return anything. You should sort the array in-place.
For example :
Let ‘ARR’ be: [1, 4, 2]
The sorted array will be: [1, 2, 4].
Input Format :
The first line of input contains an integer ‘T’, denoting the number of test cases.

The first line of each test case contains an integer, ‘N’, representing the size of the array.

The second line of each test case contains ‘N’ space-separated integers, representing the array ‘ARR’ elements.
Output Format :
For each test case, print the sorted array.

Print output of each test case in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function. 
Constraints :
1 <= T <= 10
1 <= N <= 5*10^3
1 <= ARR[i] <= 10^5

Time Limit: 1 sec

Approaches

01 Approach

Insertion Sort is a sorting algorithm in which we pick an element and move it to its sorted position. We pick an element, compare it to the elements present before it, and change the elements’ position until the current element is smaller than the elements present before it.

Example: 

Let the array be: [5, 2, 1, 3, 4]

Initially, first, two elements are compared in insertion sort. 5 > 2, so we move 2 to its sorted position. Array changes to [2, 5, 1, 3, 4]

Now we move to ‘ARR[2]’, i.e., 1, and compare it with ‘ARR[1], which is greater than ‘ARR[2]’. So we change the position of elements, the array becomes: [2, 1, 5, 3, 4].

Now we compare ‘ARR[0]’ to ‘ARR[1]’, since ‘ARR[0]’ is greater than ‘ARR[0]’ array becomes: [1, 2, 5, 3, 4].

Similarly, we compare other elements and change their positions.

Final array: [1, 2, 3, 4, 5].

 

Here is the algorithm :

 

  1. Run a loop from 1 to ‘N’ (say, iterator ‘i’).
    • Create a variable (say, ‘CURR’) to store the current element and initialize it with ‘ARR[i]’.
    • Create a variable (say, ‘IDX’) to traverse the elements from ‘i’ - 1 to 0 and initialize it with ‘i’ - 1.
    • Run a loop till ‘IDX’ is greater than equal to 0 and ‘ARR[IDX]’ is smaller than ‘CURR’.
      • Update ‘ARR[IDX + 1]’ to ‘ARR[IDX]’.
      • Decrease ‘IDX’ by 1.
    • Update ‘ARR[IDX + 1]’ to ‘CURR’.