Write a c program to implement merge sort algorithm

Let us take an example: Given Array: [6, 4, 5, 1, 2, 7, 3] First, as per step 1 above, we divide the array into 2 parts. No further breakdown is possible now.

merge sort in c using recursion

Moreover, merge sort is of interest because it creates an excellent case study for one of the widely used techniques in Computer Science — divide and conquer. In the above example, we are given 2 arrays [1, 4, 5, 6] and [2, 3, 7]. Final merged and sorted array: [1, 2, 3, 4, 5, 6, 7] The left and the right halves can always be sorted recursively using the same algorithm.

You all must notice this section whenever you visit the site. Let us see how merge function will merge the two arrays. Merge Sort Algorithm The divide and conquer algorithm of merge sort has two parts.

Merge sort program in java

Divide If q is the half-way point between p and r, then we can split the subarray A[p.. Single element sub-arrays are merged to become two element sorted sub-arrays. The array A[ The most important part of the merge sort algorithm is, you guessed it, the "merge" step. Here is an animation that explains the same. The same applied with others also. At the beginning, the whole array is the first sub-array. When the solution to each subproblem is ready, we 'combine' the results from the subproblems to solve the main problem.

These subarrays are a[i. After that, the merge function picks up the sorted sub-arrays and merges them to gradually sort the entire array.

Write a c program to implement merge sort algorithm

For instance, consider the right array: [2, 7, 3]. As we can see, the following are the subarrays left half and right half: Left half: [6, 4, 5, 1] Right half: [2, 7, 3] Then, as per step 2 above, we recursively sort the left and right halves. We have a list containing 9, 7, 8, 3, 2, 1. This is a highly parallelizable algorithm. To sort it, we will break it again into 2 sub-arrays: [2, 7] and [3]. Like 9 and 7 is compared and 7 will be placed before 9. Then they start recommending what you have bought and what you like. And finally we will get the sorted array as 1, 2, 3, 7, 8, 9. In the above example, we are given 2 arrays [1, 4, 5, 6] and [2, 3, 7]. 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. Unlike bubble sort or insertion sort , it is usable in most practical cases.
Rated 5/10 based on 20 review
Download
Merge Sort Algorithm