我正在创建一个Java程序,其中实现了MergeSort算法。我的代码是下面的(迄今为止):Java中MergeSort实现中的错误反转和重复数字
public void merge(Integer [] left, Integer[] right, Integer[] a) {
int i = 0; // a[] index (A)
int lIndex = 0; // left[] index (B)
int rIndex = 0; // right[] index (C)
// Begin main merge process
while((lIndex < left.length) && (rIndex < right.length)) {
if(left[lIndex] <= right[rIndex]) {
a[i] = left[lIndex]; // Store it
lIndex++; // Increase index of left[]
}
else {
a[i] = right[rIndex]; // Store it
rIndex++; // Increase index of right[]
}
i++; // Increase index of a[]
}
if(i == lIndex) { // If the left array is sorted
while(rIndex < right.length) { // Copy the contents of rhe right array to a[]
a[i] = right[rIndex];
i++;
rIndex++;
}
}
else { // If the right array is sorted
while(lIndex < left.length) { // Copy the contents of the left array to a[]
a[i] = left[lIndex];
i++;
lIndex++;
}
}
}
的问题是,每一次执行该功能时,输入数组返回部分排序。我的意思是大多数元素都处于正确的位置,但有一两个是错误的,还有一些是其他元素的重复。由于我看不到真正的问题,谁能帮我吗?该实现是一个小课程,我不能使用int [](比方说)而不是Integer [],以便使用Arrays.copyOf()方法复制数组A []的内容。预先感谢,请原谅我的语法/拼写错误。
请注意,输入数组总是2的幂(2,4,8,16等),所以每次我除以2找到中间元素的索引时,我总是得到一个偶数。
非常感谢,解决了这个问题!原来,这是我从书中研究的MergeSort的伪代码的误解。 – Lefteris008