I'm writing code to take an int[] and adding all of its permutations to a Collection. The code works and makes the correct swaps. Before adding it to the Stack, I have a print statement showing me my array before adding it:
132
213
231
312
321
But then when I print the arrays in the stack after the permutations are done, I get:
321
321
321
321
321
I have a feeling it has something to do with how Java handles the array and how the int[] is being added but I'm not sure.
Code here:
public Stack<int[]> perm(int[] labels) {
Stack<int[]> perm = new Stack<int[]>();
int[] value = labels;
Arrays.sort(value);
int k = labels.length;
boolean permutationsComplete = false;
perm.add(value);
while (!permutationsComplete) {
int i = k - 1;
while (i > 0 && value[i - 1] >= value[i]) {
i--;
}
if (i < 1) {
permutationsComplete = true;
System.out.println();
for(int[] list : perm) {
this.printList(list);
}
return perm;
}
int j = k;
while (value[j - 1] <= value[i - 1]) {
j--;
}
int swap1 = value[i - 1];
value[i - 1] = value[j - 1];
value[j - 1] = swap1;
i++;
j = k;
while (i < j) {
int swap2 = value[i - 1];
value[i - 1] = value[j - 1];
value[j - 1] = swap2;
i++;
j--;
}
perm.add(value);
}
return null;
}