以下方法必须以递归方式交换整数数组中的所有值。我必须使用辅助方法reverse()
。我该怎么做?这个问题的基本情况是什么?我尝试将其设置为start <= count
,start == count/2
和start >= count
,但是它们都没有起作用。
Start是要交换的值的索引,count是数组中元素的数量
public void reverse()
{
reverseRecurse(list, 0, count);
}
private void reverseRecurse(int[] list, int start, int count)
{
if (start >= count/2)
{
int temp = list[start];
list[start] = list[count];
list[count] = temp;
}
else
{
reverseRecurse(list, ++start, --count);
}
}
最佳答案
尝试这个:
public void reverse()
{
reverseRecurse(list, 0, count-1); // count - 1 is index of last element
}
private void reverseRecurse(int[] list, int start, int end)
{
if (start < end)
{
int temp = list[start];
list[start] = list[end];
list[end] = temp;
reverseRecurse(list, start + 1, end - 1);
}
}
按索引进行比较容易,所以我使用
start
和end
。