The Binary Search Algorithm with Recursion

A loop in a binary search algorithm may be substitute with a recursion. This approach allows for more elegant code. The pseudo code looks like this:

Procedure: Recursive-Binary-Search(a,p,r,x)
- a: the array to search
- x: the value we are searching for in a
- p and r: represents indexes sub-array under consideration
- The index of an element matching x in the sub-array from a[i]
- Through a[a.length], or -1 if x is not found in the array
1) If p > r then return -1
2) Else:
a) Set q to [(p + r) / 2]
b) If a[q] == x, than return q.
c) else if a[q] > x, then return Recursive-Binary-Search(a,p,q-1,x)
d) else return Recursive-Binary-Search(a,q+1,r,x)

The code in Java

System.out.println(recursiveBinarySearch(new int[] {1,2,3,4,7,9,12,18}, 0, 7, 12));

public static int recursiveBinarySearch(int[] a, int p, int r, int x) {
    if (p <= r) {
        int q = (p + r) / 2;
        if (a[q] == x) return q;
        else if (a[q] > x) return recursiveBinarySearch(a, p, q-1, x);
        else return recursiveBinarySearch(a, q+1, r, x);
    return -1;