c++ - Swapping elements in array recursively -


i've been trying swap elements store in array recursively.

my array stores list of upper , lower case letter using rand() below.

for (int = 0; < size; i++) {                alphabets[i] = (rand() % 26 + 65 + rand() % 2 * 32);           } 

the objective swap uppercase , lowercase elements , move lower case , uppercase left , right respectively

thi function meant swaps element recursively until (i == j) condition met.

void swapelementr(char alphabets[], int size) {     int temp;     int = 0;     int j = size - 1;      if(i == j)     {         return;     }     else      {         if (alphabets[i] >= 'a' && alphabets[i] <= 'z')         {             if (alphabets[j] >= 'a' && alphabets[j] <= 'z')             {                 temp = alphabets[i];                 alphabets[i] = alphabets[j];                 alphabets[j] = temp;                                 }             else                --j;                  }         else             ++i;                              }      swapelementr(alphabets, --size); } 

however, returning same array while swapping 1 alphabet instead. tried add , minus first , last array respectively until reaches base case of i=j while reducing size.

assumingly, swap works, call function , display using for-loop

void moveelementr(char alphabets[], int size) {      cout << "recursive swap of array" << endl;      swapelementr(alphabets, size);       (int = 0; < size; i++)     {         cout << alphabets[i] << "   ";     }      return;  } 

i think wanted algorithm (pseudo c-like language):

//input `array`, `i` (first char index) , `j` (last char index). void recursion(char array[], int i, int j) {     if (j <= i) return; // no more chars process     if (array[i] in [a-z]) {         recursion(array, i+1, j); // [i] lower case, skip         return;     }     if (array[j] in [a-z]) {         recursion(array, i, j-1); // [j] upper case, skip         return;     }     // here [i] upper case , [j] lower case -> swap them     swap(array[i], array[j]);     recursion(array, i+1, j-1); // resolve characters between swapped ones }  cout << recursion("abcde", 0, 4); // should produce "dcbae" 

btw, forgot add "return" after "skip it" parts on first try, abusive usage of recursion, had check code twice catch that. should debug original code, if want less rusty. if want stay rusty, hire programmer.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -