我正在嘗試用 Java 編寫一個通用的合并排序方法。這是我的源代碼:import java.util.ArrayList;import java.util.List;/** * An implementation of MergeSort * * @param <T> the type of data held by the array. */public class MergeSort<T extends Comparable<? super T>> implements ArraySort<T>{ /** * Sort the array using a MergeSort. * * (recursively breaks down the array into sub arrays until arrays of size 1 are reached.) * (then works backwards merging these arrays back into each other until a sorted array state is reached containing * all the elements of the initial unsorted array, but now sorted). * * @param array the array to be sorted. * @return array (sorted) */ @Override public T[] sort(T[] array) { //If the array being sorted is less than 2 elements, it is already sorted and cannot be split into two separate // arrays, so return the initial array to prevent an exception. if(array.length < 2) { return array; } //Create two sub arrays from the initial array passed in. T[] temp1 = copy(array, 0, (array.length/2) - 1); T[] temp2 = copy(array, (array.length/2), array.length - 1); //Sort these two arrays. sort(temp1); sort(temp2); //Merge the two subarrays back into the initial array. merge(array, temp1, temp2); //return the now sorted array. return array; }我不知道為什么,但是當我調用第 38 行和第 42 行時出現 StackOverflow 錯誤。38 = T[] temp1 = copy(...) in the sort() method42 = sort(temp1) in the sort() method.這讓我相信錯誤出在復制功能的某個地方,但我不知道如何解決問題或找到解決方案。有人可以幫我解決這個通用合并排序的實現嗎?StackTrace 用于對 12 個元素的數組進行排序。https://docs.google.com/document/d/1Ig5p7TZF_eX0Q_rroORnZUWnXtep7x-7cmDiSAZWlj8/edit?usp=sharing
2 回答

森欄
TA貢獻1810條經驗 獲得超5個贊
你的數組復制是錯誤的。
利用:
private <T> T[] copy(T[] list, int from, int to) {
return Arrays.copyOfRange(list, from, to);
}
您的代碼中有更多錯誤(merge不處理不同長度的數組),但這應該可以解決您的問題。
見List.toArray(T[])
...如果列表適合指定的數組,則在其中返回。
即您正在復制到原始數組中,而不是創建一個新數組,因此您的數組實際上永遠不會減小大小。

慕妹3146593
TA貢獻1820條經驗 獲得超9個贊
您的條件不夠好,您會在數組上獲得無限排序調用。
至少您應該包含大小等于 2 的數組:
if(array.length <= 2)
此外,您的復制方法必須改進。
無論如何,請復制/粘貼您的完整堆棧跟蹤。
添加回答
舉報
0/150
提交
取消