Algorithms – Benefits of Recursive vs Iterative Binary Search

algorithmsefficiency

In a recent assignment for my programming 2 class we tested the efficiency of searches by populating a java ArrayList with 13,040 strings. The sequential search was obviously slower than the binary searches due to the complexity difference and the amount of times the code actually has to loop through the code.

Iterative binary search and recursive binary search, however, had the same amount of comparisons. For example:

sequentialSearch(): 'some_word' found in ArrayList at index 13,020 - comparisons: 13,021

The comparisons being how many times the computer actually checked if the user's "some_word" was equal to a value ArrayList.

iterativeBinarySearch(): 'some_word' found in ArrayList at index 13,020 - comparisons: 14
recursiveBinarySearch(): 'some_word' found in ArrayList at index 13,020 - comparisons: 14

So if the comparisons of iterative and recursive are the same, in what situations would you choose one over the other? Is it simply personal taste or is there a specific reasoning for using a specific one?

Best Answer

If your language processor (compiler or interpreter) properly implements tail recursion optimization, then there winds up being no difference between a properly-coded tail-recursive binary search and an iterative binary search. The language processor will turn the recursive calls into simple loops.

At that point, choice of recursive vs. iterative formulation is pretty much a matter of personal and local preference. Some people find recursive code easier to understand. Some people are scared to death of recursion, or don't understand it, or have no clue about tail recursion optimization, and want explicitly iterative code everywhere.