Professional Documents
Culture Documents
Merge Sort
Merge Sort
technique. In Divide & Conquer algorithm design paradigm, we divide the problems
in sub-problems recursively then solve the sub-problems, & at last combine the
solutions to find the final result.
One thing to keep in mind while dividing the problems into sub-problems is that, the
structure of sub-problems should not change as of the original problem.
Divide & Conquer algorithm has 3 steps:
1. Divide: Breaking the problem into subproblems
2. Conquer: Recursively solving the subproblems
3. Combine: Combining the solutions to get the final result
In Merge sort, we divide the array recursively in two halves, until each sub-array
contains a single element, and then we merge the sub-array in a way that it results
into a sorted array. merge() function merges two sorted sub-arrays into one, wherein
it assumes that array[l .. n] and arr[n+1 .. r] are sorted.
Merge sort is one of the efficient & fastest sorting algorithms with the following time
complexity:
Example:
1. Divide the unsorted array recursively until 1 element in each sub-array remains.
2. Recursively, merge sub-arrays to produce sorted sub-arrays until all the sub-array
merges and only one array remains.
To sort an array using Merge sort, following is the process
We take two variables p & r where p stores the staring index & stores the last index
of the array
Next, we find the mid of the array to break it in two halves. Formula yo do so is
(p+r)/2 and mark the middle element as m.
Next step is to break the given array into two subarrays from the middle element, i.e.
from index p to m & m+1 to r.
We continue to break the subarrays until we reach to a level where each sub array
contains 1 element.
Next we merge the sub-array recursively in a sorted order, so that we finally get a
sorted array.
Merge Function in C
1void merge(int arr[], int l, int m, int r)
2{
3int i, j, k;
4int n1 = m - l + 1;
5int n2 = r - m;
6// Create temp arrays
7int L[n1], R[n2];
8// Copy data to temp array
9for (i = 0; i < n1; i++)
10L[i] = arr[l + i];
11for (j = 0; j < n2; j++)
12R[j] = arr[m + 1+ j];
13// Merge the temp arrays
14i = 0;
15j = 0;
16k = l;
17while (i < n1 && j < n2)
18{
19if (L[i] <= R[j])
20{
21arr[k] = L[i];
22i++;
23}
24else
25{
26arr[k] = R[j];
27j++;
28}
29k++;
30}
31// Copy the remaining elements of L[]
32while (i < n1)
33{
34arr[k] = L[i];
35i++;
36k++;
37}
38// Copy the remaining elements of R[]
39while (j < n2)
40{
41arr[k] = R[j];
42j++;
43k++;
44}
45}
Moving on with this article on Merge Sort in C
// Main Method
1int main()
2{
3int arr[] = {85, 24, 63, 45, 17, 31, 96, 50};
4int arr_size = sizeof(arr)/sizeof(arr[0]);
5printf("Given array is n");
6printArray(arr, arr_size);
7mergeSort(arr, 0, arr_size - 1);
8printf("nSorted array is n");
9printArray(arr, arr_size);
10return 0;
11}
Output: