如何在我的Merge Sort实现中找到错误?

时间:2016-08-06 23:07:38

标签: java algorithm sorting merge mergesort

我尝试编写合并排序算法,但我不知道哪里出错。你能告诉我我做错了什么吗?或者用算法建议一些有用的资源/实践?

public class MergeSort {

private int[] auxArray;

public void sort(int[] array)
{
    auxArray = new int[array.length];
    sort(array, 0, array.length - 1);

        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
      }

}

private void sort(int[] array, int begin, int end)
{
    if( begin >= end) return ;

    int middle = begin + (end - begin) / 2;

    sort(array, begin, middle);
    sort(array, middle + 1, end);
    merge(array, begin, middle, end);

}


private void merge(int[] array, int begin, int middle, int end)
{

    int i = begin;
    int j = middle + 1;

    for (int k = begin; k <= end; k++) {
        auxArray[k] = array[k];
    }

    for (int k = begin; k <= end; k++)
    {
        if(i > middle) array[k] = auxArray[j++];
        else if(j > end) array[k] = auxArray[i++];
        else if(array[i] >= array[j])
        {
            array[k] = auxArray[j++];
        }
        else
            array[k] = auxArray[i++];
    }

}

public static void main(String[] args) throws Exception {

    MergeSort sort = new MergeSort();

    int[] array = new int[] {10, 9, 8, 7, 6, 5 ,4, 3, 2 ,1};

    sort.sort(array);

}
}

1 个答案:

答案 0 :(得分:2)

在merge()中,更改

        else if(array[i] >= array[j])

        else if(auxArray[i] >= auxArray[j])