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.
As stated in the comments, I would suggest to pass a modified
startas an offset into the array in order to get rid of the static variablei. I would also replace theswapwith the built-instd::swapversion.