Merge Sort in Java
1 min readApr 18, 2021
Merge sort is the algorithm which follows divide and conquer approach. Consider an array A of n number of elements. The algorithm processes the elements in 3 steps.
- If A Contains 0 or 1 elements then it is already sorted, otherwise, Divide A into two sub-array of equal number of elements.
- Conquer means sort the two sub-arrays recursively using the merge sort.
- Combine the sub-arrays to form a single final sorted array maintaining the ordering of the array.
The main idea behind merge sort is that, the short list takes less time to be sorted.
Complexity
ComplexityBest caseAverage CaseWorst CaseTime ComplexityO(n log n)O(n log n)O(n log n)Space ComplexityO(n)
Example :
Consider the following array of 7 elements. Sort the array by using merge sort.
- A = {10, 5, 2, 23, 45, 21, 7}
https://www.tutorialandexample.com/merge-sort-in-java/
https://www.tutorialandexample.com/bubble-sort-in-java/
https://www.tutorialandexample.com/how-to-run-java-program-in-command-prompt/