I'm attempting to implement a merge sort in Java for my Algorithms class. I've tried several approaches, including assigning the last array indices in both arrays as "infinity" using Java's Double.POSITIVE_INFINITY value typecasted as an integer.
import java.util.Arrays;
public static int[] mergeSort(int[] arr, int p, int r){
int[] sortedArray = new int[1];
if(p<r){
int q = (int)Math.floor((p+r)/2);
mergeSort(arr,p,q);
mergeSort(arr,q+1,r);
sortedArray = merge(arr,p,q,r);
}
return sortedArray;
}
public static int[] merge(int[] arr, int p, int q, int r){
//I've tested here with an array of size two, and left returns an array
//length of zero. I'm not sure if it might have to do with how the base case
//of size 1 arrays is handled.
int[] left = Arrays.copyOfRange(arr,p,q);
int[] right = Arrays.copyOfRange(arr,q+1,r);
int i = 0, j = 0;
int k;
//merge the two arrays; check to see if the i or j indexes are out of range
//before attempting to merge
for(k = p; k <= r-1 && i < left.length && j < right.length; k++){
if(left[i] <= right[j]){
arr[k] = left[i];
i++;
}else{
arr[k] = right[j];
j++;
}
}
//I was handling these assignments in the loop above, but my index variables were going
//out of range when Arrays.copyOfRange() returned arrays of length 0.
if(i >= left.length && j < right.length){
while(j < right.length){
arr[k] = right[j];
j++;
}
}else if(j >= right.length && i < left.length){
while(i < left.length){
arr[k] = left[i];
i++;
}
}
return arr;
}
I'm thinking my issue is just a couple of index values that are off by a bit, but I can't figure out where they would be for the life of me.
In your call Arrays.copyOfRange(arr,p,q)
, the range extends from p (inclusive) to q (exclusive).
If p and q are equal, the result will be a zero-length array.
In your own method signatures, consider and document whether the endpoint r
is inclusive or exclusive.
Also, consider what happens when your test if(p<r)
fails in mergesort() -- you return an new 1-element array without changing its members from the default.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.