Chander Shivdasani Chander Shivdasani - 1 year ago 77
Java Question

permute a string

Given the String, print all its permutations. To do that, i came up with the following program.

public static char[] swap(char[] input, int i, int j) {
char temp;
temp = input[i];
input[i] = input[j];
input[j] = temp;

return input;


* @param args

public static void permuteStrings(char[] inputString, int start, int finish ) {
//Base case: When there is only single element, print the string
if(start == finish)
else {
//Recursive case: Swap first element with all the elements and permute on the
// rest of string.
for(int i = start; i <= finish; i++) {
inputString = swap(inputString, start, i);
permuteStrings(inputString, i + 1, finish);
inputString = swap(inputString,start, i); //restoring the original string

But, for the given input ABC, all it prints are


I cant seem to figure out what the problem is

Answer Source

Figured out the problem. The problem was in the function invocation:

permuteStrings(inputString, i + 1, finish);.

The correct way was:

permuteStrings(inputString, start + 1, finish);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download