3
\$\begingroup\$

I'd like to know if the following code is a good implementation of MergeSort? I tried some examples and the code was right, so I guess that the algorithm works correctly.

public static int[] myMerge (int[] array, int[] array2){

    int[] giveback = new int[array.length + array2.length];
    int i = 0; 
    int j = 0; 


    for (int x = 0; x < giveback.length; x++){

        if (array[i] >= array2[j]){

            giveback[x] = array2[j];
            j++;

        }
        else{

            giveback[x] = array[i];
            i++;
        }

        if (i == array.length){

            x++;
            for(int c = j; c < array2.length; c++){


                giveback[x] = array2[c];
                x++;    
            }

            return giveback;
        }

        if (j == array2.length){

            x++;
            for (int b = i; b < array.length; b++){

                giveback[x] = array[b];
                x++;
            }
            return giveback;
        }


    }       
    return giveback;
}

public static int[] myMergeSort (int[] array){

    if (array.length <= 1 ){

        return array;
    }

    if (array.length % 2 == 0){

        int[] right = new int[array.length/2];
        int[] left = new int[array.length/2];
        int counter = 0;

        for (int i = 0; i < array.length/2; i++){

            left[i] = array[i];

        }

        for (int j = array.length/2; j < array.length; j++){

            right[counter] = array[j];
            counter++;

        }
        return myMerge(myMergeSort(right),myMergeSort(left));
    }
    else{

        int[] right = new int[array.length/2];
        int[] left = new int[array.length/2];
        int counter2 = 0;

        for(int i = 0; i < array.length/2 +1; i++){

            left[i] = array[i];
        }

        for(int j = array.length/2 +1; j < array.length; j++){

            right[counter2]=array[j];
            counter2++;
        }
        return myMerge(myMergeSort(right),myMergeSort(left));
    }
}
\$\endgroup\$
1
\$\begingroup\$

You don't have to distinguish if array.length if even or odd.
Just do:

    int[] right = new int[array.length/2];
    int[] left = new int[array.length - array.length/2];

It will make the two tables to have exactly array.length items together, divided by half as precisely as possible.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.