Merge Sort algorithm

In this tutorial, I will be with you to learn about an algorithm to sort the elements in an array, Merge Sort algorithm!

OK,

Now suppose I have an array of numeric values arranged as follows:

The Merge Sort algorithm divides the array into multiple child arrays, until each of the children has only one element. Then, it compares the values of the sub arrays so that they are grouped together into sorted arrays. And finally, we will get a sorted array.

In our example, using the Merge Sort algorithm, the following steps will occur:

Step 1: Divide the large array into two sub-arrays:

  • Step 2: Continue to split

  • Step 3: Still have the array containing more than 2 elements so continue to split

  • Step 4: Because all the arrays now contain one element, we now compare the values and collect them.

  • Step 5: Continue collecting:

  • Result:

As you see, after a few steps divided, the array was rearranged.

The idea is that, so what is the Merge Sort algorithm? Let me tell you the following.

The Merge algorithm looks like this:

OK, here’s how to implement the Merge Sort algorithm with the Java language:

In this implementation of the Merge Sort algorithm, I used the Comparator interface to compare two objects of the same class.

Below, I will use the code above to make an example:

Result:

Merge Sort algorithm

Add Comment