I have written code for generating all the permutations in C as explained here. How can the code be optimized? Are there any memory leaks?
int factorial(int n) {
int fact = 1;
for(int i = 2; i <= n; i++)
fact *= i;
return fact;
}
int main(){
int len = 4, i, j;
int **p;
int **q = (int**) malloc(sizeof(int*));
q[0] = (int*) malloc(sizeof(int));
q[0][0] = 1;
for(i = 0; i < len; i++){
p = (int**) malloc(sizeof(int*) * factorial(i + 1));
for(j = 0; j < factorial(i + 1); j++)
p[j] = (int*) malloc(sizeof(int) * (i + 1));
int y=0;
for(j = 0; j < factorial(i); j++){
for(int k = 0; k < i + 1; k++){
int added = 0;
for(int l = 0; l < i + 1; l++){
if(k == l){
p[y][l] = i + 1;
added = 1;
}
else
p[y][l] = q[j][l-added];
}
y++;
}
}
for(j = 0; j < factorial(i); j++)
free(q[j]);
free(q);
q = p;
}
for(i = 0; i < factorial(len); i++){
for(j = 0; j < len; j++)
printf("%d\t", p[i][j]);
printf("\n");
free(p[i]);
}
free(p);
}
factorial(i + 1)
arrays allocated and appended intop[]
array has nothing to do with the described Johnson-Trotter algorithm. – CiaPan Feb 10 at 7:57