嘿,我正在合併排序方法,不斷收到一個索引越界的錯誤。我無法弄清楚爲什麼或在哪裏發生。我試過打印索引並查看遞歸中是否有錯誤,但我認爲它不是非常簡單的。合併排序索引越界java
public ArrayList<String> mergeSort(ArrayList<String> words,int first, int last){
if (first < last){
int mid = (first+ last)/2;
mergeSort(words,first,mid);
mergeSort(words,mid+1,last);
merge(words, first, mid, last);
}
return words;
}
public ArrayList<String> merge(ArrayList<String> words, int first, int mid, int last){
int first1 = first;
int last1 = mid;
int first2 = mid+1;
int last2 = last;
int total = first1;
ArrayList<String> temp = new ArrayList<String>();
while ((first1<=last) && (first2 <= last2)){
if (words.get(first1).compareTo(words.get(first2))<=0){
temp.add(total,words.get(first1));
first1++;
}
else{
temp.add(total,words.get(first2));
first2++;
}
total++;
}
while(first1 <= words.size()){
temp.add(total,words.get(first1));// exception occurs here
first1++;
total++;
}
while (first2 <= last2){
temp.add(total,words.get(first2));
first2++;
total++;
}
for (total = first; total <= last; ++total){
words.set(total,temp.get(total));
}
System.out.println(words);
return words;
}
爲什麼不你看看例外嗎?它告訴你在哪裏... – Alboz 2014-09-30 16:01:47
請標記一條線,發生錯誤 – talex 2014-09-30 16:01:50
它告訴我線50 – user3400512 2014-09-30 16:04:52