permutation of string in java code example
Example 1: java permutation
public static boolean next_permutation(int[] arr) {
int len = arr.length;
int i = len - 1;
while (i > 0) {
if (arr[i - 1] < arr[i]) break;
i--;
}
if (i <= 0) return false;
int j = len - 1;
while (j >= i) {
if (arr[i - 1] < arr[j]) break;
j--;
}
swap(i - 1, j, arr);
len--;
while (i < len) {
swap(i, len, arr);
len--;
i++;
}
return true;
}
public static void swap(int x, int y, int[] arr) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
Example 2: find all permutations of a string
void permute(string a, int l, int r)
{
if (l == r)
cout<<a<<endl;
else
{
for (int i = l; i <= r; i++)
{
swap(a[l], a[i]);
permute(a, l+1, r);
swap(a[l], a[i]);
}
}
}
Example 3: generate all permutations of string
void perm(char a[], int level){
static int flag[10] = {0};
static char res[10];
if(a[level] == '\0'){
res[level] = '\0';
for(int i = 0; res[i] != '\0'; ++i){
printf("%c", res[i]);
}
printf("\n");
++counter;
}
else{
for(int i = 0; a[i] != '\0'; ++i){
if(flag[i] == 0){
res[level] = a[i];
flag[i] = 1;
perm(a, level + 1);
flag[i] = 0;
}
}
}
}
int main(){
char first[] = "abc";
perm(first, 0);
return 0;
}