I was trying to permutate using java and i noticed my code works for strings but the same algorithm does not work correctly on Arrays
here's the code for strings
public static void Recurse(String s,int i)
{
for(int j=i;j<(s.length());j++)
{
s=Swap(s,i,j);
if(i<(s.length()-1))
{
Recurse(s,i+1);
}
if(i==(s.length()-1))
{
Display(s);
}
}
}
public static String Swap(String newString,int i,int j)
{
char newChar[]=newString.toCharArray();
char temp=newChar[i];
newChar[i]=newChar[j];
newChar[j]=temp;
return String.valueOf(newChar);
}
public static void Display(String s)
{
System.out.println(s);
}
public static void main(String args[])
{
String i=new String("123");
Recurse(i,0);
}
output: 123 132 213 231 312 321 works fine.
then here is the code for arrays
public static void Recurse(int [] newArray,int i)
{
for(int j=i;j<newArray.length;j++)
{
Swap(newArray,i,j);
if(i<(newArray.length-1))
{
Recurse(newArray,i+1);
}
if(i==(newArray.length-1))
{
Display(newArray);
}
}
}
public static void Display(int [] Array)
{
for(int i: Array)
{
System.out.print(i);
}
System.out.println();
}
public static void main(String args[])
{
Recurse(new int[] {1,2,3},0);
}
output 123 132 312 321 123 132
Does not work correctly,So i was wondering what went wrong here.
Swapmethod? - GBlodgettSwapmethod for yourArrayversion? - GBlodgett