为什么我的合并排序不起作用?

时间:2015-08-15 03:53:13

标签: java mergesort

我尝试使用合并排序。但是,它不断弹出我的ArrayIndexOutOfBoundsException。谁能让我知道为什么?

我完全糊涂了。我错过了什么吗?

public class InversionSearch {
    public int[] mergeSort(int[] array){
        if (array.length == 1) {
            return array;
        }
        int[] first = new int[array.length/2];
        int[] second = new int[array.length - first.length];

        System.arraycopy(array, 0, first, 0, first.length);
        System.arraycopy(array, first.length, second, 0, second.length);

        int[] result = merge(mergeSort(first), mergeSort(second));
        return result;
    }

    public int[] merge(int[] first, int[] second) {
        int i = 0;
        int j = 0;
        int[] temp = new int[first.length + second.length];
        for (int k = 0; k < temp.length; k++) {
            if (first[i] < second[j]) {
                temp[k] = first[i];
                i++;
            }else {
                temp[k] = second[j];
                j++;
            }
        }
        return temp;
    }

    public static void main(String[] args) {
        int[] input = {1, 3, 2, 4, 5, 6};
        InversionSearch iSearch = new InversionSearch();
        iSearch.mergeSort(input);
    }

}

0 个答案:

没有答案