I thought of this algorithm today. It seems fast, but how can I know?
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
/*
* Reverse a string
* the caller has to free dynamic memory allocated
*/
char *mon_string_rev(char *string)
{
char *out = malloc ( strlen(string) + 1 );
assert(out);
int len = strlen(string);
int i;
int counter = 0;
int iterations = 0;
while(1) {
if(len < 0) break;
// important to only start counting after
// determing that the loop will continue
++iterations;
for(i = 0; i < len; i++) {
// if this is the last character
// push it onto the output string
if(i == (len - 1)) {
out[counter] = string[i];
counter++;
}
}
len--;
}
out[counter] = '\0';
printf("Total iterations: %d\n", iterations);
return out;
}
int main(int argc, char **argv)
{
if(argc < 2) {
fprintf(stderr, "Usage: %s <string>", argv[0]);
exit(1);
}
char *str = mon_string_rev(argv[1]);
printf("%s\n", str);
free(str);
return !1;
}
time ./myprogram "my irreversed string." time ./myotherpr "my irreversed string."
Employ a (e.g. bash) loop to call the program multiple times and compare the output. \$\endgroup\$