【发布时间】:2015-04-08 15:06:05
【问题描述】:
我正在实现一个合并排序功能。我理解分而治之的逻辑,但实际的合并部分让我感到困惑。这是一个过去的家庭作业问题,但我正在努力理解它。
/**
* Implement merge sort.
*
* It should be:
* stable
* Have a worst case running time of:
* O(n log n)
*
* And a best case running time of:
* O(n log n)
*
* You can create more arrays to run mergesort, but at the end,
* everything should be merged back into the original T[]
* which was passed in.
*
* ********************* IMPORTANT ************************
* FAILURE TO DO SO MAY CAUSE ClassCastException AND CAUSE
* YOUR METHOD TO FAIL ALL THE TESTS FOR MERGE SORT
* ********************************************************
*
* Any duplicates in the array should be in the same relative position
* after sorting as they were before sorting.
*
* @throws IllegalArgumentException if the array or comparator is null
* @param <T> data type to sort
* @param arr the array to be sorted
* @param comparator the Comparator used to compare the data in arr
*/
对于此方法,参数、public、static 和 generics 不能更改。我不知道如何做递归合并功能。
public static <T> void mergesort(T[] arr, Comparator<T> comparator) {
if (arr == null || comparator == null) {
throw new IllegalArgumentException("Null arguments were passed.");
}
if (arr.length >= 2) {
//Midpoint from which we will split the array.
int middle = arr.length / 2;
//Each half of the split array
T[] left = (T[]) new Object[middle];
T[] right = (T[]) new Object[arr.length - middle];
//Copy items from original into each half
for (int i = 0; i < middle; i++) {
left[i] = arr[i];
}
for (int i = middle; i < length; i++) {
right[i] = arr[i];
}
//Keep splitting until length is 1
mergesort(left, comparator);
mergesort(right, comparator);
//merge each array back into original which would now be sorted.
merge(left, right, middle, arr, comparator);
merge(right, middle, arr, comparator);
}
}
private static <T> T[] merge(T[] left, T[] right, int middle, T[] arr,
Comparator<T>
comparator) {
int i = 1, j = middle + 1, k = 1;
while (i <= middle && j <= arr.length) {
arr[k++] = (comparator.compare(arr[k], partioned[i]) < 0)
? arr[j++] : partioned[i++];
}
while (i <= middle) {
arr[k++] = partioned[k++];
}
}
【问题讨论】:
-
在不涉及合并排序实现的细节的情况下,您的私有合并逻辑不是递归的,因此您可以在您的公共方法中实现它。
标签: java generics recursion mergesort