我的合并排序算法的输入数组在随机位置有随机0:
import java.util.*;
import java.lang.*;
class MRS
{
public static int [] A = new int [8];
public static int [] workArray = new int [8];
public static void mergeSort(int left, int right)
{
if (left < right)
{
int middle = (left + right) / 2;
mergeSort(left, middle);
mergeSort(middle+1, right);
Merge(left, middle, right);
}
}
public static void Merge(int left, int mid, int right)
{
int leftIterator = left;
int rightIterator = mid+1;
int workArrayIterator = left;
//for (int j = 0; j < 8; j++) System.out.print(A[j] + " ");
while (leftIterator <= mid && rightIterator < right)
{
if (A[leftIterator] <= A[rightIterator])
{
workArray[workArrayIterator] = A[leftIterator];
leftIterator++;
}
else
{
workArray[workArrayIterator] = A[rightIterator];
rightIterator++;
}
workArrayIterator++;
}
while (leftIterator <= mid)
{
workArray[workArrayIterator] = A[leftIterator];
leftIterator++;
workArrayIterator++;
}
/*while (rightIterator < right)
{
workArray[workArrayIterator] = A[rightIterator];
rightIterator++;
workArrayIterator++;
}*/
for (int i = left; i < right; i++) A[i] = workArray[i];
}
public static void main (String[] a)
{
for (int i = 0; i < 8; i++) A[i] = (int)(Math.random()*50);
//for (int j = 0; j < 8; j++) System.out.print(A[j] + " ");
mergeSort(0, 8);
for (int j = 0; j < 8; j++) System.out.print(A[j] + " ");
}
}
上面的最后一行首先输出正确的数字,但迭代后迭代,数组填充0到75%0s的点。只是澄清一下,该行仅用于调试目的,因为我一直将所有0作为此算法的输出。
我尝试将main()中的本地数组作为参数传递给mergeSort和Merge - &gt;全0
我尝试过使用全局类数组 - &gt;全0或随机0
如果您希望我发布其余代码(大约25行),请告诉我。
感谢您的所有建议。
编辑:在检查我的迭代器后,我发现了一个问题并修复了它,所以我不再得到全0了。但是,我没有得到完全排序的数组。有些整数仍然不合适。