# Write a program for merge sort in data structure

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.

The merge function compares the elements of both sub-arrays one by one and places the smaller element into the input array. The most important part of the merge sort algorithm is, you guessed it, the "merge" step. When solved, the time complexity will come to O nLogn. Divide and Conquer Strategy Using the Divide and Conquer technique, we divide a problem into subproblems. As the size of input grows, insertion and selection sort can take a long time to run. Merge sort is widely used in various applications as well.

The algorithm can be described as the following 2 step process: Divide: In this step, we divide the input array into 2 halves, the pivot being the midpoint of the array.

### Quick sort in data structure program

After that, the merge function comes into play and combines the sorted arrays into larger arrays until the whole array is merged. So, they adopted the policy of Divide and Rule. It is the best Sorting technique used for sorting Linked Lists. 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. Let us see how merge function will merge the two arrays. Merge sort is widely used in various applications as well. This means that merge sort requires additional space. Beginner Friendly Tutorials for Programmers What do you want to learn today? Conquer In the conquer step, we try to sort both the subarrays A[p..

This means that merge sort requires additional space. 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. Let us see how merge function will merge the two arrays. Divide and Conquer If we can break a single big problem into smaller sub-problems, solve the smaller sub-problems and combine their solutions to find the solution for the original big problem, it becomes easier to solve the whole problem.

Rated 8/10 based on 35 review