合并排序算法

时间:2015-02-27 22:03:04

标签: java algorithm sorting mergesort

我一直在解决与合并排序相关的问题,但不知道我的程序中有什么问题所以你能看一下吗?

问题是给出一个未排序的数组,它将提供排序而不更改原始数组。 请让我知道我的错误在哪里

public static int []  mergeSort(int[] in){

        int [] temp = in.clone();

        if (temp.length <= 1){

            }


        else{
            int [] first = new int[temp.length/2];
            int [] second = new int [temp.length - first.length];

            for (int i=0; i<first.length; i++){
                first[i] = temp[i];
            }

            for (int i = 0; i < second.length; i++){
                second[i] = temp[first.length+i];
            }

            mergeSort(first);
            mergeSort(second);
            merg(first,second,temp);

        }

    return temp;
    }
    public static void merg(int [] first, int[] second, int []newTemp){


        int i =0;
        int j = 0;
        int k = 0;
        while(i <first.length && j < second.length ){

            if(first[i] <=second[j]){

                newTemp[k] = first[i];
                i++;
            }
            else{
                newTemp[k] = second[j];
                j++;

            }
            k++;

        }
        while (i < first.length){
            newTemp[k] = first[i];
            i++;
            k++;
        }
        while(j < second.length){
            newTemp[k]= second[j];
            j++;
            k++;
        }

    }

1 个答案:

答案 0 :(得分:2)

问题是因为您正在克隆数组,每次调用mergeSort()函数时,它都会克隆数组。它只需要在第一次调用函数时克隆。

以下是您问题的完整解决方案。你应该调用第一个mergeSort()函数。

public static int[] mergeSort(int[] in) {
    return mergeSort(in, 0);
}

public static int[] mergeSort(int[] in, int number_of_times_called) {

    int[] temp;
    if (number_of_times_called == 0)
        temp = in.clone();
    else
        temp = in

    if (temp.length <= 1){
        return temp;
    }


    else{
        int [] first = new int[temp.length/2];
        int [] second = new int [temp.length - first.length];

        for (int i=0; i<first.length; i++){
            first[i] = temp[i];
        }

        for (int i = 0; i < second.length; i++){
            second[i] = temp[first.length+i];
        }

        mergeSort(first);
        mergeSort(second);
        merg(first,second,temp);

    }

    return temp;
}

public static void merg(int [] first, int[] second, int []newTemp){


    int i =0;
    int j = 0;
    int k = 0;
    while(i <first.length && j < second.length ){

        if(first[i] <=second[j]){

            newTemp[k] = first[i];
            i++;
        }
        else{
            newTemp[k] = second[j];
            j++;

        }
        k++;

    }
    while (i < first.length){
        newTemp[k] = first[i];
        i++;
        k++;
    }
    while(j < second.length){
        newTemp[k]= second[j];
        j++;
        k++;
    }

}