I am writing a code to generate permutation of elements of an array. I wrote two different types of swaping functions one using temporary storage works fine while the other that doesn’t use any temporary storage is not generating output. Why this is happening??
The following code works fine
#include<iostream>
#include<cstdio>
using namespace std;
int tt=0;
void swap1 (int v[], int i, int j) {
int t;
t = v[i];
v[i] = v[j];
v[j] = t;
}
void permute(int arr[],int n,int index)
{
if(index==n)
{
for(int i=0;i<n;i++) printf ("%c", arr[i]) ;
printf("\n");
tt++;
}
else
for(int j=index; j < n ;j++)
{
swap1(arr,index,j);
permute(arr,n,index+1);
swap1(arr,j,index);
}
}
int main()
{
int arr[]={'a','b','c','d'};
permute(arr,4,0);
cout<<endl;
printf("%d\n",tt);
getchar();
}
output:
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc
24
While the following code doesn’t output the permutations:
#include<iostream>
#include<cstdio>
using namespace std;
int tt=0;
void swap(int v[],int i,int j)
{
v[i]= v[i] + v[j];
v[j]= v[i] - v[j];
v[i]= v[i] - v[j];
}
void permute(int arr[],int n,int index)
{
if(index==n)
{
for(int i=0;i<n;i++) printf ("%c", arr[i]) ;
printf("\n");
tt++;
}
else
for(int j=index; j < n ;j++)
{
swap(arr,index,j);
permute(arr,n,index+1);
swap(arr,j,index);
}
}
int main()
{
int arr[]={'a','b','c','d'};
permute(arr,4,0);
cout<<endl;
printf("%d\n",tt);
getchar();
}
output:
24
doesn’t work when
i == j(it then set v[i] to 0), something which happens with your loop