Mergesort in java

后端 未结 12 550
予麋鹿
予麋鹿 2020-12-03 06:09

I am new to Java and have tried to implement mergesort in Java. However, even after running the program several times, instead of the desired sorted output, I am getting the

12条回答
  •  一个人的身影
    2020-12-03 06:22

    The problem lies here:

    A = merge(leftArray,rightArray);
    

    Now your merge array does this:

    static int[] merge(int[] l, int[] r) {
        int[] a = new int[totElem];
        // bunch of code
        return a;
    }
    

    When you started, A was a reference to inputArray. But then you reassigned it to be whatever came out of merge. Unfortunately, that doesn't touch what inputArray is in the main method. That basically says "Oh look at all the work you did... throw it away!"

    You could change that with something like

    static int[] mergeSort(int[] A) {
        // A = merge... // not this
        return merge... // use this
    }
    

    Then in your main method, you can do

    int[] merged = mergeSort(inputArray);
    for(int i : merged) System.out.println(i);
    

提交回复
热议问题