0
import java.util.Arrays;

public class mergeSort{

    public static void main(String[] args) {

    int[] arr = {2, 4, 5, 7, 1, 2, 3, 6};
    int size = arr.length;
    int[] L, R;

    L = new int[size/2]; //setup both the left and right side arrays
    R = new int[size/2];

    int k, i = 0, j = 0;

    for(k = 0; k < size; k++){
        if (k < size/2){
            L[i] =  arr[k];
            i++; //iterate through the left side
        }
        else{
            R[j] =  arr[k];
            j++;// iterate through the right side
        }

    }

    i = 0;
    j = 0;

    for (k = 0; k < size; k++){
        if (i < L.length && j < R.length){
            if(L[i] < R[j]){
                arr[k] = L[i];
                i++;
            }
            else{
                arr[k] = R[j];
                j++;
            }
        }

    }


    printArray(arr);    
    }

    public static void printArray(int[] arrayToPrint) {
    for (int i = 0; i < arrayToPrint.length; i++) {
        System.out.print(arrayToPrint[i] + " ");
    }
    System.out.print("\n");
}




}

I am working on an implementation for merge sort. But for some reason I am not getting the correct results. The answer I get when I try to sort this array is this: "1 2 2 3 4 5 6 6". I don't understand where "7" goes. And if I remove an element from the array I get an ArrayIndexOutOfBoundsException.

With the array out of bounds exception, I dont understand where exactly I am going wrong. I increased the size of the array but it doesnt change the result. Am I looking at it with an incorrect approach?

Thanks!

vampyfreak
  • 21
  • 1
  • 7
  • I don't see a merge sort here (merge sort first divide the array into halves recursively until you can not divide and then merge those arrays). The other problem is you are not sizing arrays properly especially when you have odd number of elements in array.. you should do something like `int half = size/2; L = new int[half]; R = new int[size-half];`. – RP- Jan 06 '17 at 00:21
  • I fixed that but I still dont understand the array out of bound error. Can you please elaborate on it if you can? Thanks! – vampyfreak Jan 06 '17 at 00:27
  • @vampyfreak - RP's comment somewhat explains this. If the array size is 7, then with his suggestion, the size of L is 3 and the size of R is 4. With the unfixed code, the size of L == size of R == 7/2 == 3. With the unfixed code in the question, you'll get an array out of bounds on the first for loop as it copies elements from arr[] into R[], specifically R[3] = arr[6]. – rcgldr Jan 06 '17 at 01:42

0 Answers0