# Merge Sort

**C++ Code To Illustrate Merge-Sort In A Single Array:**

#include<iostream.h>

void merge(int A[],int p, int q, int r)

{

int i,j,k;

int x = q-p+1;

int y = r-q;

int B[20];

int C[20];

B[x] = 10000;

C[y] = 10000;

for (i=0;i<x;i++) B[i] = A[p+i];

for (i=0;i<y;i++) C[i] = A[q+i+1];

i=0;j=0;

for (k=p;k<=r;k++)

{

if (B[i]<=C[j]) A[k] = B[i++];

else A[k] = C[j++];

}

}

void mergesort(int A[], int p,int r)

{

int q;

if (p<r)

{

q = (p+r)/2;

mergesort(A,p,q);

mergesort(A,q+1,r);

merge(A,p,q,r);

}

}

void main()

{

int A[20],n;

cout << “Enter Length Of Array \n” ;

cin >> n;

cout << “Enter Array \n”;

int i;

for (i=0;i<n;i++) cin >> A[i];

mergesort(A,0,n-1);

cout << “Sorted Array \n” ;

for (i=0;i<n;i++) cout << A[i] << ” “;

}

Posted on June 27, 2013, in Algorithms and tagged Merge Sort. Bookmark the permalink. Leave a comment.

## Leave a comment

## Comments 0