# Write a c code section for merge sort algorithm array

Merge the left half array and right half-array to get the full array sorted. As shown in the image below, the merge sort algorithm recursively divides the array into halves until we reach the base case of array with 1 element.

Another question that is to be answered — how were the left and the right arrays sorted? Here is how the sorted subarrays will look like: Recursively sorted left half: [1, 4, 5, 6] Recursively sorted right half: [2, 3, 7] Finally, as per step 3, we will merge these 2 halves to create the final sorted array. As usual, a picture speaks a thousand words. It is one of the most popular sorting algorithms and a great way to develop confidence in building recursive algorithms. The merge step of merge sort Every recursive algorithm is dependent on a base case and the ability to combine the results from base cases.

## Merge sort example

So, we do nothing in this case and simply return. As shown in the image below, the merge sort algorithm recursively divides the array into halves until we reach the base case of array with 1 element. Finally, we copy the elements from aux[] to a[]. In merge sort, we break the given array midway, for example if the original array had 6 elements, then merge sort will break it down into two subarrays with 3 elements each. In merge sort we follow the following steps: We take a variable p and store the starting index of our array in this. We pick the smaller one and put it in the final merged array and move the corresponding pointer. And then we have to merge all these sorted subarrays, step by step to form one single sorted array. We again do what we did above — pick the smaller one and put it in the final merged array and move the corresponding pointer. Now, the idea here is that an array with a single element is already sorted, so once we break the original array into subarrays which has only a single element, we have successfully broken down our problem into base problems. It is one of the most popular sorting algorithms and a great way to develop confidence in building recursive algorithms. So, they adopted the policy of Divide and Rule.

Let us see how merge function will merge the two arrays. Once we have divided the main array into subarrays with single elements, then we start merging the subarrays. Rated 6/10 based on 83 review