Welcome to Merge Sort

Hello, aspiring programmers! Today's topic is the "Merge Sort." Merge Sort is a sorting technique like arranging a deck of shuffled cards in order. But for data on the Internet scale, Merge Sort outperforms your regular techniques. Today, we'll explore Merge Sort, code it in Java, and analyze its speed. Ready? Let's get started!

What is Merge Sort?

In computer science, Merge Sort is a popular method to sort elements. Merge Sort uses the same 'divide-and-conquer' strategy for sorting, like the familiar Quick Sort algorithm. Imagine if you have one long music playlist mixed up with songs. You want to sort these songs from A to Z. That's what Merge Sort does to an array.

In the three steps of Merge Sort:

  1. Split the array into halves.
  2. Sort each half separately.
  3. Merge the sorted halves back together.
Understanding the Merge Process

We will start with building a code for merging two sorted parts. The merge process makes two halves play sort and seek. It compares elements from two halves and merges so that the resulting list is sorted as well.

Let's code a merge() function in Java that will do just that. Note that the final variant of the merge sort function will do every operation "in place," meaning there will not be actual two arrays; we will operate parts of one array. Having this in mind, let's implement the merge function to take just one array and treat its parts like separate arrays.

void merge(int arr[], int left, int mid, int right) {
    int n1 = mid - left + 1; // Find number of elements in the left array
    int Left[] = new int[n1]; // Define left array

    int n2 = right - mid; // Find number of elements in the right array
    int Right[] = new int[n2]; // Define right array

    // Let's fill in these arrays
    for (int i = 0; i < n1; i++)
        Left[i] = arr[left + i];
    for (int j = 0; j < n2; j++)
        Right[j] = arr[mid + 1 + j];
}

So far, we've divided our original list into two halves, Left and Right.

Merging the Halves Back Together

Now, we'll sort and merge these halves:

    int i = 0, j = 0;
    int k = left;
    while (i < n1 && j < n2) {
        if (Left[i] <= Right[j]) {
            arr[k] = Left[i];
            i++;
        } else {
            arr[k] = Right[j];
            j++;
        }
        k++;
    }
}

Seemingly tricky, the code is very straightforward: We place two pointers, i and j, at the beginning of the Right and Left arrays. We choose the smaller element, put it in the final array arr, and move the corresponding pointer further. We keep doing this until one of the pointers reaches the end of its array.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal