Hi, i'm trying to write merge sort methods but I have 2 problems, here's the mergesort method, and then the merge method below where I have some problems:
public static void mergesort(int[] array, int first, int last)
{
if (last-first > 1)
{
int mid = (first + last)/2;
mergesort(array, first, mid); //recursive call 1
mergesort(array, mid, last); //recusive call 2
merge(array, first, mid, last);
}
}
public static void merge(int[] array, int first, int mid, int last) {
//merge array[first to mid-1] and array[mid to last-1]
int leftpos = first;
int rightpos = mid;
int newpos = 0;
int[] temparray = new int[x];//<------- What should the size of x be?
while(leftpos<mid && rightpos<=(last-1)) {
if (array[leftpos] <= array[rightpos]) {
temparray[newpos] = array[leftpos];
leftpos++; newpos++;
}
else {
temparray[newpos] = array[rightpos];
rightpos++; newpos++;
}
while(leftpos<mid){ //copy the rest of left half
temparray[newpos] = array[leftpos];
leftpos++; newpos++;
}
while(rightpos<=last-1) { //copy the rest of right half (
temparray[newpos] = array[rightpos];
rightpos++; newpos++;
}
// copy temparray to array[first to (last-1)] <---- how do I do this?
}
}
Any help?
Thank you.