Merge Sort Algorithm -
Merge sort is a Divide and Conquer based Algorithm. It divides the input array into two-parts, until the size of the input array is not ‘1’. In the return part, it will merge two sorted arrays a return a whole merged sorted array.
The above illustrates shows how merge sort works.
It is compulsory to use the ‘Merge Sort’ algorithm.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next 2*'T' lines represent the ‘T’ test cases.
The first line of each test case contains an integer ‘N’ which denotes the size of ‘ARR’.
The second line of each test case contains ‘N’ space-separated elements of ‘ARR’.
For each test case, print the numbers in non-descending order
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 50
1 <= N <= 10^4
-10^9 <= arr[i] <= 10^9
Time Limit : 1 sec
The basic idea is that we divide the given ‘ARR’ into two-part call them ‘leftHalves’ and ‘rightHalves’ and call the same function again with both the parts. In the end, we will get sorted ‘leftHaves’ and sorted ‘righthalves’ which we merge both of them and return a merged sorted ‘ARR’.
We implement this approach with a divide and conquer strategy.
Here is the algorithm :
MERGE() function :
The basic idea is that consider every element of ‘ARR’ as a sorted array of size 1.
Consider given ‘ARR’ : { 8, 3, 4, 6, 1, 5, 7, 2 }
In the first step, merge all the elements of ‘arr’ with a gap of ‘1’ indices so that every element of gap ‘1’ indices become sorted in size of ‘1’ subarray. At the end of this, we will get { 8, 3, 4, 6, 1, 5, 7, 2 }. In the second step, merge all the elements of ‘ARR’ with the gap of ‘2’ indices in the way every element of gap ‘2’ indices are sorted. At the end of this, we will get { 3, 8, 4, 6, 1, 5, 2, 7 } and you can see every pair of size ‘2’ is sorted. In the third step, merge all the elements of ‘ARR’ with the gap of ‘4’. At the end of this, we will get { 3, 4, 6, 8, 1, 2, 5, 7 } and you can see every pair of size ‘4’ is sorted { 3, 4, 6, 8 } and { 1, 2, 5, 7 }. In the fourth step, merge all the elements of ‘ARR’ with the gap of ‘8’ indices. At the end of all step, we will get a sorted ‘ARR’ { 1, 2, 3, 4, 5, 6, 7, 8 }.
Here is the algorithm :