Program for Merge sort


#include<iostream>
#include<iomanip>
using namespace std;
void divide(int [],int ,int);
void merge(int [],int,int,int);
int main()
{
 int i,j,k,temp,n;
 cout<<"\nenter the no of integers : ";
 cin>>n;

 int a[n];
 cout<<"\nenter the integers : ";

 for(i=0;i<n;i++)
 {
  cin>>a[i];
 }

 cout<<"\narray before sorting : ";


 for(i=0;i<n;i++)
 {
  cout<<a[i]<<" ";
 }
 cout<<"\n";

 divide(a,0,n-1);

 cout<<"\nafter sorting : ";

 for(i=0;i<n;i++)
 {
  cout<<a[i]<<" ";
 }
 cout<<"\n";

 return 0;
}

void divide(int a[],int min ,int max)
{
 int mid;
 if(min<max)
 {
  mid=(max+min)/2;
  divide(a,min,mid);
  divide(a,(mid+1),max);
  merge(a,min,mid,max);
 }
}

void merge(int a[],int min,int mid,int max)
{
 int temp[max],i,j,k,l,m;
 j=min;
 m=mid+1;
 for(i=min;(j<=mid && m<=max);i++)
 {
  if(a[j]<=a[m])
  {
   temp[i]=a[j];
   j++;
  }
  else
  {
   temp[i]=a[m];
   m++;
  }
 }
 if(j>mid)
 {
  for(k=m;k<=max;k++)
  {
   temp[i]=a[k];
   i++;
  }
 }
 else
 {
  for(k=j;k<=mid;k++)
  {
   temp[i]=a[k];
   i++;
  }
 }
 for(k=min;k<=max;k++)
 {
  a[k]=temp[k];
 }
}