归并排序:先将大的序列分为若干个小的序列,得到答案后再将答案合并,递归深度为 log n 。
实现:
public void mergeSort(int[] array, int start, int end, int temp[]) {
if (start >= end) {
return;
}
mergeSort(array, start, (start + end) / 2, temp);
mergeSort(array, (start + end) / 2 + 1, end, temp);
merge(array, start, end, temp);
}
public void merge(int[] array, int start, int end, int[] temp) {
int middle = (start + end) / 2;
int left = start;
int right = middle + 1;
int index = left;
while (left <= middle && right <= end) {
if (array[left] < array[right]) {
temp[index++] = array[left++];
} else {
temp[index++] = array[right++];
}
}
while (left <= middle) {
temp[index++] = array[left++];
}
while (right <= end) {
temp[index++] = array[right++];
}
for (int i = start; i <= end; i++) {
array[i] = temp[i];
}
}
如果对您有帮助,请点赞关注支持我,谢谢!❤
如有错误或者不足之处,敬请指正!❤
个人主页:星不易 ❤
算法通关村专栏:不易|算法通关村 ❤