Merge Sort

The Code Vault

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] << ” “;
}

View original post

Advertisements

About Khuram Ali

Programming... Programming and Programming...!!!

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: