Recursive Permutation in Java

Finding all the permutations for any given set of items has always been an area of interest for programmers. A very simple algorithm for finding all the permutations, the Bell Algorithm and the C code implementation of that algorithm has already been presented. However the initial solution was provided using iteration.


Programming Geeks : Recursive permutation in Java

Here the java code for permutation is presented using recursive routine.


import java.io.*;
public class permutation {
    public static void main(String args[]) throws IOException{
        String str;
        System.out.println("Enter the initial string");
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        str=br.readLine();
        System.out.println("Permutations are :");
        permute("", str);
    }

  public static void permute(String beginningString, String endingString) {
    if (endingString.length() <= 1)
      System.out.println(beginningString + endingString);
    else
      for (int i = 0; i < endingString.length(); i++) {
        try {
          String newString = endingString.substring(0, i) + endingString.substring(i + 1);

          permute(beginningString + endingString.charAt(i), newString);
        } catch (StringIndexOutOfBoundsException exception) {
          exception.printStackTrace();
        }
      }
  }
}


Related Posts

Share

Filed Under: CodesJava

Tags:

About the Author: Software Engineer - Search & Recommendation at Rovi

RSSComments (4)

Leave a Reply | Trackback URL

  1. lwpro2 says:

    cool, i m trying the same logic. but struggling on the codes.

    ooops.

  2. Ebenezer says:

    Thanks, It was really helpful.

    I needed the resultset to be unique so I stored the result into HashSet instead of printing it directly.

  3. priti says:

    not understood anything …plzzz expln clearly.

    • Saurabh says:

      Hi Priti,
      In case you are having trouble in understanding the recursive approach, you can check out this post which is more explanatory and uses a more efficient algorithm

Leave a Reply

*

AWSOM Powered