对于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));
}
然而,在我的结果中,我只获得了列表的前半部分。我已经查看了在线合并排序的其他示例,我的代码似乎相似。我究竟做错了什么?非常感谢正确方向的指针。
答案 0 :(得分:1)
您的代码中有拼写错误 -
while(lstaNew.size()>0||lstaNew.size()>0) {
应该是 -
while(lstaNew.size()>0||lstbNew.size()>0) {