Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

MERGE SORT

Merge sort is a sorting technique based on divide and conquer technique. With worst-case
time complexity being 0(n log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted
Manner. Or

Merge sort is based on the divide-and-conquer paradigm. Its worst-case running time has a
lower order of growth than insertion sort. Since we are dealing with sub-problems, we state each
sub-problem as sorting a sub-array A[p .. r]. Initially, p = 1 and r = n, but these values change as
we recurse through sub-problems.

TO SORT A[p .. r]:

1. Divide Step
If a given array A has zero or one element, simply return; it is already sorted. Otherwise, split
A[p .. r] into two sub-arrays A[p .. q] and A[q + 1 .. r], each containing about half of the elements
of A[p .. r]. That is, q is the halfway point of A[p .. r].

2. Conquer Step
Conquer by recursively sorting the two sub-arrays A[p .. q] and A[q + 1 .. r].

3. Combine Step
Combine the elements back in A[p .. r] by merging the two sorted sub-arrays A[p .. q] and A[q +
1 .. r] into a sorted sequence. To accomplish this step, we will define a procedure MERGE (A, p,
q, r).

Note that the recursion bottoms out when the sub-array has just one element, so that it is trivially
sorted.

To sort the entire sequence A[1 .. n], make the initial call to the procedure MERGE-SORT (A,
1, n).

MERGE-SORT (A, p, r)

1. IF p < r // Check for base case


2. THEN q = FLOOR [(p + r)/2] // Divide step
3. MERGE (A, p, q) // Conquer step.
4. MERGE (A, q + 1, r) // Conquer step.
5. MERGE (A, p, q, r) // Conquer step.
How Merge Sort Works?
To understand merge sort, we take an unsorted array as the following –

We know that merge sort first divides the whole array iteratively into equal halves unless
the atomic values are achieved. We see here that an array of 8 items is divided into two
arrays of size 4.

This does not change the sequence of appearance of items in the original. Now we divide
these two arrays into halves.

We further divide these arrays and we achieve atomic value which can no more be divided.

Now, we combine them in exactly the same manner as they were broken down. Please
note the color codes given to these lists.
We first compare the element for each list and then combine them into another list in a
sorted manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and
in the target list of 2 values we put 10 first, followed by 27. We change the order of 19
and 35 whereas 42 and 44 are placed sequentially.
In the next iteration of the combining phase, we compare lists of two data values, and
merge them into a list of found data values placing all in a sorted order.

After the final merging, the list should look like this –

IN OTHER WAY MERGE SORT CAN BE EXPLAINED IN THIS FORMAT


Now we should learn some programming aspects of merge sorting.

ALGORITHM

Merge sort keeps on dividing the list into equal halves until it can no more be divided. By
definition, if it is only one element in the list, it is sorted. Then, merge sort combines the
smaller sorted lists keeping the new list sorted too.

Step 1 − if it is only one element in the list it is already sorted, return.


Step 2 − divide the list recursively into two halves until it can no more be
divided.
Step 3 − merge the smaller lists into new list in sorted order.

PSEUDOCODE

We shall now see the pseudodes for merge sort functions. As our algorithms point out
two main functions − divide & merge.
Merge sort works with recursion and we shall see our implementation in the same way.

procedure mergesort( var a as array )


if ( n == 1 ) return a

var l1 as array = a[0] ... a[n/2]


var l2 as array = a[n/2+1] ... a[n]
l1 = mergesort( l1 )

l2 = mergesort( l2 )
return merge( l1, l2 )

end procedure

procedure merge( var a as array, var b as array )

var c as array
while ( a and b have elements )
if ( a[0] > b[0] )
add b[0] to the end of c
remove b[0] from b
else
add a[0] to the end of c
remove a[0] from a
end if

end while
while ( a has elements )
add a[0] to the end of c
remove a[0] from a
end while

while ( b has elements )


add b[0] to the end of c
remove b[0] from b
end while

return c

end procedure

Merge sort is a sorting technique based on divide and conquer technique. With the worstcase
time complexity being Ο(n log n), it is one of the most respected algorithms.

Implementation
We shall see the implementation of merge sort in C programming language here –

#include <stdio.h>
#define max 10
int a[10] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44 };
int b[10];

void merging(int low, int mid, int high) {


int l1, l2, i;
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}

while(l1 <= mid)


b[i++] = a[l1++];
while(l2 <= high)
b[i++] = a[l2++];
for(i = low; i <= high; i++)
a[i] = b[i];
}

void sort(int low, int high) {


int mid;
if(low < high) {
mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
}else {
return;
}
}

int main() {
int i;
printf("List before sorting\n");
for(i = 0; i <= max; i++)
printf("%d ", a[i]);
sort(0, max);
printf("\nList after sorting\n");
for(i = 0; i <= max; i++)
printf("%d ", a[i]);
}

If we compile and run the above program, it will produce the following result –

List before sorting


10 14 19 26 27 31 33 35 42 44 0
List after sorting
0 10 14 19 26 27 31 33 35 42 44
WRITE A PROGRAM TO IMPLEMENT MERGE SORT
.
/* program to sort elements of an array using Merge Sort */
#include<stdio.h>
void disp( );
void mergesort(int,int,int);
void msortdiv(int,int);
int a[50],n;
void main( )
{
int i;
clrscr( );
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nBefore Sorting the elements are:");
disp( );
msortdiv(0,n-1);
printf("\nAfter Sorting the elements are:");
disp( );
getch( );
}
void disp( )
{
int i;
for(i=0;i<n;i++)
printf("%d ",a[i]);
}
void mergesort(int low,int mid,int high)
{
int t[50],i,j,k;
i=low;
j=mid+1;
k=low;
while((i<=mid) && (j<=high))
{
if(a[i]>=a[j])
t[k++]=a[j++];
else
t[k++]=a[i++];
}

while(i<=mid)
t[k++]=a[i++];
while(j<=high)
t[k++]=a[j++];
for(i=low;i<=high;i++)
a[i]=t[i];
}

void msortdiv(int low,int high)


{
int mid;
if(low!=high)
{
mid=((low+high)/2);
msortdiv(low,mid);

mergesort(low,mid,high);
}
}
OUTPUT:
How many elements you want to sort ? : 7
Enter elements for an array : 88 45 54 8 32 6 12
After Sorting the elements are : 6 8 12 32 45 54 88

EXPLAIN A SORTING TECHNIQUE WHICH FOLLOWS DIVIDE AND CONQUER


MECHANISM WITH AN EXAMPLE. (QUICK & MERGE SORTS)

Divide and Conquer:- This is a special case of recursion in which given problem is divided into
two or more sub-problems of exactly same type and solution to problem is expressed in terms of
solution to sub-problem. i.e. Dividing the list of elements into two approximately equal parts
recursively and find solution independently then merged together into single list. Quick and
merge sorts are based on Divide and Conquer concept.

The divide and conquer strategy solves a problem by :


1. Breaking into sub problems that are themselves smaller instances of the same type of problem.
2. Recursively solving these sub problems.
3. Appropriately combining their answers.

Two types of sorting algorithms which are based on this divide and conquer algorithm :
1. Quick sort: Quick sort also uses few comparisons (somewhat more than the other two). Like
heap sort it can sort "in place" by moving data in an array.
2. Merge sort: Merge sort is good for data that's too big to have in memory at once, because its
pattern of storage access is very regular. It also uses even fewer comparisons than heap sort,
and is especially suited for data stored as linked lists.

You might also like