Ok, i wrote 2 versions of this program. But im looking for the best solution – the most simple and fast one.
This is my solution but i was told that this solution is O(n*n) slower, which i dont know what really means. I was also told i could fasten it by breaking it into 2 functions, could anyone help me doing this?
void reverse3(char s[])
{
int l;
int i;
l = strlen(s);
if(l > 1)
{
reverse3(s + 1);
for(i = 1; i < l; i++)
{
int temp = s[i-1];
s[i-1] = s[i];
s[i] = temp;
}
}
}
You should swap the outermost bytes, i.e., i=1 and j=(l-1), then i=2, j=(l-2), etc. until i <= (j-1) (in other words, until either i=j, for an even number of characters, or i=j-1, for an odd number).
That will perform in O(n).
Recursion isn’t necessary, and “breaking it into two functions” doesn’t seem necessary either IMHO.
Ok, read your edit about this being part of the assignment.
In this case, you do need two functions to, as Jimmy said, preserve the parameter list of your “main” function.
The second function would be something like:
Please excuse my rusty C, I live in C#, VB.NET, and JavaScript now, some of the details escape me.
Also, I may or may not have left a bug in there, since this is homework. 😉