我的数组合并排序器不能正常处理包含一些重复值的数组的奇数长度
My Array merge sorter does not work properly with odd number length of the array that includes some duplicate values
我的数组合并排序器无法正常处理包含一些重复值的奇数长度数组。例如,对于 int[] array = {1, 3, 15, 3, 7, 9, 8, 15, 0}
,结果是 {0, 1, 3, 3, 7, 8, 0, 9, 15,}
。谁能告诉我哪里错了?
public static void mergeSort(int[] inputArray) {
int size = inputArray.length;
if (size < 2)
return;
int mid = size / 2;
int leftSize = mid;
int[] left = Arrays.copyOfRange(inputArray, 0, leftSize);
int[] right = Arrays.copyOfRange(inputArray, leftSize, inputArray.length);
mergeSort(left);
mergeSort(right);
merge(left, right, inputArray);
}
public static void merge(int[] left, int[] right, int[] arr) {
int leftSize = left.length;
int rightSize = right.length;
int i = 0, j = 0, k = 0;
while (i < leftSize && j < rightSize) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}
while (i < leftSize) {
arr[k++] = left[i++];
}
while (j < leftSize) {
arr[k++] = right[j++];
}
}
改变这个
while (j < leftSize) {
arr[k++] = right[j++];
}
至
while (j < rightSize) {
arr[k++] = right[j++];
}
我的数组合并排序器无法正常处理包含一些重复值的奇数长度数组。例如,对于 int[] array = {1, 3, 15, 3, 7, 9, 8, 15, 0}
,结果是 {0, 1, 3, 3, 7, 8, 0, 9, 15,}
。谁能告诉我哪里错了?
public static void mergeSort(int[] inputArray) {
int size = inputArray.length;
if (size < 2)
return;
int mid = size / 2;
int leftSize = mid;
int[] left = Arrays.copyOfRange(inputArray, 0, leftSize);
int[] right = Arrays.copyOfRange(inputArray, leftSize, inputArray.length);
mergeSort(left);
mergeSort(right);
merge(left, right, inputArray);
}
public static void merge(int[] left, int[] right, int[] arr) {
int leftSize = left.length;
int rightSize = right.length;
int i = 0, j = 0, k = 0;
while (i < leftSize && j < rightSize) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}
while (i < leftSize) {
arr[k++] = left[i++];
}
while (j < leftSize) {
arr[k++] = right[j++];
}
}
改变这个
while (j < leftSize) {
arr[k++] = right[j++];
}
至
while (j < rightSize) {
arr[k++] = right[j++];
}