这个合并排序实现有什么问题

时间:2013-04-13 15:45:13

标签: java

在下面的代码中,merge()函数只被调用两次然后进入一些无限循环。

package Prac;


public class MergeSort {

    private static int[] arr = {12, 10, 5, 2, 7, 56, 81, 17, 14, 1 };
    private static int[] helper;

    public static void main(String[] args) {

        MergeSort ob = new MergeSort();
        ob.sort();
        for (int i : arr) {
            System.out.println(arr[i]);
        }
    }

    private void sort() {
        int number = arr.length;
        helper = new int[number];
        mergeSort(0, number - 1);
    }

    private void mergeSort(int low, int high) {
        if (low < high) {
            int middle = (low + (high - low)) / 2;
            mergeSort(low, middle);
            mergeSort(middle + 1, high);
            merge(low, middle, high);
        }
    }

    private void merge(int low, int middle, int high) {
        for (int i = low; i <= high; i++) {
            helper[i] = arr[i];
        }
        int firstPointer = low;
        int secondPointer = middle + 1;
        int insertPointer = low;
        while (firstPointer <= middle && secondPointer <= high) {
            if (helper[firstPointer] < helper[secondPointer]) {
                arr[insertPointer] = helper[firstPointer];
                firstPointer++;
            } else {
                arr[insertPointer] = helper[secondPointer];
                secondPointer++;
            }
            insertPointer++;
        }
        if (firstPointer < middle || middle == 0) {
            while (firstPointer <= middle) {
                arr[insertPointer] = helper[firstPointer];
                firstPointer++;
                insertPointer++;
            }
        } else {
            while (secondPointer <= high) {
                arr[insertPointer] = helper[secondPointer];
                secondPointer++;
                insertPointer++;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

获得中间位置应该是:

int middle = low + ((high - low) / 2);

答案 1 :(得分:2)

我认为你的问题就在这里

int middle = (low + (high - low)) / 2; ???????????????????

请注意:(low + (high - low)) / 2 等于 hight / 2

所以正确的中间函数是:

int middle = (low + high ) / 2;