Advertisement
electricmaster

RecursiveSwap

Nov 19th, 2016
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. /*Write a recursive method that has as arguments an array of characters and two bounds on array indexes.
  2. The method should reverse the order of those entries in the array whose indexes are between the two bounds (inclusive).
  3. For example, suppose the array is:
  4. a[0]  = ‘A’                   a[1] = ‘B’                    a[2]= ‘C’
  5.  
  6. a[3] = ‘D’                    a[4] = ‘E’
  7. and the bounds are 1 and 4. Then, after the method is run, the array elements should be:
  8. a[0]  = ‘A’                   a[1] = ‘E’                    a[2]= ‘D’
  9. a[3] = ‘C’                    a[4] = ‘B’
  10. Embed the method in a program and test it.*/
  11.  
  12. public class HillaryClinton{
  13.  
  14.   public static char[] FlipFlop(char[] x, int a, int b){
  15.     if(a < 0 || b < 1 || a > b) throw new IllegalArgumentException();
  16.  
  17.     if(b - a == 1)
  18.       return swap(x, a, b);
  19.       else{
  20.         for(int i = a + 1; i <= b; i++)
  21.           for(int j = b; j >= i; j--)
  22.             x = FlipFlop(x, j - 1, j);
  23.       }
  24.       return x;
  25.   }
  26.  
  27.   private static char[] swap(char[] x, int a, int b){
  28.     if(a < 0 || b < 0) throw new IllegalArgumentException();
  29.     if(a == b) return x;
  30.     char t = x[a];
  31.     x[a] = x[b];
  32.     x[b] = t;
  33.     return x;
  34.   }
  35.  
  36.   public static void main(String[] args){
  37.     char[] x = {'A', 'B', 'C', 'D', 'E'};
  38.     x = FlipFlop(x, 1, 4);
  39.     for(Character c: x)
  40.       System.out.print(c + " ");
  41.   }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement