The Linear Search Algorithm with Recursion

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

Procedure: Recursive-Linear-Search(a,i,x)
- a: the array to search in
- x: the value we are searching for in a
- i: the index of an element in a
- 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 i > the last element index, then return -1
2) Else if a[i] == x, then return i
3) Else return Recursive-Linear-Search(a, i + 1, x)

Java code:


public static int recursiveLinearSearch(int[] a, int i, int x) {
    if (i > a.length - 1) return -1;
    else if (a[i] == x) return i;
    else return recursiveLinearSearch(a, i + 1, x);