Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Write a recursive method that has as arguments an array of characters and two bounds on array indexes.
- The method should reverse the order of those entries in the array whose indexes are between the two bounds (inclusive).
- For example, suppose the array is:
- a[0] = ‘A’ a[1] = ‘B’ a[2]= ‘C’
- a[3] = ‘D’ a[4] = ‘E’
- and the bounds are 1 and 4. Then, after the method is run, the array elements should be:
- a[0] = ‘A’ a[1] = ‘E’ a[2]= ‘D’
- a[3] = ‘C’ a[4] = ‘B’
- Embed the method in a program and test it.*/
- public class HillaryClinton{
- public static char[] FlipFlop(char[] x, int a, int b){
- if(a < 0 || b < 1 || a > b) throw new IllegalArgumentException();
- if(b - a == 1)
- return swap(x, a, b);
- else{
- for(int i = a + 1; i <= b; i++)
- for(int j = b; j >= i; j--)
- x = FlipFlop(x, j - 1, j);
- }
- return x;
- }
- private static char[] swap(char[] x, int a, int b){
- if(a < 0 || b < 0) throw new IllegalArgumentException();
- if(a == b) return x;
- char t = x[a];
- x[a] = x[b];
- x[b] = t;
- return x;
- }
- public static void main(String[] args){
- char[] x = {'A', 'B', 'C', 'D', 'E'};
- x = FlipFlop(x, 1, 4);
- for(Character c: x)
- System.out.print(c + " ");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement