Merge sort is considered to be highly reliable and efficient sorting algorithm. It is one of the most popular choices for many applications that need sorting logic.
Merge sort is also called stable sort as it preserves the relative order of equal elements in the input array.
package org.code2care.java.sorting.algo;
import java.util.Arrays;
public class MergeSortJavaExample {
public static void main(String[] args) {
//Unsorted Array
int[] unsortedArray = {4, 99, 2, 11, 34, 67, 54, 12, 45, 245, 234, 12, 200};
MergeSortJavaExample mergeSort = new MergeSortJavaExample();
int[] sortedArray = mergeSort.mergeSortAlgorithm(unsortedArray);
System.out.println(Arrays.toString(sortedArray));
}
public int[] mergeSortAlgorithm(int[] arrayOfNumbers) {
int arrayLength = arrayOfNumbers.length;
if (arrayLength == 1) {
return arrayOfNumbers;
}
//Divide the array into two halves
int midIndex = arrayLength / 2;
int[] leftArray = Arrays.copyOfRange(arrayOfNumbers, 0, midIndex);
int[] rightArray = Arrays.copyOfRange(arrayOfNumbers, midIndex, arrayLength);
leftArray = mergeSortAlgorithm(leftArray);
rightArray = mergeSortAlgorithm(rightArray);
return mergeArrays(leftArray, rightArray);
}
public int[] mergeArrays(int[] leftArray, int[] rightArray) {
int leftLength = leftArray.length;
int rightLength = rightArray.length;
int[] mergedArray = new int[leftLength + rightLength];
int leftIndex = 0, rightIndex = 0, mergedIndex = 0;
while (leftIndex < leftLength && rightIndex < rightLength) {
if (leftArray[leftIndex] <= rightArray[rightIndex]) {
mergedArray[mergedIndex] = leftArray[leftIndex];
leftIndex++;
} else {
mergedArray[mergedIndex] = rightArray[rightIndex];
rightIndex++;
}
mergedIndex++;
}
while (leftIndex < leftLength) {
mergedArray[mergedIndex] = leftArray[leftIndex];
leftIndex++;
mergedIndex++;
}
while (rightIndex < rightLength) {
mergedArray[mergedIndex] = rightArray[rightIndex];
rightIndex++;
mergedIndex++;
}
return mergedArray;
}
}
Though merge sort does require additional memory compared to a few other sorting algorithms, it is still worth it as on the other hand it increases the speed and stability of the sort.
Merge sort is a good choice for many sorting applications.
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
Thanks for your feedback! If you have time, please provide details by selecting options below.
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!