i am trying out merge sort.
i have made two functions sort and merge;
i am calling merge recursively.
i think my sort function is working fine. the problem lies with merge function.
in merge function i am dividing the array using recursive calls. it ends when lb = = ub(ie lower bound equals upper bound). lower bound and upper bound are index of array.

then i am passing it to sort function function.

suggest me a solution of correction to merge sort.

#include<iostream>
//#include<stream>

using namespace std;

int A[7] = {3,4,77,10,2,5,7}; 

void sort(int l1,int u1,int l2,int u2)
{
	int B[7];
	int i=l1;
	int j=l2;
	int k=0;

	while(i<=u1&&j<=u2)	{
		if(A[i]<A[j])	{
	       		B[k] = A[i];
			i++;
			k++;
		}

		else	{
			B[k] = A[j];
			j++;
			k++;
		}
	}


	while(j<=u2)	{
		B[k]=A[j];
		j++;
		k++;
	}

	while(i<=u1)	{	
		B[k] = A[i];
		i++;
		k++;
	}

	for(i=l1;i<=u2;i++){
		A[i]=B[i];
	}
}


				


void merge(int lb,int ub)
{
	int lo;
	lo=(ub+lb)/2;
	
	if(lb<ub){
	merge(lb,lo);
	merge(lo+1,ub);
	sort(lb,lo,lo+1,ub);
	}
}


int main()
{
for(int i=0;i<7;i++)
	cout<<A[i]<<" ";
cout<<endl;

merge(0,6);
//sort(0,3,4,6);
for(int i=0; i<7;i++)
       cout<<A[i]<<" ";

return 0;
}

I don't think it is your merge function but the sort function.
You're starting to fill in B in the beginning but you have to start at l1.
So the inititial value for k has to be l1, not zero.

This article has been dead for over six months. Start a new discussion instead.