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!

Bottom Up Merge Sort

802508Oct 1 2010 — edited Oct 2 2010
I am trying to implement merge sort in an iterative manner. I keep receiving an index out of bounds error, but I cannot tell what is causing it. Can anyone help point out where this is happening? My code is below. The variable count is there simply to keep track of the number of comparisons made. Sorry about it not being in code format. I am unsure how to do it in this forum.

public class ArraySort {
private static long[] a;
private int nElems;// number of data items
private static int count = 0;

public ArraySort(int max)
{
a = new long[max];
nElems = 0;
}


public static void merge(long [] arr, long[] temp, int left, int middle, int right){
for(int i = left; i < middle; i++){
temp[i] = arr;
}
for(int k = middle; k < right; k++){
temp[k] = arr[middle + right - k - 1];
}
int i = left;
int j = right - 1;
for(int n = 1; n < right; n++){
count++;
if(temp[j] < temp[i]){ *****This is the line that throws the exception********
arr[n] = temp[j--];
}
else{
arr[n] = arr[i++];
}
}
}

public static void mergesort(long[] arr){
long[] temp = new long[arr.length];
for(int i = 1; i < arr.length; i = i + i){
for(int k = 0; k < arr.length - i; k+= i + i){
merge(arr, temp, k, k + i, Math.min(k + i + i, arr.length));
}
}
}

public int mergesort(){
mergesort(this.a);
return count;
}

Edited by: 799505 on Oct 1, 2010 6:34 PM

Edited by: 799505 on Oct 1, 2010 7:15 PM

Edited by: 799505 on Oct 1, 2010 7:39 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 30 2010
Added on Oct 1 2010
2 comments
366 views