问题在于使用递归和合并排序进行排序。
我没有看到任何错误,但cmd弹出空指针异常。
import java.util.*;
public class listMethodRunner
{
public static void main(String [] args)
{
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(2);
list1.add(3);
list1.add(5);
list1.add(9);
list1.add(22);
list1.add(38);
list1.add(56);
ArrayList<Integer> list2 = new ArrayList<Integer> ();
list2.add(4);
list2.add(7);
list2.add(8);
list2.add(23);
list2.add(37);
ArrayList<Integer> mergeList = ListMethods.merge(list1,list2);
if (mergeList.size() == 0)
{
System.out.println("This list is empty");
}
else
{
for(Integer m: mergeList)
{
System.out.println(m);
}
}
} // main
} // class listMethodRunner
import java.util.*;
public class ListMethods
{
public static ArrayList<Integer> merge(ArrayList<Integer> list1,ArrayList<Integer> list2)
{
ArrayList<Integer> merge = new ArrayList<Integer>();
if (list1.size() == 0 || list2.size() == 0)
{
merge = new ArrayList<Integer>();
}
else if (list1.get(0) <= list2.get(0))
{
list1.remove(0);
merge = merge(list1,list2);
Integer temp = list1.remove(0);
merge.add(temp);
}
else if (list1.get(0) >= list2.get(0))
{
list2.remove(0);
Integer temp = list2.remove(0);
merge = merge(list1,list2);
merge.add(temp);
}
return merge;
} // merge
} // class ListMethods
答案 0 :(得分:0)
merge
方法似乎未正确实施。以下版本基于API docs,但未经测试:
public static ArrayList<Integer> merge(ArrayList<Integer> list1,ArrayList<Integer> list2)
{
if (list1.size() == 0) {
merge = list2; // ... an empty first list means to return the second one
else if (list2.size() == 0) {
merge = list1; // ... an empty second list means to return the first one
}
else {
ArrayList<Integer> merge = new ArrayList<Integer>();
Integer temp;
if (list1.get(0) <= list2.get(0))
{
temp = list1.remove(0);
}
else if (list1.get(0) >= list2.get(0))
{
temp = list2.remove(0);
}
merge.add(0, temp); // the smallest element of them all comes first ...
merge.addAll ( merge(list1,list2) ); // ... followed by the sorted merge of both lists without the smallest element just added
}
return merge;
} // merge