Advertisement
cf1709

stringPermRecursion

Sep 21st, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1.  
  2. package stringpermrecursion;
  3.  
  4. import javax.swing.*;
  5.  
  6. public class StringPermRecursion {
  7.  
  8.     public static void main(String[] args) {
  9.         //ask for a string
  10.         String input = JOptionPane.showInputDialog("Input a string:");
  11.        
  12.         //transfer the input to a string array
  13.         char arrayStr[] = input.toCharArray();
  14.        
  15.         //pass the string, pointers to first and last element of string
  16.         permutation( arrayStr , 0, input.length() - 1 );
  17.     }
  18.    
  19.     public static void permutation( char[] arr, int strLeft, int strRight ){
  20.         if( strLeft == strRight ){
  21.             for(int i = 0; i < arr.length; i++){
  22.                 System.out.print( arr[ i ]);
  23.             }
  24.            
  25.             System.out.print( "\n" );            
  26.         }        
  27.         else{
  28.             for(int i = strLeft; i <= strRight; i++ ){
  29.                 swap( arr, strLeft, i );
  30.                 permutation( arr, strLeft+1, strRight );
  31.                 swap( arr, strLeft, i );
  32.             }
  33.         }            
  34.     }
  35.    
  36.     //swap two elements of the array
  37.     public static void swap( char[] a, int l, int j ){
  38.         char temp = a[l];
  39.         a[l] = a[j];
  40.         a[j] = temp;
  41.     }    
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement