【发布时间】:2014-09-30 20:48:56
【问题描述】:
我正在研究一种使用归并排序对数组列表进行排序的方法。我的问题是它不会按照我想要的方式对数组列表进行排序(按单词出现的总次数)。似乎它正在对其进行排序,但是当我调试它时,它会在最后恢复为字母顺序。
编辑:澄清一下:变量“temp”是一个实例变量。这是我们要排序的 ArrayList。
代码:
public void mergeSortFreq(ArrayList<Term> toDo, int first, int mid, int last) {
int first1 = first;
int last1 = mid;
int first2 = mid + 1;
int last2 = last;
int index = first1;
ArrayList<Term> temp = new ArrayList<Term>();
int counter = 0;
while ((first1 <= last1) && (first2 < last2)) {
if (toDo.get(first1).compareTo(toDo.get(first2).getTotalFrequency()) <= 0) {
temp.add(toDo.get(first1));
first1++;
counter++;
} else {
temp.add(toDo.get(first2));
first2++;
}
index++;
}
while (first1 < last1) {
temp.add(toDo.get(first1));
first1++;
index++;
}
while (first2 < last2) {
temp.add(toDo.get(first2));
first2++;
index++;
}
for(index = first; index < temp.size(); ++index){
terms.set(index, temp.get(index));
}
}
public void mergeFreqhelp(ArrayList<Term> toDo, int first, int last) {
int mid = (first + last) / 2;
if (first < last) {
mergeFreqhelp(toDo, first, mid);
mergeFreqhelp(toDo, mid + 1, last);
mergeSortFreq(toDo, first, mid, last);
}
else{
System.out.println("Working???");
}
}
【问题讨论】:
-
在Java中重新实现排序没有意义,内置排序会更快更不容易出错
-
看到这个stackoverflow.com/questions/26125557/sorting-a-time-intervals/…在这个我实现了一个归并排序,忽略B和helperB,这个变量是用来回答这个问题的。
标签: java sorting arraylist camera