[英]Merge Sort Implementation Issues
I'm attempting to implement a merge sort in Java for my Algorithms class. 我正在尝试为我的Algorithms类在Java中实现合并排序。 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. 我尝试了几种方法,包括使用Java转换为整数的Double.POSITIVE_INFINITY值将两个数组中的最后一个数组索引分配为“无穷大”。
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). 在调用Arrays.copyOfRange(arr,p,q)
,范围从p(包括)扩展到q(不包括)。
If p and q are equal, the result will be a zero-length array. 如果p和q相等,则结果将为零长度数组。
In your own method signatures, consider and document whether the endpoint r
is inclusive or exclusive. 在您自己的方法签名中,考虑并记录端点r
是包含的还是排除的。
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. 另外,请考虑当您的测试if(p<r)
在mergesort( if(p<r)
失败时会发生什么—您返回一个新的1元素数组而不更改其默认成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.