Merge Sort in Java

Merge Sort in Java. Merge sort is a popular sorting algorithm known for its efficiency and reliability. Merge sort follows the divide and conquer approach, breaking down the sorting task into smaller sub-problems until the base case is reached, and merging the sorted solutions to form the final sorted array. In this article we will write code for merge sort in java.

Overview of Merge Sort Algorithm

Merge Sort operates by recursively dividing the input array into two halves until each subarray contains only one element. then it merges those sorted subarrays to produce a fully sorted array. The key steps of merge sort include-

  • Divide- Split the unsorted array into half.
  • Conquer- Recursively apply merge sort to each sub-array until they are reduced to a single element.
  • Combine- Merge this sorted sub-array to produce the final sorted array.

Merge Sort Program in Java

Output

Merge Sort Program in Java

In the above C program

  • The merge function combines two sorted sub-arrays into a single sorted array.
  • The mergeSort function recursively divides the array into two halves and calls the merge function two to merge the sorted halves.
  • The main function initializes an array, calls mergeSort to sort the array, and prints the sorted array.

Merge Sort Time Complexity

Merge Sort’s time complexity is consistently effective and is expressed as O(n logn), Where n is the number of elements in the array to be sorted. The complexity of merge sort makes merge sort a reliable choice for sorting large data sets, As it maintains a relatively consistent performance regardless of input size.

Happy Coding & Learning

See Also

Leave a Comment