I searched on the internet for an algorithm for permutations in C and I found the following function:
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf("%s\n", a);
else
{
for (i = l; i <= r; i++)
{
swap((a + l), (a + i));
permute(a, l + 1, r);
swap((a + l), (a + i)); //backtrack
}
}
}
The link to the page is: https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
The function looks elegant and short but quite frankly, I don't understand how it works, so I decided to implement my own understanding of the problem and came up with the following code:
#include <stdio.h>
#include <string.h>
void fn(char *str, int k, int n);
int main(void)
{
char str[] = "abcd";
fn(str, strlen(str), strlen(str));
return 0;
}
void swap(char *a, char *b)
{
char tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void fn(char *str, int k, int n)
{
for (int i = 1; i <= k; i++)
{
if (i == 1)
{
puts(str);
}
else
{
for (int j = 1; j < i; j++)
{
if (i == n)
putchar('\n');
swap(str + n - i, str + n - i + j);
fn(str, i - 1, n);
swap(str + n - i, str + n - i + j);
}
}
}
}
My question is, should I be using that function or my function? Is there any advantage to that function over my function, given that my function has two loops?