Merge Sort Algorithm using Generics in Java

Today, we are going to show the implementation of the Merge Sort algorithm, which is the fifth one from our series of tutorials on sorting algorithms. If you haven’t read the first four tutorials on BubbleSortInsertionSortSelectionSort and CountingSort, I strongly recommend that you go there and read them, because we will reuse code that was explained there.

The application is really simple, it will just get an instance of a Sortable algorithm, which in this case will be a MergeSort object and pass some Integer and String arrays to it, but any object that implements Comparable can be passed as a parameter as well, then it will print the elements from the sorted arrays.

<br />
public class SorterApp {<br />
  public static void main(String[] args) {<br />
    SorterApp app = new SorterApp();<br />;<br />
<p>  private void run() {<br />
    sort(new Integer[] { 2, 42, -3, 2, 4 });<br />
    sort(new Integer[] { 1, 2, 3, 4, 5 });<br />
    sort(new Integer[] { 3, 1, 5, 4, 2 });<br />
    sort(new Integer[] { 5, 4, 3, 2, 1 });</p>
<p>    System.out.println();</p>
<p>    sort(new String[] { &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot; });<br />
    sort(new String[] { &quot;c&quot;, &quot;a&quot;, &quot;e&quot;, &quot;d&quot;, &quot;b&quot; });<br />
    sort(new String[] { &quot;e&quot;, &quot;d&quot;, &quot;c&quot;, &quot;b&quot;, &quot;a&quot; });<br />
<p>  private &lt;T extends Comparable&lt;T&gt;&gt; void sort(T[] values) {<br />
    Sortable sorter = newSortable(5);<br />
    sorter.sortAscending(values);<br />
    // sorter.sortDescending(values);<br />
    Utils.printArray(values);<br />
<p>  private Sortable newSortable(int sortableAlgorithm) {<br />
    switch (sortableAlgorithm) {<br />
      case 1:<br />
        return new BubbleSort();<br />
      case 2:<br />
        return new InsertionSort();<br />
      case 3:<br />
        return new SelectionSort();<br />
      case 4:<br />
        return new CountingSort();<br />
      case 5:<br />
        return new MergeSort();<br />
      default:<br />
        return new BubbleSort();<br />
    }<br />
  }<br />
}<br />

You can see in the code below that the sortAscending and sortDescending invoke the same private method mergeSort with the difference of just one parameter. This is done because the code to sort in ascending or descending order is pretty much the same; the difference is just one small detail.

The Sorter Abstract class and the Sortable Interface were explained in the first tutorial of our series.

<br />
public class SelectionSort extends Sorter implements Sortable {<br />
  private int count = 0;</p>
<p>  @Override<br />
  public &lt;T extends Comparable&lt;T&gt;&gt; void sortAscending(T[] values) {<br />
    count = 0;<br />
    mergeSort(values, 0, values.length - 1, 0);</p>
<p>    System.out.printf(&quot;%2s: &quot;, count);<br />
<p>  @Override<br />
  public &lt;T extends Comparable&lt;T&gt;&gt; void sortDescending(T[] values) {<br />
    count = 0;<br />
    mergeSort(values, 0, values.length - 1, 1);</p>
<p>    System.out.printf(&quot;%2s: &quot;, count);<br />
  }<br />

The Merge Sort implementation will create some temporary arrays and to do that, we added a method into the Utils class:

<br />
  public static &lt;T&gt; List&lt;T&gt; newList(int initialCapacity) {<br />
    return new ArrayList&lt;T&gt;(initialCapacity);<br />
  }<br />

Just like Bubble Sort, Insertion Sort and Selection Sort, the Merge Sort is a comparison sort type of algorithm, which means, it sorts its elements by doing comparisons between two elements at a time, but unlike the others, the most common implementations of Merge Sort do not sort in-place and because of this, they require more memory.

<br />
  private &lt;T extends Comparable&lt;T&gt;&gt; void mergeSort(T[] arValues, int low, int high, int orderType) {<br />
    if (low &lt; high) {<br />
      // Get the middle of the array.<br />
      int middle = low + ((high - low) / 2);</p>
<p>      // Divide.<br />
      mergeSort(arValues, low, middle, orderType);<br />
      mergeSort(arValues, middle + 1, high, orderType);</p>
<p>      // Conquer.<br />
      merge(arValues, low, middle, high, orderType);<br />
    }<br />
<p>  private &lt;T extends Comparable&lt;T&gt;&gt; void merge(T[] arValues, int low, int middle, int high, int orderType) {<br />
    // The amount of numbers to sort.<br />
    int numbersToSort = (high - low) + 1;</p>
<p>    // Temp array to contain the sorted elements of this iteration.<br />
    List&lt;T&gt; arTemp = Utils.newList(numbersToSort);</p>
<p>    int i = low;<br />
    int j = middle + 1;<br />
    T lowValue = null;<br />
    T highValue = null;<br />
    for (int k = 0; k &lt; numbersToSort; k++) {<br />
<p>      lowValue = (i &lt;= middle) ? arValues[i] : null;<br />
      highValue = (j &lt;= high) ? arValues[j] : null;</p>
<p>      if (checkBiggerSmaller(lowValue, highValue, orderType)) {<br />
        arTemp.add(arValues[i++]);<br />
      } else {<br />
        arTemp.add(arValues[j++]);<br />
      }<br />
<p>    // Transfer the sorted elements to the original array.<br />
    for (int k = 0; k &lt; numbersToSort; k++) {<br />
      count++;<br />
      arValues[low + k] = arTemp.get(k);<br />
    }<br />
<p>  private &lt;T extends Comparable&lt;T&gt;&gt; boolean checkBiggerSmaller(T lowValue, T highValue, int orderType) {<br />
    if ((lowValue != null) &amp;&amp; (highValue == null)) {<br />
      return true;<br />
    } else if ((lowValue == null) &amp;&amp; (highValue != null)) {<br />
      return false;<br />
<p>    if (0 == orderType) {<br />
      // Ascending.<br />
      return lowValue.compareTo(highValue) &lt;= 0;<br />
    } else {<br />
      // Descending.<br />
      return lowValue.compareTo(highValue) &gt;= 0;<br />
    }<br />
  }<br />
}<br />



You can download all the files here: MergeSort.

Thank you for your time and feel free to leave any comments or questions.


Leave a Reply

Time limit is exhausted. Please reload CAPTCHA.