Program for Merge Sort in Java is one of the most widely used and efficient algorithms. Merge sort is based on the divide and conquer technique which involves dividing a given problem into multiple subproblems and solving each subproblem independently. When the subproblems are solved, we combine their results to get the final solution to the problem. Merge sort algorithm can be implemented using recursion as it involves working with subproblems rather than the main problem.
Let us consider an unsorted array that needs to be sorted using the merge sort algorithm. Here are the steps involved in sorting an array with values: 18, 8, 4, 13, 10, 12, 7, and 11:
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Here is a code example showing the implementation of merge sort in java:
Code:
package com.edubca.sorting; public class MergeSort { private int[] array; private int[] tempMergedArr; private int length; public static void main(String a[]){ int[] inputArr = {18, 8, 4, 13, 10, 12, 7, 11}; MergeSort mergeSort = new MergeSort(); mergeSort.sort(inputArr); for(int i:inputArr){ System.out.print(i + " "); } } public void sort(int inputArr[]) { this.array = inputArr; this.length = inputArr.length; this.tempMergedArr = new int[length]; performMergeSort(0, length - 1); } private void performMergeSort(int lowerIndex, int higherIndex) { if (lowerIndex < higherIndex) { int middle = lowerIndex + (higherIndex - lowerIndex) / 2; // Sort the left side of the array call performMergeSort recursively performMergeSort(lowerIndex, middle); // Sort the right side of the array call performMergeSort recursively performMergeSort(middle + 1, higherIndex); // Merge subparts using a temporary array mergeData(lowerIndex, middle, higherIndex); } } private void mergeData (int lowerIndex, int middle, int higherIndex) { for (int i = lowerIndex; i <= higherIndex; i++) { tempMergedArr[i] = array[i]; } int i = lowerIndex; int j = middle + 1; int k = lowerIndex; while (i <= middle && j <= higherIndex) { if (tempMergedArr[i] <= tempMergedArr[j]) { array[k] = tempMergedArr[i]; i++; } else { array[k] = tempMergedArr[j]; j++; } k++; } while (i <= middle) { array[k] = tempMergedArr[i]; k++; i++; } } }
The above code will produce a sorted array as output.
Output:
Merge sort can be used in the following scenarios:
Below points analysis complexity of merge sort:
Below points compare merge sort with other algorithms:
The article concludes that the merge sort is an important concept to understand when it comes to algorithms.
Atas ialah kandungan terperinci Program untuk Merge Sort dalam Java. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!