递归反转数组

Ang*_*gad 1 c++ recursion

我试图递归地反转数组的元素。我可以在函数中拥有的唯一参数是数组和大小。这是我到目前为止所做的,但在交换时遇到了麻烦。如何修复我的输出?例如,当我输入 1 2 3 时,元素会反转为 2 3 1

//Recursive function for Reversing array
void reverse_arr(int a[],int size){
    if(size ==0){
        return ;
    }
    else{
        int temp;
        int i= 0;
        temp = a[i];
        a[i]= a[size-1];
        a[size -1] = temp;
        reverse_arr(a, size-1);
    }      
}

int main() {
    int a[100];
    int size ;

    cout<<"Enter the size of the array: "<<endl;
    cin>>size;
    cout<<"Enter the elements of the array: "<<endl;
    for(int i = 0; i<size; i++){
        cin>>a[i]; }
    for(int i = 0; i<size; i++){

        cout<<a[i]<<"  ";}
    cout<<endl;
    reverse_arr(a, 3);
    for(int i = 0; i<size; i++){

        cout<<a[i]<<"  ";}
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 5

总是交换第一个和最后一个元素不会做你想要的。如果您的数组最初是1 2 3 4 5,这里是每个递归步骤的交换序列:

  • 交换045 2 3 4 1
  • 交换034 2 3 5 1
  • 交换023 2 4 5 1
  • 交换012 3 4 5 1

在递归算法中,每个递归步骤都应该在较小的数据集上解决相同的问题,并将其与我们迄今为止所做的相结合,以更接近所需的结果。但是交换第一个和最后一个只有在它们与原始顺序相同时才是正确的,在每个步骤之后都不是这样。

交换数组的第一个和最后一个元素后,您需要在数组的中间递归,而不仅仅是与size - 1. 因此,您需要在从第二个元素开始的数组上递归调用该函数,并从 中减去 2 size

您什么都不做的基本情况应该是 when size <= 1,因为当您反转它时,1 元素数组是相同的。

//Recursive function for Reversing array
void reverse_arr(int a[],int size){
    if(size <= 1 ){
        return ;
    }
    else{
        int temp;
        int i= 0;
        temp = a[i];
        a[i]= a[size-1];
        a[size -1] = temp;
        reverse_arr(&a[1], size-2);
    }
}
Run Code Online (Sandbox Code Playgroud)