Array ( [0] => [1] => questions [2] => Popular-Algorithms [3] => Insertion-Sort ) Popular Algorithms | Insertion Sort | THE INQUISITIVE





Insertion Sort

LEVEL:Beginner

Description

Given a list of integers and a integer (size of array). Sort the given array using Insertion Sort Algorithm.

Input Format

First line contains the size of array (n) followed by n integers separated by spaces.

Output Format

Print the sorted array separated by spaces.


Example 1:

Input
5
4 5 3 2 1
Output
1 2 3 4 5
Example 2:

Input
6
96 54 100 32 45 64
Output
32 45 54 64 96 100
Example 3:

Input
8
55 44 93 82 31
Output
31 44 55 82 93

oops

Login to see Discussion




Approach

Step-i) If it is the first element, it is already sorted. return 1;
Step-ii) Pick next element, Compare with all elements in the sorted sub-list.
Step-iii)Shift all the elements in the sorted sub-list that is greater than the value to be sorted. Insert the value/
Step-iv) Repeat until list is sorted.

Time Complexity: O(n^2)
Space Complexity: O(1)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution