因此,对于家庭作业,我必须编写一个程序,将与常规数组一起使用的代码中的数组列表合并排序,我只是想知道是否有人可以帮助我找出我出错的地方,因为我的代码抛出了大量的 NULL POINTER 异常,我试图修复它们,但是当我修复一个时,它会转到另一个......等等......
谢谢!我的代码:
private static ArrayList<Integer> numbers= new ArrayList<Integer>();
private static ArrayList<Integer> helper;
private static int number;
public static void sort(ArrayList<Integer> myNumbers){
for(int i=0; i<myNumbers.size();i++){
numbers.add(myNumbers.get(i));
}
//numbers=myNumbers;
number = myNumbers.size()-1;
mergesort(0, number -1);
}
private static void mergesort(int low, int high){
//check if low is smaller than high, if not then the array is sorted
if(low<high){
//get the index of the element which is in the middle
int middle=low+(high-low)/2;
//sort the left side of the array
mergesort(low, middle);
//sort the right side of the array
mergesort(middle +1, high);
//combine them both
merge(low, middle, high);
}
}
private static void merge(int low, int middle, int high){
//copy both parts into the helper array
for(int i=high;i>low;i++){
helper.add((numbers.get(i)));
}
int i=low;
int j=middle+1;
int k=low;
//copy the smallest myNumbers from either the left or right side back to the original array
while(i<middle && j<high){
if(helper.get(i)< helper.get(j)){
numbers.set(k,(helper.get(i)));
i++;
}
else{
numbers.set(k,(helper.get(j)));
j++;
}
k++;
}
//copy the rest of the left side of the array into target array
while(i<middle){
numbers.set(k,helper.get(i));
k++;
i++;
}
}
回报:
Exception in thread "main" java.lang.NullPointerException
at BinarySearch.merge(BinarySearch.java:61)
at BinarySearch.mergesort(BinarySearch.java:55)
at BinarySearch.mergesort(BinarySearch.java:51)
at BinarySearch.mergesort(BinarySearch.java:51)
at BinarySearch.mergesort(BinarySearch.java:51)
at BinarySearch.mergesort(BinarySearch.java:51)
at BinarySearch.mergesort(BinarySearch.java:51)
at BinarySearch.mergesort(BinarySearch.java:51)
at BinarySearch.sort(BinarySearch.java:43)
at BinarySearch.main(BinarySearch.java:25)