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.

pacmaninbw
26.2k13 gold badges47 silver badges113 bronze badges
asked Nov 3, 2020 at 20:30
\$\endgroup\$
2
  • \$\begingroup\$ The same problem has been address many times: 1, 2, 3, etc... \$\endgroup\$ Commented Nov 4, 2020 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\$ Commented Nov 6, 2020 at 18:40

1 Answer 1

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.

answered Nov 4, 2020 at 4:34
\$\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\$ Commented Nov 4, 2020 at 17:33
  • \$\begingroup\$ Print the SUM of the digits, not the NUMBER of digits \$\endgroup\$ Commented Nov 6, 2020 at 2:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.