Last active
September 1, 2016 13:15
-
-
Save developer-sdk/a8db20ec7d070873d3a6072570e2bb7f 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 Permutation { | |
public static void main(String[] args) { | |
int[] arr = { 1, 2, 3 }; | |
perm(arr, 0); | |
} | |
public static void perm(int[] arr, int pivot) { | |
if (pivot == arr.length) { | |
print(arr); | |
return; | |
} | |
for (int i = pivot; i < arr.length; i++) { | |
swap(arr, i, pivot); | |
perm(arr, pivot + 1); | |
swap(arr, i, pivot); | |
} | |
} | |
public static void swap(int[] arr, int i, int j) { | |
int temp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = temp; | |
} | |
public static void print(int[] arr) { | |
for (int i = 0; i < arr.length; i++) { | |
if (i == arr.length - 1) | |
System.out.println(arr[i]); | |
else | |
System.out.print(arr[i] + ","); | |
} | |
} | |
} |
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 PermutationString { | |
public static void main(String[] args) { | |
permutation("abcd"); | |
} | |
public static void permutation(String str) { | |
permutation("", str); | |
} | |
private static void permutation(String prefix, String str) { | |
int n = str.length(); | |
if (n == 0) | |
System.out.println(prefix); | |
else { | |
for (int i = 0; i < n; i++) | |
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment