1
\$\begingroup\$

I am trying to learn recursion and have a question involving an array that needs to be reversed. I am focusing on c# but the language probably doesn't matter a whole lot because my function is not using any libraries.

Here is my code:

char[] ReverseString(char[] s, int i = 0)
{
    char[] x = s;
    char temp = s[i];
    s[i] = s[s.Length - (i + 1)];
    s[s.Length - (i + 1)] = temp;

    i++;
    if (i < (s.Length) / 2)
    {
        ReverseString(s, i);
    }
    return x;
}

Any suggestions on how I should improve my function (maybe time complexity or using libraries (nuget packages)) is appreciated as well.

\$\endgroup\$
2
  • \$\begingroup\$ The same problem has been address many times: 1, 2, 3, etc... \$\endgroup\$ – Peter Csala Nov 4 '20 at 9:51
  • \$\begingroup\$ Tip: System.Linq is great when you want to do something with arrays or collections string hello = "Hello World!"; string olleh = new string(hello.Reverse().ToArray()); Output: !dlroW olleH. \$\endgroup\$ – aepot Nov 6 '20 at 18:40
4
\$\begingroup\$

Honestly, this is not a very good problem to do recursively, just pick another problem. Here's a better one: take in an integer, and print the sum of the digits.

Some general feedback:

  • ReverseString returns something, but you ignore its return value
  • You make x, but it's a shallow copy of s -- modifying x and s do the same thing, and returning them would do the same thing. Just don't declare 'x' at all.
  • See how short you can make this. It's not good general advice, but it can be good advice when learning recursion.

One last tip when learning recursion: next time, try to do it without modifying a single variable. Just use expressions and return values. Again, it's not always how you should write real code, but it will help you learn faster.

\$\endgroup\$
2
  • \$\begingroup\$ Thanks I am following a guide on LeetCode and this was the first problem they gave but I will try printing the amount of digits in an int. (I have done this but not recursively). But could you explain your first point about ignoring the return value? \$\endgroup\$ – stupidQuestions Nov 4 '20 at 17:33
  • \$\begingroup\$ Print the SUM of the digits, not the NUMBER of digits \$\endgroup\$ – Zachary Vance Nov 6 '20 at 2:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.