我正在創建一個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