Java Recursive Binary Search

Can someone help me fix this? I’m getting an IndexArrayOutofBounds error…

    private static int recursiveBinarySearch(book[] book, String title) {
        int low = 0, high = book.length - 1, middle = (low + high) / 2;
        String bookTitle = title;
        
        book[] newBook = new book[middle];
        
        if (bookTitle.compareTo(book[middle].getTitle()) == 0) // base case
            return middle;
            
        else { // recursive
            if (bookTitle.compareTo(book[middle].getTitle()) < 0) {
                for (int i = 0; i < (book.length / 2); i++) {
                    newBook[i] = book[i]; // must be new array = to old array
                }
            }
            else {
                for (int i = (book.length / 2); i < book.length; i++)  {
                    newBook[i] = book[i];
                }
            }
            return (recursiveBinarySearch(newBook, bookTitle));
        }
    }

Say your input array has 10 elements.

middle = (0 + 9) / 2 = 4 (this isn’t the middle…)

then in your loop near the end you try to assign newBook[5] through newBook[9] but declared it as a 4 element array, so only indices 0-3 are valid

You have a few logic errors you need to fix

You’re kinda losing the benefit of doing a binary search by doing all this extra work, iterating loops and copying the array repeatedly. Instead you can change the function parameters to include the low and high indices and just change these indices as you make recursive calls. You search within a single array, zero loops, constant memory.