//Program to sort an array using merge sort.
#include<iostream.h>
#include<conio.h>
void merge(int a[],int,int);
void merge_sort(int a[],int ,int,int);
void main()
{
clrscr();
int A[10],N,i;
cout<<"\nEnter number of elements in array : ";
cin>>N;
cout<<"\nElements are : ";
for(i=0;i<N;i++)
{
cin>>A[i];
}
merge(A,0,N-1);
cout<<"\nSorted array is : ";
for(i=0;i<N;i++)
{
cout<<" "<<A[i];
}
getch();
}
void merge(int a[10],int beg,int end)
{
int mid=(beg+end)/2;
if(beg<end)
{
merge(a,beg,mid);
merge(a,mid+1,end);
merge_sort(a,beg,mid,end);
}
}
void merge_sort(int a[10],int beg,int mid,int end)
{
int i=beg,j=mid+1,k=beg,temp[10];
while(i<=mid&&j<=end)
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
if(i>mid)
{
while(j<=end)
temp[k++]=a[j++];
}
else
{
while(i<=mid)
temp[k++]=a[i++];
}
for(int s=beg;s<k;s++)
a[s]=temp[s];
}
Output:
#include<iostream.h>
#include<conio.h>
void merge(int a[],int,int);
void merge_sort(int a[],int ,int,int);
void main()
{
clrscr();
int A[10],N,i;
cout<<"\nEnter number of elements in array : ";
cin>>N;
cout<<"\nElements are : ";
for(i=0;i<N;i++)
{
cin>>A[i];
}
merge(A,0,N-1);
cout<<"\nSorted array is : ";
for(i=0;i<N;i++)
{
cout<<" "<<A[i];
}
getch();
}
void merge(int a[10],int beg,int end)
{
int mid=(beg+end)/2;
if(beg<end)
{
merge(a,beg,mid);
merge(a,mid+1,end);
merge_sort(a,beg,mid,end);
}
}
void merge_sort(int a[10],int beg,int mid,int end)
{
int i=beg,j=mid+1,k=beg,temp[10];
while(i<=mid&&j<=end)
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
if(i>mid)
{
while(j<=end)
temp[k++]=a[j++];
}
else
{
while(i<=mid)
temp[k++]=a[i++];
}
for(int s=beg;s<k;s++)
a[s]=temp[s];
}
Output:
No comments:
Post a Comment