归并排序:
将数组分为2块,再到每一小块再分为两块,直到最后一个元素为一块,然后进行有序数组合并,最终合并为一个有序数组
代码实现
public static void mergeSorts ( int[] array){
mergeSortsInternal(array,0,array.length)
//mergeSortsInternalNoR(array);
}
/**
* 归并排序:递归内部排序
*/
public static void mergeSortInternal ( int[] array, int low, int high){
if (low + 1 >= high) {//[low,high)
return;
}
int mid = (low + high) / 2;
mergeSortInternal(array, low, mid);
mergeSortInternal(array, mid, high);
merge(array, low, mid, high);
}
private static void merge ( int[] array, int low, int mid, int high){
int length = high - low;
int[] extral = new int[length];
//[low,mid]
//[mid,high]
int less = low;
int great = mid;
int i = 0;
while (less < mid && great < high) {
if (array[less] <= array[great]) {
extral[i] = array[less];
less++;
i++;
} else {
extral[i] = array[great];
great++;
i++;
}
}
while (less < mid) {
extral[i++] = array[less++];
}
while (great < high) {
extral[i++] = array[great++];
}
for (int j = 0; j < length; j++) {
array[low + j] = extral[j];
}
}