gpt4 book ai didi

java - java中数组列表的合并排序

转载 作者:行者123 更新时间:2023-12-02 07:04:59 24 4
gpt4 key购买 nike

因此,对于家庭作业,我必须编写一个程序,通过使用常规数组的代码对数组列表进行合并排序,我只是想知道是否有人可以帮助我找出哪里出错了,因为我的代码抛出了大量的 NULL指针异常,我尝试修复它们,但是当我修复一个异常时,它会转到另一个......等等......

谢谢!我的代码:

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)

最佳答案

罪魁祸首是:

for(int i=high;i>low;i++){
helper.add((numbers.get(i)));
}

使用 for(int i=high; i>=low; i--) { 代替。

关于java - java中数组列表的合并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16214186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com