我的mergesort实现中的运行时错误

时间:2010-06-01 09:37:56

标签: java algorithm

我编写了以下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];
    }
}

它不起作用。编译后,出现此错误:

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)

如何解决这个问题?

1 个答案:

答案 0 :(得分:6)

您有两个名为a的数组:

静态,mergesort.a

public static int a[];

和main中的局部变量:

int a[]=new int[]{64,21,33,70,12,85,44,99,36,108};

a中使用merge时,您使用的静态成员从未初始化。
你想初始化mergesort.a,你应该写

a = new int[]{64,21,33,70,12,85,44,99,36,108};

然而,这会使merge变得奇怪,因为它将work = a作为参数,并引用静态mergesort.a,这将是相同的数组。

困惑?我也是...... :)