Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Merge Sort Algorithm

843785Mar 12 2009 — edited Mar 13 2009
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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 10 2009
Added on Mar 12 2009
9 comments
456 views