I am using a recursive algorithm to list all possible permutations of elements of an array p = {1,2,3}. Following is the simple recursive implementation I am using:
void swap(int x, int y){
int temp = array[x];
array[x]=array[y];
array[y]=temp;
return;
}
void printArray(int size){
int i;
for (i=0;i<size;i++)
printf("%d ", array[i]);
printf("\n");
return;
}
void permute(int k,int size){
int i;
if (k==0)
printArray(size);
else{
for (i=k-1;i>=0;i--){
swap(i,k-1);
permute(k-1,size);
swap(i,k-1);
}
}
return;
}
The problem is instead of printing them I want to add every permutation to a 2D array. Currently, I am printing the permutations to a file and then reading it to a 2D array, but I think there should be a better way to do this.