我试图实现合并排序,但我不确定错误是什么。我确定我的逻辑没问题,但我搞砸了索引。非常感谢一些反馈:
public static void mergeSort(long[] arr, int low, int high) {
if (low < high) {
int mid = (high + low) / 2;
mergeSort(arr, low, mid);
mergeSort(arr, mid+1, high);
merge(arr, low, mid, high);
}
}
public static void merge(long[] arr, int low, int mid, int high) {
long[] tmp = new long[arr.length];
//System.out.println((high-low+1)==arr.length);
System.arraycopy(arr, 0, tmp, 0, arr.length);
int i = low;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= high) {
if (tmp[i] <= tmp[j]) {
arr[k] = tmp[i];
i++;
} else {
arr[k] = tmp[j];
j++;
}
k++;
}
while (i <= mid) {
arr[k] = tmp[i];
i++;
k++;
}
while (j <= high) {
arr[k] = tmp[j];
j++;
k++;
}
}