我正在尝试根据第 0 个索引的值对 2D 数组进行排序。我尝试稍微修改一下合并排序,但我遇到了这个问题,在调用该函数后,仅将第一个元素复制到所有索引。
public static void mergeSort(long arr[][], int s, int e) {
if (s < e) {
int mid = s + (e - s) / 2;
mergeSort(arr, s, mid);
mergeSort(arr, mid + 1, e);
merge(arr, s, mid, e);
}
}
public static void merge(long arr[][], int s, int mid, int e) {
int n1 = mid - s + 1, n2 = e - mid;
long left[][] = new long[n1][2];
long right[][] = new long[n2][2];
for (int i = 0; i < n1; i++) {
left[i] = arr[i];
}
for (int i = 0; i < n2; i++) {
right[i] = arr[i + n1];
}
int i = 0, j = 0, k = s;
while (i < n1 && j < n2) {
if (left[i][0] < right[j][0])
arr[k++] = left[i++];
else
arr[k++] = right[j++];
}
while (i < n1) {
arr[k++] = left[i++];
}
while (j < n2) {
arr[k++] = left[j++];
}
}
public static void main(String[] args) {
long arr[][] = { { 1, 4 }, { 3, 6 }, { 8, 4 }, { 7, 7 } };
mergeSort(arr, 0, 3);
for (int i = 0; i < 4; i++) {
System.out.println(arr[i][0] + " " + arr[i][1]);
}
}
代码中的主要问题是
merge
方法中临时数组的初始化不正确:您必须在arr
中使用移位索引:
for (int i = 0; i < n1; i++) {
left[i] = arr[s + i];
}
for (int i = 0; i < n2; i++) {
right[i] = arr[m + 1 + i];
}