我正在尝试根据在线提供的各种教程实现Java中的Merge Sort,但我的结果列表具有重复值。经过多次调试后,我仍然无法找到实施中的错误。 以下是代码:
public ArrayList<Integer> mergeSort(ArrayList<Integer> whole)
{
ArrayList<Integer> left = new ArrayList<Integer>();
ArrayList<Integer> right = new ArrayList<Integer>();
int center;
if(whole.size() ==1 ) return whole;
else
{
center = whole.size()/2;
for(int i = 0; i < center; i++ )
{
left.add(whole.get(i));
}
for(int i = center ; i < whole.size(); i++ )
{
right.add(whole.get(i));
}
left = mergeSort(left);
right = mergeSort(right);
whole = merge(left, right, whole);
return whole;
}
}
private ArrayList<Integer> merge(ArrayList<Integer> left, ArrayList<Integer> right, ArrayList<Integer> whole)
{
// TODO Auto-generated method stub
int leftIn = 0;
int rightIn = 0;
int wholeIn = 0;
while( leftIn <left.size() && rightIn < right.size())
{
if(left.get(leftIn).compareTo(right.get(rightIn)) < 0)
{
whole.set(wholeIn, left.get(leftIn));
leftIn++;
}
else
{
whole.set(rightIn, right.get(rightIn));
rightIn++;
}
wholeIn++;
}
ArrayList<Integer> rest;
int restIn;
if(leftIn >= left.size())
{
rest = right;
restIn = rightIn;
}
else
{
rest = left;
restIn = leftIn;
}
for(int i = restIn ; i < rest.size(); i++)
{
whole.set(wholeIn, rest.get(i));
wholeIn++;
}
return whole;
}
输入清单:1 5 -2 98 -221 3 8 7
输出:-221 3 7 8 5 3 8 98
答案 0 :(得分:0)
您的merge
方法在rightIn
循环的else
情况下意外使用了错误的索引while
。这可能导致覆盖的值,表现为缺失值和重复值。
像wholeIn
案例一样使用if
。变化
whole.set(rightIn, right.get(rightIn));
到
whole.set(wholeIn, right.get(rightIn));