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));
 }
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Dec 11, 2016 at 17:45
\$\endgroup\$

1 Answer 1

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.

answered Dec 11, 2016 at 18:10
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.