-1

在下面的代码中,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++;
            }
        }
    }
}
4

2 回答 2

2

要获得中间位置应该是:

int middle = low + ((high - low) / 2);
于 2013-04-13T15:52:00.900 回答
2

我认为你的问题就在这里

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

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

所以正确的中间函数是:

int middle = (low + high ) / 2;


于 2013-04-13T15:52:17.530 回答