# Attempt at Merge Sort: Is this correct?

I am trying to write a merge sort algo. I can't tell if this is actually a canonical merge sort. If I knew how to calculate the runtime I would give that a go. Does anyone have any pointers? Thanks.

``````public static void main(String[] argsv) {

int[] A = {2, 4, 5, 7, 1, 2, 3, 6};
int[] L, R;

L = new int[A.length/2];
R = new int[A.length/2];

int i = 0, j = 0, k;

PrintArray(A);
// Make left and right arrays
for (k = 0; k < A.length; k++) {
if (k < A.length/2) {
L[i] = A[k];
i++;
}
else {
R[j] = A[k];
j++;
}
}

PrintArray(L);
PrintArray(R);

i = 0;
j = 0;
// Merge the left and right arrays
for (k = 0; k < A.length; k++) {
System.out.println(i + " " + j + " " + k);
if (i < L.length && j < R.length) {
if (L[i] < R[j]) {
PrintArray(A);
A[k] = L[i];
i++;
}
else {
PrintArray(A);
A[k] = R[j];
j++;
}
}
}

PrintArray(L);
PrintArray(R);
PrintArray(A);
}

public static void PrintArray(int[] arrayToPrint) {
for (int i = 0; i < arrayToPrint.length; i++) {
System.out.print(arrayToPrint[i] + " ");
}
System.out.print("\n");
}
``````
-
I asked here after reading Jeff Atwood's post here: blog.stackoverflow.com/2010/12/…;. "In a nutshell, Stack Overflow is for when you’re front of your compiler or editor working through code issues. Programmers is for when you’re in front of a whiteboard working through higher level conceptual programming issues. Hence the (awesome) whiteboard inspired design!" I guess I must have misinterpreted that. I am trying to learn mergesort for upcoming interviews –  Beatrice Oct 16 '12 at 20:51
can you run the code? –  Malachi Oct 16 '12 at 20:54
Hm. I guess that is what I am asking. Thanks for the advice. –  Beatrice Oct 16 '12 at 20:54
@Malachi: yes, the code runs and correctly sorts an array with an even number of elements –  Beatrice Oct 16 '12 at 20:55
I think what you are asking here is: what is the correct answer when asked in an interview: write a canonical Merge Sort. right? –  Malachi Oct 16 '12 at 20:58

## migrated from programmers.stackexchange.comOct 16 '12 at 20:56

This question came from our site for professional programmers interested in conceptual questions about software development.