Saturday 1 October 2011

Source code of Merge Sort


/***************************************************************/
/******************** MERGE ** SORT    *************************/
/***************************************************************/


#include <iostream>
#include <conio.h>
#include <malloc.h>
#define INF 2000


void Merge(int [],int ,int ,int);
void Merge_sort(int [], int, int);


int main()
{
int A[10];
int p = 0, n;
cout << "Enter the no of elements: ";
cin >> n;
cout << "Enter the elements:\n";
for(int i=0; i <n; i++)
{
cin >> A[i];
}
Merge_sort(A,p,n);               //calling of Merge sort function
cout << "The sorted array is : ";
for(int i=0; i <n; i++)
{
cout << A[i] << " ";
}
getch();
return 0;
}


void Merge_sort(int A[],int p, int r)
{
int q;
if(p < r)
{
q = ((p+r)/2);
Merge_sort(A, p, q);
Merge_sort(A, q+1, r);
Merge(A,p,q,r);
}
}


void Merge(int A[], int p, int q, int r)
{
int n1 = (q-p+1), n2 = (r-q);
int L[10];
int R[10];
for(int i = 1; i <= n1; i++)
L[i] = A[p+i-1];
for(int j = 1; j <= n2; j++)
R[j] = A[q+j];
L[n1 + 1] = INF;
R[n2 + 1] = INF;
int i = 1;
int j = 1;
for(int k = p; k <= r; k++)
{
if(L[i] <= R[j])
{
A[k] = L[i];
i = i + 1;
}
else
{
A[k] = R[j];
j = j + 1;
}
}
}

No comments:

Post a Comment