Java
Java

 

 

Overview

Merge Sort is a divide-and-conquer algorithm that sorts an array by recursively dividing it into two halves,
sorting those halves, and then merging them back together. This algorithm has a time complexity of O(n log n)
and is known for its efficiency in handling large datasets.

Java Implementation


public class MergeSort {

    // Main function that sorts array[left...right] using merge()
    public void sort(int[] array) {
        if (array == null || array.length == 0) {
            return;
        }
        int[] tempArray = new int[array.length];
        mergeSort(array, 0, array.length - 1, tempArray);
    }

    // Recursive function to sort the array
    private void mergeSort(int[] array, int left, int right, int[] tempArray) {
        if (left < right) {
            int mid = (left + right) / 2;

            // Sort the first half
            mergeSort(array, left, mid, tempArray);
            // Sort the second half
            mergeSort(array, mid + 1, right, tempArray);
            // Merge the sorted halves
            merge(array, left, mid, right, tempArray);
        }
    }

    // Merges two subarrays of array[]
    private void merge(int[] array, int left, int mid, int right, int[] tempArray) {
        // Copy data to temp array
        for (int i = left; i <= right; i++) {
            tempArray[i] = array[i];
        }

        int i = left;      // Starting index for left subarray
        int j = mid + 1;   // Starting index for right subarray
        int k = left;      // Starting index to be sorted

        // Merge the temp arrays back into array[left...right]
        while (i <= mid && j <= right) {
            if (tempArray[i] <= tempArray[j]) {
                array[k] = tempArray[i];
                i++;
            } else {
                array[k] = tempArray[j];
                j++;
            }
            k++;
        }

        // Copy the remaining elements of left subarray, if any
        while (i <= mid) {
            array[k] = tempArray[i];
            i++;
            k++;
        }

        // No need to copy the right subarray as they are already in place
    }

    // Main method to test the sorting algorithm
    public static void main(String[] args) {
        MergeSort mergeSort = new MergeSort();
        int[] array = {38, 27, 43, 3, 9, 82, 10};
        
        System.out.println("Original Array:");
        printArray(array);
        
        mergeSort.sort(array);
        
        System.out.println("Sorted Array:");
        printArray(array);
    }

    // Utility method to print the array
    private static void printArray(int[] array) {
        for (int value : array) {
            System.out.print(value + " ");
        }
        System.out.println();
    }
}

Program Structure

The MergeSort class contains methods to perform the merge sort operation.
The main components of the program are:

  • sort(int[] array): This is the main method that initializes the sorting process.
  • mergeSort(int[] array, int left, int right, int[] tempArray): This recursive method divides the array into halves.
  • merge(int[] array, int left, int mid, int right, int[] tempArray): This method merges two sorted halves back into a single sorted array.
  • printArray(int[] array): A utility method to print the contents of the array.

How to Run the Program

To run the program, copy the code into a file named MergeSort.java and compile it using a Java compiler:


javac MergeSort.java
java MergeSort

The output will display the original and sorted arrays.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)