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].
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.
1 <= T <= 10
1 <= N <= 5*10^3
1 <= ARR[i] <= 10^5
Time Limit: 1 sec
2
4
3 1 2 2
3
1 4 2
1 2 2 3
1 2 4
For test case 1:
The sorted array will be: [1, 2, 2, 3].
For test case 2:
The sorted array will be: [1, 2, 4].
2
4
4 12 11 20
6
6 5 4 3 2 1
4 11 12 20
1 2 3 4 5 6
Try to place the elements at their positions one at a time.
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 :
O(N^2), where ‘N’ is the size of the array.
We run a loop to traverse all the elements of the array, which takes O(N) time, and for each element, we again run a loop to place it at its sorted position, which can take O(N) time. Therefore, the overall time complexity will be O(N^2).
O(1)
We don’t use any extra space. Therefore, the overall space complexity will be O(1).