C++ rogram to implement merge sort

Share on FacebookTweet about this on TwitterDigg thisPin on PinterestShare on LinkedInShare on StumbleUponShare on TumblrShare on Google+Email this to someone
#include <iostream.h>
const int MAX = 5 ;
class array
{
	private :
		int *a ;
		int size ;
		int count ;
	public :
		array( ) ;
		array ( int sz ) ;
		void add ( int num ) ;
		void display( ) ;
		void merge_sort(int low,int high);
		void merge(int low,int mid,int high);
		~array( ) ;
} ;
array :: array( )
{
	count = size = 0 ;
	a = NULL ;
}
array :: array( int sz )
{
	count = 0 ;
	size = sz ;
	a = new int[sz] ;
}
void array :: add ( int num )
{
	if ( count < size )
	{
		a[count] = num ;
		count++ ;
	}
	else
		cout << "\nArray is full" << endl ;
}
void array :: display( )
{
	for ( int i = 0 ; i < count ; i++ )
		cout << a[i] << "\t" ;
	cout << endl ;
}
void array :: merge_sort(int low,int high)
{
 
	int mid;
	if(low<high)
	{
		mid=(low+high)/2;
		merge_sort(low,mid);
		merge_sort(mid+1,high);
		merge(low,mid,high);
	}
}
void array :: merge(int low,int mid,int high)
{
	int h,i,j,b[50],k;
	h=low;
	i=low;
	j=mid+1;
 
	while((h<=mid)&&(j<=high))
	{
		if(a[h]<=a[j])
		{
			b[i]=a[h];
			h++;
		}
		else
		{
			b[i]=a[j];
			j++;
		}
		i++;
	}
	if(h>mid)
	{
		for(k=j;k<=high;k++)
		{
			b[i]=a[k];
			i++;
		}
	}
	else
	{
		for(k=h;k<=mid;k++)
		{
			b[i]=a[k];
			i++;
		}
	}
	for(k=low;k<=high;k++) a[k]=b[k];
}
array :: ~array( )
{
	delete a ;
}
 
void main( )
{
	array a ( MAX ) ;
 
	a.add ( 11 ) ;
	a.add ( 2 ) ;
	a.add ( 9 ) ;
	a.add ( 13 ) ;
	a.add ( 57 ) ;
 
	cout << "\nMerge sort.\n" ;
 
	a.merge_sort (0,4) ;
 
	cout << "\nArray after sorting: " << endl ;
	a.display( ) ;
}

Share on FacebookTweet about this on TwitterDigg thisPin on PinterestShare on LinkedInShare on StumbleUponShare on TumblrShare on Google+Email this to someone

2 Responses to “C++ rogram to implement merge sort”

  1. plzz tll the output of above program as i ‘ve to complete my prac fyl by 2morro……………………………………….

    Reply

Leave a Reply