# merge sort with recursive method (need help badlly!!)

• 01-08-2011, 08:10 PM
zetalore
merge sort with recursive method (need help badlly!!)
I was asked to make programing merge sort with recursive sorting in the specific way my teacher asked(as is shown in the function and comments in the following way )
I tried my outmost best at it, but cannot manage to complete... Can anyone please give some insight into the mistake in my code??

//Implementation of Mergesort
public class MergeSort
{
private int[] helpArray;
private int [] array;

//Constuctor initializes the instance variables
public MergeSort(int[] a)
{
array=a;
helpArray = new int[array.length];

}

//Standard recursive implementation of sort
public void sort(int left, int right)
{
int middle;
int temp;
if (left < right)
{
middle = (left + right) / 2 ;
if(left == (right-1))
{
if(array[left] > array[right])
{
temp = array[right];
array[right] = array[left];
array[left] = temp;
}
}
else if(middle == (right-1))
{
merge(left,middle,right);
}
else
{
sort(left, middle);
sort(middle+1, right);
merge(left, middle, right);
}

// split array in two halves
// sort left part recursively
// sort right part recursively
// merge the two parts together
}
}

//Merge two arrays into one array
private void merge(int left, int middle, int right)
{
// the left sub-array {array[left]..array[mid]} and
// the right sub-array {array[middle+1]..array[right]}
int li = left; // current index left sub-array
int ri = middle + 1; // current index right sub-array
int hi = left; // current index helpArray

while (li <= middle && ri <= right)
{
if(array[li] < array[ri])
{
helpArray[hi] = array[li];
helpArray[hi+1] = array[ri];
System.out.println(helpArray[hi]);
System.out.println(helpArray[hi+1]);
}
else
{
helpArray[hi] = array[ri];
helpArray[hi+1] = array[li];
System.out.println(helpArray[hi]);
System.out.println(helpArray[hi+1]);
}
li++;
ri++;
hi = hi + 2;

// compare current elements of the left sub-array
// with the elements of the right sub-array
// and copy the smaller one to help array
}

//copy remaining elements of left and right part to helpArray

for(int i = 0; i<array.length-1; i++)
{
array[i]= helpArray[i];

}
}
}

//In the main class, the constructor is inicialized with ramdamly created int array. And the first index and the last index is passed to the sort method like this: MergeSort msObj = new MergeSort(intArray);
msObj.sort(0, intArray.length-1);