0

I am trying to measure the time it takes for my system to sort an Array of 50 thousand random numbers using Selection sort, however i am getting an error. The error i received is null pointed exception. Would someone look at where i am going wrong here

 import java.util.Random;

 public class SelectionSort {

public static void main(String[] args) {
    int arrayOne[] = null;
    int arr[] = { 9, 1, 8, 5, 7, -1, 6, 0, 2, 2718 };

    int arr1[] = fillArray(arrayOne);

    int sortedArr[] = selectionSort(arr1);
    System.out.println("Selection sort implemented below");
    System.currentTimeMillis();

    long start = System.currentTimeMillis();
    print(sortedArr);
    long elapsed = System.currentTimeMillis() - start;
    System.out.println(elapsed);

}

private static int[] fillArray(int[] array) {
    Random generator2 = new Random(System.currentTimeMillis());

    for (int x = 0; x < 50000; x++) {
        array[x] = generator2.nextInt();
    }
    return array;
}

private static int[] selectionSort(int[] arr) {

    int minIndex, tmp;
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        minIndex = i;
        for (int j = i + 1; j < n; j++)
            if (arr[j] < arr[minIndex])
                minIndex = j;
        if (minIndex != i) {
            tmp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = tmp;
        }
    }
    return arr;

}

private static void print(int[] Array) {
    // TODO prints the array
    for (int i = 0; i < Array.length; i++)
        System.out.print(Array[i] + " ");
    System.out.println();
}
}
4

2 回答 2

0

当您调用 fillArray(arrayOne) 时,您将 null 作为参数传递。然后在 fillArray 方法中,您尝试将值放入空数组。

顺便说一句,如果您在调试器中逐行运行代码,您会在几秒钟内发现这个问题。事实上,即使是抛出的异常也会准确地告诉你哪一行有问题。

于 2013-10-30T23:03:04.940 回答
0

您正在尝试填写以下arrayOne内容null

int arrayOne[] = null;

在尝试填充它之前,您需要使用足够的容量对其进行初始化:

int arrayOne[] = new int[50000];
于 2013-10-30T23:03:06.993 回答