HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

Is this attempt at a merge sort correct?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thismergeattemptcorrectsort

Problem

I am trying to write a merge sort algorithm. 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?

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");
}

Solution

When a prospective employer asks you a question like this one, they most likely want to see something original. They want you to show them that you can create code and not just copy and paste bits and pieces of code.

If what you wrote works and runs correctly, then you have accomplished the answer.

Sometimes employers are trying to find out if you know the theory behind a merge sort. It looks to me like you have done that as well.

The only thing that I can think of that you could do to make your code better is to improve the naming of your variables.

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];


Change them to

int[] array = {2, 4, 5, 7, 1, 2, 3, 6};
int[] leftSide;
int[] rightSide;

leftSide = new int[array.length/2];
rightSide = new int[array.length/2];


This would make it much easier to read.

Code Snippets

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[] array = {2, 4, 5, 7, 1, 2, 3, 6};
int[] leftSide;
int[] rightSide;

leftSide = new int[array.length/2];
rightSide = new int[array.length/2];

Context

StackExchange Code Review Q#17622, answer score: 5

Revisions (0)

No revisions yet.