对于CS作业,我试图使用合并排序方法对ArrayList进行排序。这是我的代码:
public static LinkedList<Object> merge (LinkedList<Object> lsta, LinkedList<Object> lstb) {
LinkedList<Object> result = new LinkedList<Object>();
LinkedList<Object> lstaNew = (LinkedList<Object>) lsta.clone();
LinkedList<Object> lstbNew = (LinkedList<Object>) lstb.clone();
while(lstaNew.size()>0||lstaNew.size()>0) {
if(lstaNew.size()>0&&lstbNew.size()>0) {
if( ((Comparable) lstaNew.getFirst()).compareTo(lstbNew.getFirst()) < 0 ) {
result.add(lstaNew.getFirst());
lstaNew.remove();
}
else {
result.add(lstbNew.getFirst());
lstbNew.remove();
}
}
else if(lstaNew.size()>0) {
result.add(lstaNew.getFirst());
lstaNew.remove();
}
else {
result.add(lstbNew.getFirst());
lstbNew.remove();
}
}
return result;
}
public static LinkedList<Object> sort (LinkedList<Object> lst) {
if (lst.size() <= 1) return lst;
LinkedList<Object> left = new LinkedList<Object>();
LinkedList<Object> right = new LinkedList<Object>();
int midpoint = lst.size()/2;
for (int i=0;i<midpoint;i++) left.add(lst.get(i));
for (int i=midpoint;i<lst.size();i++) right.add(lst.get(i));
return merge(sort(left),sort(right));
}
但是,在我的结果中,我只获得列表的前半部分。我看了其他在线合并排序的例子,我的代码似乎很相似。我究竟做错了什么?朝着正确方向的指针将不胜感激。
最佳答案
您的代码中有错字-
while(lstaNew.size()>0||lstaNew.size()>0) {
本来应该 -
while(lstaNew.size()>0||lstbNew.size()>0) {
关于java - 递归mergesort仅返回ArrayList的前一半,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26291941/