JavaAlgorithms/Sorts/MergeSort.java

89 lines
2.2 KiB
Java
Raw Normal View History

2018-11-14 01:15:47 +08:00
package Sorts;
/**
* Generic merge sort algorithm.
*
* @see SortAlgorithm
*/
class MergeSort implements SortAlgorithm {
2020-10-24 18:23:28 +08:00
/**
* Generic merge sort algorithm implements.
2020-10-24 18:23:28 +08:00
*
* @param unsorted the array which should be sorted.
* @param <T> Comparable class.
* @return sorted array.
2020-10-24 18:23:28 +08:00
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] unsorted) {
doSort(unsorted, 0, unsorted.length - 1);
return unsorted;
}
/**
* @param arr the array to be sorted.
* @param left the first index of the array.
* @param right the last index of the array.
2020-10-24 18:23:28 +08:00
*/
private static <T extends Comparable<T>> void doSort(T[] arr, int left, int right) {
if (left < right) {
int mid = (left + right) >>> 1;
2020-10-24 18:23:28 +08:00
doSort(arr, left, mid);
doSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
2020-10-24 18:23:28 +08:00
}
/**
* Merges two parts of an array.
2020-10-24 18:23:28 +08:00
*
* @param arr the array to be merged.
* @param left the first index of the array.
* @param mid the middle index of the array.
* @param right the last index of the array merges two parts of an array in increasing order.
2020-10-24 18:23:28 +08:00
*/
private static <T extends Comparable<T>> void merge(T[] arr, int left, int mid, int right) {
int length = right - left + 1;
@SuppressWarnings("unchecked")
2020-10-24 18:23:28 +08:00
T[] temp = (T[]) new Comparable[length];
int i = left;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= right) {
if (arr[i].compareTo(arr[j]) <= 0) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
2020-10-24 18:23:28 +08:00
while (i <= mid) {
temp[k++] = arr[i++];
}
2020-01-09 18:28:56 +08:00
2020-10-24 18:23:28 +08:00
while (j <= right) {
temp[k++] = arr[j++];
}
2020-10-24 18:23:28 +08:00
System.arraycopy(temp, 0, arr, left, length);
}
/** Driver code */
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
MergeSort mergeSort = new MergeSort();
2020-10-24 18:23:28 +08:00
Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12};
mergeSort.sort(arr);
for (int i = 0; i < arr.length - 1; ++i) {
assert arr[i] <= arr[i + 1];
}
2020-10-24 18:23:28 +08:00
String[] stringArray = {"c", "a", "e", "b", "d"};
mergeSort.sort(stringArray);
for (int i = 0; i < stringArray.length - 1; ++i) {
assert arr[i].compareTo(arr[i + 1]) <= 0;
}
2020-10-24 18:23:28 +08:00
}
}