[英]Runtime error in my mergesort implementation
I have written the following mergesort code. 我写了下面的mergesort代码。
public class mergesort {
public static int a[];
public static void merges (int work[], int low, int high) {
if (low==high)
return;
else {
int mid = (low+high)/2;
merges(work,low,mid);
merges(work,mid+1,high);
merge(work,low,mid+1,high);
}
}
public static void main (String[] args) {
int a[] = new int[] {64, 21, 33, 70, 12, 85, 44, 99, 36, 108};
merges(a,0,a.length-1);
for (int i=0; i<a.length; i++) {
System.out.println(a[i]);
}
}
public static void merge (int work[], int low, int high, int upper) {
int j = 0;
int l = low;
int mid = high-1;
int n = upper-l+1;
while (low<=mid && high<=upper)
if (a[low] < a[high])
work[j++] = a[low++];
else
work[j++] = a[high++];
while (low <= mid)
work[j++]=a[low++];
while (high <= upper)
work[j++] = a[high++];
for (j=0;j<n;j++)
a[l+j]=work[j];
}
}
It does not work. 这是行不通的。 After compilation, there is this error: 编译后,出现此错误:
java.lang.NullPointerException
at mergesort.merge(mergesort.java:45)
at mergesort.merges(mergesort.java:12)
at mergesort.merges(mergesort.java:10)
at mergesort.merges(mergesort.java:10)
at mergesort.merges(mergesort.java:10)
at mergesort.main(mergesort.java:27)
How can this problem be fixed? 如何解决此问题?
You have two arrays called a
: 您有两个称为a
数组:
a static, mergesort.a
: 静态的mergesort.a
:
public static int a[];
and a local variable in main: 和main中的局部变量:
int a[]=new int[]{64,21,33,70,12,85,44,99,36,108};
When you use a
in merge
, you use the static member, which was never initialized. 当您使用a
在merge
,使用静态成员,这是从来没有初始化。
It you wanted to initialize mergesort.a
, you should have written 您要初始化mergesort.a
,应该已经编写了
a = new int[]{64,21,33,70,12,85,44,99,36,108};
However, that would make merge
weird, since it will have work = a
as an argument, and reference to the static mergesort.a
, which would then be the same array. 但是,这会使merge
变得很奇怪,因为它将有work = a
作为参数,并引用了静态mergesort.a
,该静态mergesort.a
之后将是同一数组。
Confused? 困惑? So am I... :)
我也是... :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.