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.
1 Answer 1
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.
-
\$\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– stupidQuestions2020年11月04日 17:33:23 +00:00Commented Nov 4, 2020 at 17:33
-
\$\begingroup\$ Print the SUM of the digits, not the NUMBER of digits \$\endgroup\$Zachary Vance– Zachary Vance2020年11月06日 02:44:55 +00:00Commented Nov 6, 2020 at 2:44
System.Linq
is great when you want to do something with arrays or collectionsstring hello = "Hello World!"; string olleh = new string(hello.Reverse().ToArray());
Output:!dlroW olleH
. \$\endgroup\$