// binsearch2.cpp
// Glenn G. Chappell
// 18 Feb 2008
//
// For CS 311 Spring 2008
// Binary Search
// Version #2: Recursive (improved)


#include <iostream>
using std::cout;
using std::endl;
#include <cstdlib>    // for std::size_t
#include <algorithm>  // for std::distance, std::advance


// binSearch
// Does Binary Search on a range specified with iterators.
// Recursive.
// Requirements on types:
//     FDIter is a forward iterator type.
//     ValueType is the value type of FDIter.
//     operator< is a total order on ValueType.
// Pre:
//     [first, last) is a valid range.
//     Values in the range are sorted by < (ascending).
// Post:
//     Return is true if findMe was found (using equivalence) in range,
//      false otherwise.
// If ValueType operator< throws, then binSearch throws the same exception.
// Otherwise, will not throw.
template <typename FDIter, typename ValueType>
bool binSearch(FDIter first,      // Iterator to first item in range
               FDIter last,       // Iterator to one-past last item in range
               const ValueType & findMe)  // value to find
{
    std::size_t size = std::distance(first, last);

    // BASE CASE

    if (size <= 1)
    {
        if (size == 1)
            return !(*first < findMe) && !(findMe < *first);
        else
            return false;
    }

    // RECURSIVE CASE

    // Get iterator to middle position of range
    FDIter pivotIter = first;
    std::advance(pivotIter, size/2);

    if (findMe < *pivotIter)
    {   // Recursively search first half of range
        return binSearch(first, pivotIter, findMe);
    }
    else
    {   // Recursively search second half of range
        return binSearch(pivotIter, last, findMe);
    }
}


// Main program
// Demonstrates use of function binSearch
int main()
{
    // Set up array
    const int SIZE = 100000;
    int arr[SIZE];
    for (int i = 0; i < SIZE; ++i)
        arr[i] = 10*i;

    int value = 40;  // Value to search for

    // Do a search
    bool success = binSearch(arr, arr + SIZE, value);

    // Print result
    if (success)
        cout << value << " FOUND" << endl;
    else
        cout << value << " not found" << endl;
}
