merge sort

the code isn't sorting elements and just printing the unsorted elements ?





#include <iostream>
#include<math.h>
#include<string>


using namespace std;

int p;
int q;
int r;
int x;


void merge(int *A,int l,int m,int h)
{ int n1;
int n2;
int i;
int j;
int k ;
int L[10] ;
int R[10];

n1= m-l+1 ; // size of elements ..
n2= h-m ; // h-(m-1)+1 -> h-m ..

for( i=0;i<n1;i++)
L[i]=A[l+i];
for (j=0;j<n2;j++)
R[j]=A[m+j+1];

L[i]=10000;
R[i]=10000; // represents the infinity ..

i=0 ;
j=0;

for(k=1;k<=h;k++)
{
if(L[i]<R[j])
{A[k]=L[i];
i++; }
else
A[k]=R[j++];

}

return ;

}

void merge_sort(int *A,int p ,int r )
{
if(p<r)
{ q= floor ( (p+q)/2 );

merge_sort(A,p,q);
merge_sort(A,q+1,r);
merge(A,p,q,r);
}

return;
}



int main() {

int A[8]={5,6,4,8,1,2,7,9};
x=8;
p=0;
r=x-1;


cout<<"Array A[] elements before sorting ";

for(int i=0;i<x;i++)
{
cout<<endl<< A[i];
}

merge_sort(A,0,7);

for(int i=0;i<x;i++)
{
cout<<A[i]<<endl;
}




return 0;
}

Function merge_sort() calls itself recursively until the program runs out of stack space and it crashes.

Try changing
 
    q = floor( (p+q)/2 );
to
 
    q = (p+r) / 2;


That won't necessarily solve everything, but it may be a start.

A general hint. If you use meaningful names for variables, such as start, finish, middle, or first, last etc. such mistakes are easier to spot. Code with lots of single-letter variable names is virtually unreadable.

One more thing.

Don't use global variables such as
1
2
3
4
int p;
int q;
int r;
int x;

It means your functions are not self-contained, instead their inner workings are leaking out for the rest of the world to see, like a wounded animal with its guts spilling out.
Last edited on
Topic archived. No new replies allowed.