Class Mergesort
java.lang.Object
topics.sorting.mergesort.Mergesort
- All Implemented Interfaces:
SortingAlgorithm
Mergesort
A classic divide-and-conquer algorithm. It works by recursively breaking down an array into two halves until each sub-array consists of a single element, and then merging those sub-arrays back together in a strictly sorted order.
Algorithm Steps
- Divide: Find the midpoint of the array to divide it into two halves.
- Conquer: Recursively call Mergesort for the left and right halves.
- Combine (Merge): Merge the two sorted halves into a single sorted sequence using an auxiliary array.
Complexity Analysis
- Time Complexity:
O(N log N)strictly in all cases (Best, Average, Worst). - Space Complexity:
O(N)- Requires an auxiliary array of the same size as the input to merge elements securely. - Stability: Yes - Maintains the relative order of equal elements during the merge phase.
- Author:
- vicegd
- See Also:
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
Mergesort
public Mergesort()
-
-
Method Details
-
sort
public void sort(int[] elements) Description copied from interface:SortingAlgorithmSorts the elements in-place silently.- Specified by:
sortin interfaceSortingAlgorithm- Parameters:
elements- The array of integers to be sorted.
-
sort
public void sort(int[] elements, boolean trace) Description copied from interface:SortingAlgorithmSorts the elements in-place, optionally emitting step-by-step traces to visualize the algorithmic progression.- Specified by:
sortin interfaceSortingAlgorithm- Parameters:
elements- The array of integers to be sorted.trace- Iftrue, logs the internal state during execution.
-