Merge Sorting Program In C++

#include<iostream.h>
#include<conio.h>
void display(int *A,int s){
cout<<"\n";
for(int i=0;i<=s;i++){
cout<<A[i]<<"  ";
}}
void merge(int *A,int p,int q,int r)
{
int n1=q-p+1;
int n2=r-q;
int *L=new int[n1];
int *R=new int[n2];
{
for(int i=0;i<=n1;i++){
R[i]=A[p+i-1];
}

for(int j=0;j<=n2;j++){
R[j]=A[q+j];
}  }
int i=1,j=1;
for(int k=p;k<=r;k++){
if(L[i]<=R[j])
{
A[k]=L[i];
i++;
}
else{
A[k]=R[j];
j++;
}
}
}
void merge_sort(int *A,int p,int r)
{
if(p<r){
int q=((p+r)/2);
merge_sort(A,p,q);
merge_sort(A,q+1,r);
merge(A,p,q,r);
}
}
void main()
{
clrscr();
int A[]={5,4,8,7,9,1,6,3};
merge_sort(A,0,7);
display(A,7);
getch();
}

No comments

Powered by Blogger.