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.
#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 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;
ConstructArray (myArray, randomSize);
printArray (myArray, randomSize);
iterativeSwap (myArray, randomSize);
ConstructArray (myArrayR, randomSizeR);
printArray (myArrayR, randomSizeR);
recursiveSwap(myArrayR, 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 myArray[], int left, int right)
{
if (left >= right)
return;
swap(myArray[left], myArray[(left + right) / 2]);
int last = left;
for (int i = left+1; i < right; ++i)
if (myArray[i] > myArray[left])
swap(myArray[i], myArray[++last]);
swap(myArray[left], myArray[last]);
recursiveSwap(myArray, left, last-1);
recursiveSwap(myArray, last+1, right);
cout << "Recursive Swap" << endl;
for(int i = 0; i < right; i++)
cout << myArray[i] << "\t";
cout << endl;
return;
}
Now can someone help me with the recursive code as I'm not exactly sure whats wrong with it or how it works in-depth.
problematic code section:
void recursiveSwap(char myArray[], int left, int right)
{
if (left >= right)
return;
swap(myArray[left], myArray[(left + right) / 2]);
int last = left;
for (int i = left+1; i < right; ++i)
if (myArray[i] > myArray[left])
swap(myArray[i], myArray[++last]);
swap(myArray[left], myArray[last]);
recursiveSwap(myArray, left, last-1);
recursiveSwap(myArray, last+1, right);
cout << "Recursive Swap" << endl;
for(int i = 0; i < right; i++)
cout << myArray[i] << "\t";
cout << endl;
return;
}