你好所以我正在做合并排序,我认为一切都是正确的,我只是在使用 merge_sort 函数的最后两行时遇到了困难......在倒数第二行它说“整数无法解析为变量, ArrayList 无法解析为变量,类型不匹配:无法从 ArrayList 转换为 int[]。” 最后一行说:“类型不匹配无法从 int[] 转换为 ArrayList。” 我怎样才能解决这个问题?任何帮助是极大的赞赏!!
public static ArrayList<Integer> merge_sort(ArrayList<Integer> B)
{
if (B.size() <= 1)
System.out.println(B);
int midpoint = B.size()/2;
ArrayList<Integer> left = new ArrayList<Integer>(midpoint);
ArrayList<Integer> right;
if(B.size() % 2 == 0)
right = new ArrayList<Integer>(midpoint);
else
right = new ArrayList<Integer>(midpoint + 1);
int[] result = new int[B.size()];
for (int i = 0; i < midpoint; i++)
left.set(i, B.get(i));
int x = 0;
for (int j = midpoint; j < B.size(); j++)
{
if(x < right.size())
right.set(x, B.get(j));
x++;
}
left = merge_sort(left);
right = merge_sort(right);
result = merge(left, right);
return result;
}
public static ArrayList<Integer> merge(ArrayList<Integer> left, ArrayList<Integer> right)
{
int lengthResult = left.size() + right.size();
ArrayList<Integer> result = new ArrayList<Integer>(lengthResult);
int indexL = 0;
int indexR = 0;
int indexRes = 0;
while (indexL < left.size() || indexR < right.size())
{
if(indexL < left.size() && indexR < right.size())
{
if (left.get(indexL) <= right.get(indexR))
{
result.set(indexRes, left.get(indexL));
indexL++;
indexRes++;
}
else
{
result.set(indexRes, right.get(indexR));
indexR++;
indexRes++;
}
}
else if (indexL < left.size())
{
result.set(indexRes, left.get(indexL));
indexL++;
indexRes++;
}
else if (indexR < right.size())
{
result.set(indexRes, right.get(indexR));
indexR++;
indexRes++;
}
}
return result;
}