[英]Merge Sort Implementation Issues
我正在嘗試為我的Algorithms類在Java中實現合並排序。 我嘗試了幾種方法,包括使用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;
}
我以為我的問題只是幾個稍微偏離的索引值,但我無法弄清楚它們在我的一生中的位置。
在調用Arrays.copyOfRange(arr,p,q)
,范圍從p(包括)擴展到q(不包括)。
如果p和q相等,則結果將為零長度數組。
在您自己的方法簽名中,考慮並記錄端點r
是包含的還是排除的。
另外,請考慮當您的測試if(p<r)
在mergesort( if(p<r)
失敗時會發生什么—您返回一個新的1元素數組而不更改其默認成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.