[英]Recursive mergesort error
我一直在使用排序算法進行練習,並且在合並排序時不斷遇到此錯誤 。 我什至無法滾動查看原始錯誤是什么,因為它在SortTestPractice.mergesort等處顯示,所以我多次達到顯示上限。 關於錯誤可能是什么的任何想法?
這是我有關代碼的代碼
public static ArrayList<String> mergeSort(ArrayList<String> testList)
{
ArrayList<String> left = new ArrayList<String>();
ArrayList<String> right = new ArrayList<String>();
int center;
center = testList.size()/2;
// copy the left half of testList into the left.
for (int i=0; i<center; i++) {
left.add(testList.get(i));
}
//copy the right half of testList into the new arraylist.
for (int i=center; i<testList.size(); i++) {
right.add(testList.get(i));
}
// Sort the left and right halves of the arraylist.
left = mergeSort(left);
right = mergeSort(right);
// Merge the results back together.
merge(left, right, testList);
return testList;
}
它指向我的left = mergeSort(left);
線是left = mergeSort(left);
。 我最初的想法是,它無法識別左和右何時僅包含1個數據,並一直試圖對其進行拆分。 通過添加if else語句,我想出了一個快速解決方案,但仍然遇到相同的錯誤。
這是我的合並功能
private static ArrayList<String> merge(ArrayList<String> left, ArrayList<String> right, ArrayList<String> testList) {
// source: modified from http://www.codexpedia.com/java/java-merge-sort-implementation/
int leftIndex = 0;
int rightIndex = 0;
int testListIndex = 0;
// As long as neither the left nor the right ArrayList has
// been used up, keep taking the smaller of left.get(leftIndex)
// or right.get(rightIndex) and adding it at both.get(bothIndex).
while (leftIndex < left.size() && rightIndex < right.size()) {
if ( (left.get(leftIndex).compareTo(right.get(rightIndex))) < 0) {
testList.set(testListIndex, left.get(leftIndex));
leftIndex++;
} else {
testList.set(testListIndex, right.get(rightIndex));
rightIndex++;
}
testListIndex++;
}
ArrayList<String> rest;
int restIndex;
if (leftIndex >= left.size()) {
// The left ArrayList has been use up...
rest = right;
restIndex = rightIndex;
} else {
// The right ArrayList has been used up...
rest = left;
restIndex = leftIndex;
}
// Copy the rest of whichever ArrayList (left or right) was not used up.
for (int i=restIndex; i<rest.size(); i++) {
testList.set(testListIndex, rest.get(i));
testListIndex++;
}
return testList;
}
public static void hybridSort(ArrayList<String> testList)
{
int temp = 0;
for (int i = 0; i<100; i++)
{
if (testList.get(i).compareTo(testList.get(i+1)) < 0)
{
temp++;
}
}
if (temp >= 90)
{
insertionSort(testList);
}
else
{
mergeSort(testList);
}
}
}
將此添加到mergeSort函數的開頭。 您需要一個基本案例。
if(testList.size() <= 1){ return testList; }
---編輯@rcgldr在我做之前發表了同樣的評論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.