Skip to content

Instantly share code, notes, and snippets.

@ayago
Created June 20, 2025 20:37
Show Gist options
  • Save ayago/654cc811a2d80035eabf68d17694a751 to your computer and use it in GitHub Desktop.
Save ayago/654cc811a2d80035eabf68d17694a751 to your computer and use it in GitHub Desktop.
Brute force printing of all permutations of a given array
private List<int[]> allPermutationsOf(int [] givenArray){
Queue<int[]> results = new LinkedList<>();
results.add(givenArray);
int previousExpectedOutcome = 1;
for(int pivot = 0; pivot < givenArray.length - 1; pivot++){
int expectedOutcomeForEachResult = givenArray.length - pivot;
for(int c = 0; c < previousExpectedOutcome; c++){
int[] array = results.poll();
for(int outcome = 0; outcome < expectedOutcomeForEachResult; outcome++){
if(outcome == 0){
results.add(array);
} else {
int[] newOutcome = new int[givenArray.length];
for(int i = 0; i < pivot; i++){
newOutcome[i] = array[i];
}
int pivotValue = array[pivot];
int shiftedIndex = pivot + outcome;
int swapValue = array[shiftedIndex];
newOutcome[pivot] = swapValue;
newOutcome[pivot + 1] = pivotValue;
for(int i = pivot + 2; i <= shiftedIndex; i++){
newOutcome[i] = array[i - 1];
}
for(int i = shiftedIndex + 1; i < givenArray.length; i++){
newOutcome[i] = array[i];
}
results.add(newOutcome);
}
}
}
previousExpectedOutcome = previousExpectedOutcome * expectedOutcomeForEachResult;
}
return new ArrayList<>(results);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment