How to set max depth for recursive program in java?

Viewed 82

I've written a recursive program in java that takes an array of characters and with two methods, one switching places of the two leftmost tiles and the other moving the rightmost tile to the left of the leftmost tile. It then returns the order of moves which makes the array in alphabetical order with the smallest number of moves. It seems to be working but I'm also supposed to set a max depth (15), and what I wonder is what do I return when it has reached max depth? It seems to be working right now, but I'm not sure it's correct.

This is part of the code:

 public static String Sorter(char[] letters){
        int nrOfMoves = 0;
        return Sorter(letters,nrOfMoves);
    }
    
    private static String Sorter(char[] letters, int nrOfMoves){
        if(sorted(letters)) return "";
        if(nrOfMoves >= 15) return "" ; //??
        
        switchLeft(letters);
        String moveb = "b" + Sorter(letters,nrOfMoves+1);
        switchLeft(letters);
        
        rightToLeft(letters);
        String moves = "s" + Sorter(letters,nrOfMoves+1);
        leftToRight(letters);
        
        if(moves.length()<moveb.length()) return moves;
        return moveb;
    }
1 Answers

The example seems fine. Personally, I would make use of nrOfMoves++ instead of nrOfMoves+1

and I would have it count down (number of moves left instead of number of moves performed). This makes sure that your Sorter method does not need to know at what depth it needs to stop. It just gets a limit of how many more recursions it can perform

public static String Sorter(char[] letters){
    int nrOfMoves = 15;
    return Sorter(letters,nrOfMoves);
}

private static String Sorter(char[] letters, int nrOfMoves){
    if(sorted(letters) || nrOfMoves <= 0){ 
       return "";
    }

    switchLeft(letters);
    String moveb = "b" + Sorter(letters,nrOfMoves--);
    switchLeft(letters);

    rightToLeft(letters);
    String moves = "s" + Sorter(letters,nrOfMoves--);
    leftToRight(letters);

    if(moves.length()<moveb.length()) return moves;
    return moveb;
}
Related