Home » Codes » C++ » Advance » Merge Sort in C++

Merge Sort in C++

Sep 18, 2012 by     1    Placed under: Advance, C++, Codes
2
SHARES

a2 Merge Sort in C++ fb share Merge Sort in C++ tweet Merge Sort in C++

c plus plus new Merge Sort in C++

This tutorial is about merge sort in C++.I hope this tutorial is helpful for all of you.

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
// function declaration
void mergesort(int *,int,int);
void merge(int *,int,int,int);
// main
void main()
	 {
	 clrscr();
	 printf("enter no of items\n");
	 int n;
	 cin>>n;
	 int * arr;
	 arr=new int[n];
	 cout<<"enter items to sort"<<endl;
	 int i;
	 for(i=0;i<n;i++)
	 cin>>arr[i];
	 cout<<"before sorting"<<endl;
	 for(i=0;i<n;i++)
	 cout<<arr[i]<<" ";
	 cout<<endl;
	 cout<<"enter lower limit to sort"<<endl;
	 int low;
	 cin>>low;
	 cout<<"enter upper limit to sort"<<endl;
	 int high;
	 cin>>high;
	 mergesort(arr,low,high);                 // function calling
	 cout<<"after sorting"<<endl;
	 for(i=0;i<n;i++)
	 cout<<arr[i]<<" ";
	 cout<<endl;
	 getch();
}
void mergesort(int * arr,int low,int high)     // function body
	 {
	 if(low<high)
		  {
		  int mid;
		  mid=(high+low)/2;
		  mergesort(arr,low,mid);
		  mergesort(arr,mid+1,high);
		  merge(arr,low,mid,high);
	 }
}
void merge(int *arr,int low,int mid,int high)             // function body
{
	 int n1,n2;
	 n1=mid-low+1;
	 n2=high-mid;
	 int *l,*r;
	 l=new int[n1+1];
	 r=new int[n2+1];
	 int i,j,k;
	 j=low;
	 for(i=0;i<n1;i++)
	 l[i]=arr[j++];
	 l[i]=32474;
	 j=mid+1;
	 for(i=0;i<n2;i++)
	 r[i]=arr[j++];
	 r[i]=32147;
	 j=0;
	 k=0;
	 for(i=low;i<=high;i++)
		  {
		  if(l[j]<=r[k])
		  arr[i]=l[j++];
		  else
		  arr[i]=r[k++];
	 }
}
Tagged with:
Loading Disqus Comments ...
Loading Facebook Comments ...

Subscribe to our Newsletter

To subscribe to our newsletter simply add your email below. A confirmation email will be sent to you!