I cannot wrap my mind around doing this logically. I have mapped out all possibilities for sorting and based my algorithm on that.
ABC
ACB
BAC
BCA
CAB
CBA
Only six possible combinations for 3 strings, and so, I thought it a very quick and easy solution to hardcode this with conditionals. See code;
char str1[x]; // where x is some constant value
char str2[x];
char str3[x];
char temp[x];
if (strcmp(str1, str2) > 0)
{
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
else if (strcmp(str2, str3) > 0)
{
strcpy(temp, str2);
strcpy(str2, str3);
strcpy(str3, temp);
}
else if (strcmp(str1, str3) > 0)
{
strcpy(temp, str1);
strcpy(str1, str3);
strcpy(str3, temp);
}
Essentially I would like to take any variation of ABC for example and sort it to ABC. i.e. BAC -> ABC, CAB -> ABC.
You're very close. Your biggest problem is those else
s. By using else if
you're ensuring that at most one of your if
blocks can run, which means that there are four possible paths you can take through the code — the first block runs, or the second block runs, or the third block runs, or none of them run. But that can't be correct, since you pointed out yourself that there are six cases to account for.
Second, you have a slight ordering problem, which can be solved by exchanging your second and third blocks.
If you make both of those changes, you should have something that works. By first swapping str1
with str2
if needed, then swapping str1
and str3
if needed, you ensure that the smallest value ends up in str1
, and only the two higher values remain in str2
and str3
(in unknown order). Then, by swapping str2
with str3
if needed, you ensure that those two are in the right order as well, therefore the whole thing must be in order.