下面是一些评论。也看看这个视频,它可以帮助你了解发生了什么。要记住的主要是这是一个递归算法,所以你可以通过将其分解成更小的部分并在这些较小的部分上运行相同的算法来解决它。
static void sort(int[]array, int[] helper, int lower, int upper){
if(lower == upper){
// Lower == upper, this means there is only one element, so by definition this is sorted, nothing to do just return
return;
}
// Okay, we have more then one element if we are here. Our goal here is to sort both the upper half, and lower half independently first.
//
// First find the mid point between the upper and lower bounds we are sorting
// For example if we have an array [6, 5, 3, 1, 8, 7, 2, 4] with lower == 0 and upper == 7 then the mid point is 3
// Find the mid-point of lower and upper. This will be used to
int mid = lower + (upper - lower)/2;
// Now sort both the upper and lower half of the array recursively.
// Array will look like this to begin with [6, 5, 3, 1, 8, 7, 2, 4]
sort(array, helper, lower, mid);
// After sorting from 0 to 3 it will look like this
// [1, 3, 5, 6, 8, 7, 2, 4]
sort(array, helper, mid+1, upper);
// After sorting from 4 to 7 it will look like this
// [1, 3, 5, 6, 2, 4, 7, 8]
// Finally merge the two sorted arrays together. This is easier now the two halfs are sorted.
merge(array, helper, lower, mid+1, upper);
// After we have a sorted array
// [1, 2, 3, 4, 5, 6, 7, 8]
}
你不了解什么?它不工作吗?你的'merge()'方法在哪里? – Keppil
http://en.wikipedia.org/wiki/Merge_sort –