使用binarySearch

时间:2015-11-06 22:22:32

标签: java arrays sorting

我只想问为什么我仍然在我的函数sortInOrder(Object x)上得到空指针。

我要做的是使用sortInOrder按升序在data[]数组中插入对象。

public Object[] data = new Object[10];

public static void main(String[] args) {

    for (int i = 0; i < 5; i++)
    {
        int r = (int) (Math.random() * 100);
        System.out.println("Adding " + r);
        sortInOrder(r);

        for (int j = 0; j <= 10; j++)
            System.out.println((Integer) data[j]);
    }

    for (int i = 0; i < 10; i++)
        System.out.println((Integer) data[i]);
}

public static void sortInOrder(Object x) {
    if (x == null)
        throw new IllegalArgumentException();

    int idx = 0;
    if ( data[idx] != null ) 
        idx = Arrays.binarySearch(data, 0, data.length-1, ((Integer) data[idx]).compareTo((Integer) x));

    for ( int i = idx + 1 ; i < data.length - 1 ; i++ )
        data[i] = data[ i - 1 ];

    data[idx] = x;
}

1 个答案:

答案 0 :(得分:0)

我修复了你的代码。请注意,binarySearch方法的返回值为:

“搜索关键字的索引,如果它包含在指定范围内的数组中;否则,( - (插入点) - 1)”(source

import java.util.Arrays;
import java.util.Comparator;

public class Q1 {

    public static Object[] data = new Object[10];

    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {
            int r = (int) (Math.random() * 100);
            System.out.print("Adding: " + r);
            sortInOrder(r);

            System.out.print("[");
            for (int j = 0; j < 10; j++)
                System.out.print(" " + data[j]);
            System.out.println(" ]");
        }

        System.out.print("[");
        for (int i = 0; i < 10; i++)
            System.out.print(" " + data[i]);
        System.out.print(" ]");
    }

    public static void sortInOrder(Integer x) {
        if (x == null)
            throw new IllegalArgumentException();

        int idx = Arrays.binarySearch(data, 0, data.length - 1, x, Comparator.nullsLast((Object o1, Object o2) -> ((Integer) o1) - ((Integer) o2)));

        if (idx < 0) idx = -idx - 1;
        System.out.println(" at index: " + idx);

        // Hint: Use arraycopy instead of for loop for better performance
        System.arraycopy(data, idx, data, idx + 1, data.length - 1 - idx);

        data[idx] = x;
    }

}

或者您可以使用匿名类而不是lambda:

int idx = Arrays.binarySearch(data, 0, data.length - 1, x, 
    Comparator.nullsLast(new Comparator<Object>() {
        @Override
        public int compare(Object o1, Object o2) {
            return ((Integer) o1) - ((Integer) o2);
        }
    }));

结果:

Adding: 2 at index: 0
[ 2 null null null null null null null null null ]
Adding: 29 at index: 1
[ 2 29 null null null null null null null null ]
Adding: 88 at index: 2
[ 2 29 88 null null null null null null null ]
Adding: 9 at index: 1
[ 2 9 29 88 null null null null null null ]
Adding: 27 at index: 2
[ 2 9 27 29 88 null null null null null ]
[ 2 9 27 29 88 null null null null null ]
Process finished with exit code 0