时间复杂度:O(NlogN) 空间复杂度:O(N)
public void merge(int[] array, int left, int mid, int right) {
int length = right - left + 1;
int[] tmp = new int[length];
int i = left, j = mid + 1, index = 0;
while (i <= mid && j <= right) {
if (array[i] <= array[j]) {
tmp[index++] = array[i++];
} else {
tmp[index++] = array[j++];
}
}
while (i <= mid) {
tmp[index++] = array[i++];
}
while (j <= right) {
tmp[index++] = array[j++];
}
for (i = 0; i < length; i++) {
array[left++] = tmp[i];
}
}
public void mergeSort(int[] array, int left, int right) {
if (left >= right) {
return;
}
int mid = (left + right) / 2;
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, mid, right);
}