You are on page 1of 4

Merge Sort

Merge sort is defined as a sorting algorithm that works by dividing an array into
smaller subarrays, sorting each subarray, and then merging the sorted subarrays
back together to form the final sorted array.

1. The elements are split into two sub-arrays (n/2) again and again until only
one element is left.

2. Merge sort uses additional storage for sorting the auxiliary array.

3. Merge sort uses three arrays where two are used for storing each half, and
the third external one is used to store the final sorted list by merging the
other two and each array is then sorted recursively.

4. At last, all sub-arrays are merged to make it ‘n’ element size of the array.

Merge Sort Algorithm

Merge sort is a recursive algorithm that continuously splits the array in half until it
cannot be further divided i.e., the array has only one element left (an array with
one element is always sorted). Then the sorted subarrays are merged into one
sorted array.

Time Complexity
O(n*logn)
Best Case
Average Case O(n*logn)
Worst Case O(n*logn)

Space Complexity

Space Complexity O(n)


Stable YES
Example:

Program for Merge Sort


#include <stdio.h>
void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;

int LeftArray[n1], RightArray[n2]; //temporary arrays

/* copy data to temp arrays */


for (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];

i = 0; /* initial index of first sub-array */


j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */

while (i < n1 && j < n2)


{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}

while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}

void mergeSort(int a[], int beg, int end)


{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}

int main()
{
int a[20],n,i;
printf(“Entere range:”);
scanf(“%d”,&n);
printf(“Enter the elements:”);
for(i=0;i<n;i++)
scanf(“%d”,&n);
printf("Before sorting array elements are\n");
for(i=0;i<n;i++)
printf(“%d\n”,a[i]);
mergeSort(a, 0, n - 1);
printf("After sorting array elements are\n");
for(i=0;i<n;i++)
printf(“%d\n”,a[i]);
return 0;
}

You might also like