00:00

Merge Sort in Java

Sorting is the process of arranging a list of unsorted data in a particular order, either ascending or descending. Sort algorithms play a very crucial role for organizing unsorted data and facilitating efficient searching, retrieval, and analysis.

Every sorting algorithm has a unique approach for sorting the data; these sorting algorithms are used according to the specific requirements of the problem, including data size, structure, and distribution, as well as time and space constraints.

In this tutorial, we are going to learn all about Merge Sort in Java.

Example of Merge Sort in Java

MergeSortExample.java
class MergeSortExample {

  // Merges two subarrays of arrayNumber[].
  // First subarray is arrayNumber[l..m]
  // Second subarray is arrayNumber[m+1..r]
  static void merge(int arrayNumber[], int l, int m, int r) {
    // Find sizes of two subarrays to be merged
    int n1 = m - l + 1;
    int n2 = r - m;

    // Create temp arrays
    int L[] = new int[n1];
    int R[] = new int[n2];

    // Copy data to temp arrays
    for (int i = 0; i < n1; ++i)
      L[i] = arrayNumber[l + i];
    for (int j = 0; j < n2; ++j)
      R[j] = arrayNumber[m + 1 + j];

    // Initial indices of first and second subarrays
    int i = 0, j = 0;

    // Initial index of merged subarray array
    int k = l;
    while (i < n1 && j < n2) {
      if (L[i] <= R[j]) {
        arrayNumber[k] = L[i];
        i++;
      } else {
        arrayNumber[k] = R[j];
        j++;
      }
      k++;
    }

    // Copy remaining elements of L[] if any
    while (i < n1) {
      arrayNumber[k] = L[i];
      i++;
      k++;
    }

    // Copy remaining elements of R[] if any
    while (j < n2) {
      arrayNumber[k] = R[j];
      j++;
      k++;
    }
  }

  // Function to sorts an array[l..r] using merge sort technique
  static void sort(int array[], int l, int r) {
    if (l < r) {

      // Find the middle point
      int m = l + (r - l) / 2;

      // Sort first and second halves
      sort(array, l, m);
      sort(array, m + 1, r);

      // Merge the sorted halves
      merge(array, l, m, r);
    }
  }

  // Function to print an array
  static void printArray(int arrayNumber[]) {
    int n = arrayNumber.length;
    for (int i = 0; i < n; ++i)
      System.out.print(arrayNumber[i] + " ");
    System.out.println();
  }

  public static void main(String args[]) {
    // Creates an array
    int arrayNumber[] = { 40, 70, 90, 20, 80, 100, 60, 10, 30, 50 };

    System.out.println("Origin unsorted array is");
    printArray(arrayNumber);

    sort(arrayNumber, 0, arrayNumber.length - 1);

    System.out.println("\nSorted array is");
    printArray(arrayNumber);
  }
}
Output
Origin unsorted array is

40 70 90 20 80 100 60 10 30 50

Sorted array is

10 20 30 40 50 60 70 80 90 100