merge sort issue

Hello, first time doing this. Here goes....
I'm practicing my merge sorting and i'm running to the issue of getting the first three correctly on to the array but then it bugs out on me. please help!

#include <iostream>
using namespace std;
void mergesort (int a[], int aux[],int lo, int hi);
void msort (int a[], int aux[],int lo, int hi);
void printout(int a[]);

int main()
{
int a[8]= {2,3,1,4,5,7,8,6};
int aux[8];
msort(a,aux,0,7);
printout(a);

}
void msort(int a[],int aux[],int lo,int hi)
{
int mid = lo +((hi-lo)/2);
if (lo >= hi)
return;
msort(a,aux,lo,mid);
msort(a,aux,mid+1,hi);
mergesort(a,aux,lo,hi);
}
void mergesort(int a[],int aux[],int lo,int hi)
{
int i = lo;
int j = (lo+((hi-lo)/2))+1;
int mid = lo + ((hi-lo)/2);

for (int k=lo;k<=hi;k++)
{
aux[k]=a[k];
}
for(int k=lo;k<=hi;k++)
{
if(aux[i]<aux[j])
{
a[k]=aux[i];
i++;
}
else if (aux[j]<=aux[i])
{
a[k]=aux[j];
j++;
}
else if (aux[i]>=mid)
{
a[k]=aux[j];
j++;
}
else if (aux[j]>=hi)
{
a[k]=aux[i];
i++;
}
}
}
void printout(int a[])
{
for(int m =0;m<8;m++)
{
cout<<a[m];
}
}
Please use [code] tags.

Remember, there are two parts to a merge sort.

(1) divide -- split your data into two parts and recurse over them
(2) merge -- join the two parts

Your naming has confused you a little. In order to do it, you have named the main mergesort "msort" and the merge part "mergesort".

It might help you to rename "mergesort" to "merge" and then "msort" to "mergesort".

In the merge part, your first loop is correct -- you copy a[] to aux[]. After that you mess up.

Remember that you are merging aux[lo..mid-1] with aux[mid..hi], placing the results in a[k++], where k starts at lo.

You might want to take a look at the FAQ to read about the merge algorithm:
http://www.cplusplus.com/faq/sequences/sequencing/sort-algorithms/mergesort/#algorithm

Specifically, given (lo, mid, hi), you also need to have
k --> index into a[] where next element goes
m --> index into aux[] from lo to mid-1
n --> index into aux[] from mid to hi-1

While m < mid and n < hi:
put smallest of aux[m],aux[n] into a[k]
increment k, and whichever of m,n is correct
Copy any remaining elements of aux[m..mid-1] or aux[n..hi-1] to a[k..hi-1].

Hope this helps.
Topic archived. No new replies allowed.