Created
July 18, 2014 01:50
-
-
Save lamida/d7c23efbd3b2e7db3a82 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Permut { | |
public static void main(String[] args) { | |
int ar[] = { 1, 2, 3}; | |
permut(ar, 0); | |
} | |
public static void print(int[] ar){ | |
for(int i = 0; i < ar.length; i++){ | |
System.out.printf("%d ", ar[i]); | |
} | |
System.out.println(); | |
} | |
public static void swap(int[] ar, int i, int j) { | |
int tmp = ar[i]; | |
ar[i] = ar[j]; | |
ar[j] = tmp; | |
} | |
private static int count = 0; | |
private static int stack = 0; | |
public static String genTab(int stack){ | |
StringBuilder b = new StringBuilder(); | |
for(int i = 0; i < stack; i++){ | |
b.append("\t"); | |
} | |
return b.toString(); | |
} | |
public static void permut(int[] ar, int i) { | |
count++; | |
//System.out.printf("%sCall permut %d stack %d\n", genTab(stack), count, stack); | |
stack++; | |
int j = i; | |
if(j == ar.length){ | |
print(ar); | |
stack--; | |
return; | |
} | |
for (j = i; j < ar.length; j++) { | |
swap(ar, i, j); | |
permut(ar, i + 1); | |
swap(ar, i, j); | |
} | |
stack--; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment