I wrote an isPermute
method. Can I get some tips and advice on better coding style?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
bool isPermute(char*, char*);
char* sort(char*);
int main(int argv, char **argc)
{
printf("%s and %s are %spermutations of each other. \n", argc[1], argc[2], isPermute(argc[1], argc[2]) ?
"" : "not ");
return 0;
}
bool isPermute(char* s1, char* s2)
{
int size1 = strlen(s1);
int size2 = strlen(s2);
//default cases
if((size1 != size2) || (size1 == 0) || (size2==0))
return false;
if(strcmp(sort(s1), sort(s2)))
return false;
else
return true;
}
char* sort(char* str1)
{
int d=0, size = strlen(str1);
char character;
char *original = str1;
char *result = (char *)malloc(size);
for ( character = 'a' ; character <= 'z' ; character++ )
{
int i;
for ( i = 0 ; i < size ; i++ )
{
if ( str1[i] == character )
{
result[d] = str1[i];
d++;
}
}
str1 = original;
}
return result;
}
int argc, char** argv
? as in argcount, and arg value? \$\endgroup\$qsort
, a standard library sorting function, for sorting characters in a string in O(n log n) time. Or you may prepare two arrays of character counters (constant time), scan both strings to count characters' repetitions (linear time) and compare corresponding counters (constant time)... \$\endgroup\$qosrt
is not O(n log n). It has a O(n^2) worst case behavior. \$\endgroup\$qsort
is thousand times that of linear scan,qsort
will still be faster (except the rare worst case) for strings up to about 60 thousand characters. \$\endgroup\$