归并排序实现简单,但是应用场景你会吗?
互联网侦察
共 656字,需浏览 2分钟
·
2021-11-10 00:17
前言
实现
public static void innerMergeSort(int[] arr, int start, int end) {
int mid = (end - start) / 2 + start;
if(start < mid) {
innerMergeSort(arr, start, mid);
}
if(mid + 1 < end) {
innerMergeSort(arr, mid + 1, end);
}
int[] tmp = new int[end - start + 1];
int index = 0, index1 = start, index2 = mid + 1;
while(index1 <= mid && index2 <= end) {
if(arr[index1] <= arr[index2]) {
tmp[index++] = arr[index1++];
} else {
tmp[index++] = arr[index2++];
}
}
while(index1 <= mid) {
tmp[index++] = arr[index1++];
}
while(index2 <= end) {
tmp[index++] = arr[index2++];
}
for(int i = 0; i < end - start + 1; i++) {
arr[start + i] = tmp[i];
}
}
public static void mergeSort(int[] arr) {
innerMergeSort(arr, 0, arr.length - 1);
}
应用
练习题
评论