Here I have some code that will run a program that generates a bunch of lowercase and uppercase letters from length 15-25 and will swap it first using an iterative swap method. It will then generate a second set of letters and will swap it this time with a recursive function.
How do I convert this iterative swap to a recursive swap guys? thanks.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
const int MAXSIZE = 25;
void ConstructArray (char [], int);
void printArray (const char [], int);
void iterativeSwap (char [], int);
void recursiveSwap (char [], int, int, int);
int main ()
{
char myArray [MAXSIZE], myArrayR [MAXSIZE];
static int left = 0;
static int right;
srand (time(NULL));
int randomSize = rand() % 11 + 15;
int randomSizeR = rand() % 11 + 15;
right = randomSizeR - 1;
ConstructArray (myArray, randomSize);
printArray (myArray, randomSize);
iterativeSwap (myArray, randomSize);
ConstructArray (myArrayR, randomSizeR);
printArray (myArrayR, randomSizeR);
recursiveSwap(myArrayR, randomSizeR, left, right);
}
void ConstructArray (char myArray [], int randSize)
{
char randUppcase, randLowcase;
int randDuty;
for (int i = 0; i < randSize; i++)
{
randDuty = rand() % 2 + 1;
randUppcase = rand() % 26 + 65;
randLowcase = rand() % 26 + 97;
if (randDuty == 1)
randDuty = randUppcase;
else
randDuty = randLowcase;
myArray [i] = randDuty;
}
}
void printArray (const char myArray [], int randSize)
{
cout << "Given the following array " << endl;
for (int i = 0; i < randSize; i++)
cout << myArray[i] << "\t";
cout << endl;
}
void iterativeSwap (char myArray [], int randSize)
{
int i = 0;
int j = randSize - 1;
while (i != j)
{
if (myArray[i] >= 'A' && myArray[i] <= 'Z')
{
if (myArray[j] >= 'a' && myArray[j] <= 'z')
{
swap(myArray[i],myArray[j]);
}
else
--j;
}
else
++i;
}
cout << "Iterative Swap" << endl;
for(int i = 0; i < randSize; i++)
cout << myArray[i] << "\t";
cout << endl;
}
void recursiveSwap(char myArrayR[], int randSizeR, int left, int right)
{
if (left == right)
return;
else
{
recursiveSwap(&myArrayR[left], NULL, left +1, NULL);
if (myArrayR[left] >= 'A' && myArrayR[left] <= 'Z')
{
recursiveSwap(&myArrayR[right], NULL, right -1, NULL);
if (myArrayR[right] >= 'a' && myArrayR[right] <= 'z')
swap (left, right);
}
}
cout << "Recursive Swap" << endl;
for(int i = 0; i < right; i++)
cout << myArrayR[i] << "\t";
cout << endl;
return;
}