Thursday, 9 January 2014

Java : Program to print all permutations of a given string.

A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Below are the permutations of string ABC. ABC, ACB, BAC, BCA, CAB, CBA

public class Ques2 {

    /**
     * @param args the command line arguments
     */
   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));
    }
}

        
    public static void main(String[] args) throws IOException {

       String str="abc";
       permutation(str);
}
}

No comments:

Post a Comment