×

Merge Sort in Java

Merge Sort in Java

Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort.

1) Divide the given array into two halves (smaller arrays). Divides those two halves into further halves and continue to do so until further division is not possible.

2) Now, do the conquer by sorting the smaller arrays recursively.

3) Concatenate the smaller arrays that are sorted and it forms the bigger arrays. The concatenation of bigger arrays leads to an even bigger array, ultimately leading to a final array that is also sorted. Its size will be equal to the original array.

Algorithm and Pseudo Code

mergeSort(A[], i,  j)

If j > i

     1. Get the mid-point to split the given array into two halves: 

             middle mid = i + (j - i) / 2

     2. Invoke the mergeSort() method for the first half:  

             Call mergeSort(A, i, mid)

     3. Similarly, invoke the mergeSort() for the second half:

             Call mergeSort(A, mid + 1, j)

     4. Combine the two sorted halves found in step 2 and 3:

             Call merger(A, i, mid, mid + 1, r)

Java Program

The following Java program implements Merge sort.

FileName: MergeSortExample.java

 public class MergeSortExample
{
// method that implements merge sort
static void mergeSort(int a[], int i, int j)
{
// find the middle point
int mid = (j + i) / 2;
if(j > i)
{
    // recursively splitting the array into two halves
    mergeSort(a, i, mid); // first half
    mergeSort(a, mid + 1, j); // second half
    // merging the two halves to
    // form a bigger array
    merger(a, i, mid, mid + 1, j);
}
}
// The merger() method merges the two sorted array
// The first sorted array starts from the index s1 and ends at e1
// Similarly, the second sorted array starts from the index s2 and ends at e2
static void merger(int arr[], int s1, int e1, int s2, int e2)
{
    // calculating the temp array
    int length = e2 - s1 + 1;
    // the temp array
    int temp[] = new int[length];
    // two pointers pointes to the starting
    // index of the two sorted arrays
    int ptr1 = s1, ptr2 = s2;
    // index is the variable used to
    // iterate over the temp array
    int index = 0;
    // while loop does the actual merging and
    // stores the resultant sorted array in temp
    while(ptr1 <= e1 && ptr2 <= e2)
    {
        if(ptr1 <= e1 && (arr[ptr1] < arr[ptr2]))
        {
            temp[index] = arr[ptr1];
            ptr1 = ptr1 + 1;
        }
        else if(ptr2 <= e2)
        {
            temp[index] = arr[ptr2];
            ptr2 = ptr2 + 1;
        }
        index = index + 1;
    }
    // copying remaining elements of the arr to temp
    while(ptr1 <= e1)
    {
        temp[index] = arr[ptr1];
        ptr1 = ptr1 + 1;
        index = index + 1;
    }
    // copying remaining elements of the arr to temp
    while(ptr2 <= e2)
    {
        temp[index] = arr[ptr2];
        ptr2 = ptr2 + 1;
        index = index + 1;
    }
    // resetting the index to 0
    index = 0;
    // copying the values of temp array
    // in the array arr
    for(int i = s1; i <= e2; i++)
    {
        arr[i] = temp[index];
        index = index + 1;
    }
}
// main method
public static void main(String argvs[])
{
    // given input array
    int a[] = {67, 78, 34, 12, 30, 6, 9, 21};
    // calculating size of the array
    int size = a.length;
    System.out.println("The array before sorting is: ");
    for(int i = 0; i < size; i++)
    {
       System.out.print(a[i] + " ");
    }
    System.out.println("\n");
    // invoking method mergeSort()
    mergeSort(a, 0, size - 1);
    System.out.println("The array after sorting is: ");
    // displaying the sorted array
    for(int i = 0; i < size; i++)
    {
        System.out.print(a[i] + " ");
    }
}
} 

Output:

 The array before sorting is:
67 78 34 12 30 6 9 21
The array after sorting is:
6 9 12 21 30 34 67 78 

Explanation: First, we split the input array into smaller arrays called sub-arrays. Perform the step until each sub-array has 1 element. Since, an array of a single element is always sorted, the merger() method is called to combine the smallest sub-arrays to  get a small sub-array, which is sorted, contains 2 elements. Now, two sub-arrays of length 2 are merged to get a sorted array of size 4. Again, two sub-arrays of size 4 are merged to get a sorted array of size 8. The array we get is a final sorted array. The merging of the two sorted arrays is done using the two-pointer approach. The first while loop present in the merger() method does the same. The following diagram depicts the same.

Analysis of Merge Sort

Merge sort is a stable algorithm. One of the main properties of the marge sort algorithm is that it does not depend on the arrangement of elements. The property is good as well as bad. For example, consider an array a[] = {67, 78, 80, 90}. We see that the array is already sorted. However, if we apply merge sort on this array, the merge sort does not care whether the array is sorted or not, i.e., it splits the array, which is already sorted, recursively and applies the conquer and combine approach. It is the cons of the merge sort algorithm.

The positive aspect is if we consider the array as a[] = {78, 67, 90, 80}, the divide and conquer approach comes very handy. For this type of inputs, merge sort emerges as one of the finest sorting algorithms.

Time Complexity

The time complexity of the merge sort is O(nlog(n)), where n is the number of elements present in the array or list. Since merge sort is independent of the arrangement of elements; therefore, the best, as well as the worst complexity, is O(nlog(n)).

Space Complexity

The space complexity of the merge sort algorithm is O(n), where n is the number of elements present in the array or list. It is due to the auxiliary array (temp array in our case) that is used for copying the elements from one array to another.

Conclusion

For arrays whose elements are almost sorted or sorted completely, merge sort is not the best sorting algorithm to go with. However, merge sort must be used for those arrays whose elements are jumbled a lot.


Related Topics

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Java finalize()

Java finalize() In Java, the Object class is the root class that is inherited by all the Java classes. The class provides the finalize() method that is called just before the...

4 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.