我一直在努力寻找问题所在。但每次我运行这个程序时,都会显示:
Exception in thread "main" java.lang.NullPointerException
at MergeSortTest.mergeSort(MergeSortTest.java:8)
有人可以帮我解决这个问题吗?
public class MergeSortTest
{
private static int[] arr;
public static void mergeSort(int[] array)
{
int start = 0;
int end = arr.length - 1;
mergeSort(start, end);
array = arr;
}
public static void mergeSort(int start, int end)
{
if (start == end) {
return;
}
int center = (start + end) / 2;
mergeSort(start, center);
mergeSort(center + 1, end);
merge(start, center + 1, end);
}
public static void merge(int left, int right, int rightEnd)
{
int k = left;
int leftEnd = right-1;
int num = rightEnd - left + 1;
int front[] = new int[leftEnd - left + 1];
int back[] = new int[rightEnd - right + 1];
for (int i = left; i < front.length; i++)
{
front[i] = arr[i];
}
for (int i = right; i < back.length; i++)
{
back[i] = arr[i];
}
int[] temp = new int[num];
while (true)
{
if (front[left] <= back[right])
{
if (left < leftEnd)
{
temp[k] = front[left];
k++;
left++;
}
if (left == leftEnd)
{
temp[k] = front[left];
for (right = right; right < rightEnd + 1; right++)
{
k++;
temp[k] = back[right];
}
break;
}
}
else
{
if (right < rightEnd)
{
temp[k] = back[right];
k++;
right++;
}
if (right == rightEnd)
{
temp[k] = back[left];
for(left = left; left < leftEnd+1; left++)
{
k++;
temp[k] = front[left];
}
break;
}
}
}
}
public static void main(String []args)
{
int[] array = new int[10];
initializeRandom(array);
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println();
mergeSort(array);
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
}
public static void initializeRandom(int[] array)
{
for (int i = 0; i < array.length; i++)
{
array[i] = (int)(Math.random() * 10 + 1);
}
}
}
答案 0 :(得分:0)
您没有使用您作为参数传递的数组,但使用未初始化的数组:
private static int[] arr;
// ...
int end = arr.length - 1;
在main
方法中:
mergeSort(array);
您需要将arr
传递给merge
或重写您的逻辑。