Swap alternate elements in an array using recursion?

79 views Asked by At

I wrote the below code to swap alternate elements in an array {eg. (1,2,3,4,5)-->(2,1,4,3,5) }. I wanted to try it using recursion.

#include <iostream>
using namespace std;

void print(int *a, int n)
{
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
    cout << endl;
}

void swap(int *x, int *y) //swaps two elements
{
    int temp = *x;
    *x = *y;
    *y = temp;
}

void swapAlter(int *a, int n) //swaps elements in an array
{
    static int i;
    if (i >= n - 1)
        return;
    else
    {
        swap(&a[i], &a[i + 1]);
        i += 2;
        swapAlter(a, n);
    }
}

//driver code
int main()
{

    int a[] = {7, 4, 5, 6, 21, 2, 9};
    int size = sizeof(a) / sizeof(a[0]);
    cout << "normal array--> ";
    print(a, size);
    cout << endl;
    swapAlter(a, size);
    cout << "updated array--> ";
    print(a, size);
    cout << endl;
    return 0;
}


the above code works just fine but i was wondering if there is a recursive approach possible (i'm sure it definitely is) to do the same without using static variable.

1

There are 1 answers

0
André On

As stated in the comments, I would suggest to pass a modified start as an offset into the array in order to get rid of the static variable i. I would also replace the swap with the built-in std::swap version.

#include <iostream>
#include <algorithm> // for std::swap
using namespace std;

void print(int *a, int n)
{
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
    cout << endl;
}

void swapAlter(int *start, int *end) //swaps elements in an array
{
    if (start+1 < end)
    {
        swap(*start, *(start+1));
        swapAlter(start+2, end);
    }
}

//driver code
int main()
{

    int a[] = {7, 4, 5, 6, 21, 2, 9};
    int size = sizeof(a) / sizeof(a[0]);
    cout << "normal array--> ";
    print(a, size);
    cout << endl;
    swapAlter(a, a+size);
    cout << "updated array--> ";
    print(a, size);
    cout << endl;
    return 0;
}