Please send questions to st10@humboldt.edu .

#include <iostream>
#include <cmath>
#include <cassert>
using namespace std;

int count_bin(int valArr[], int leftIndex, int rightIndex, int val, int& comps_so_far)
{
    int midIndex;   // index of the middle element in this range

    assert(leftIndex >= 0);
    assert(rightIndex >= 0);
    
    // base case #1 --- is there anything to search?
    if (rightIndex < leftIndex)
    {
        // element was NOT found --- return -1, failure
        return -1;
    }

    // base case #2 --- there is only ONE element to search
    else if (rightIndex == leftIndex)
    {
        // in either case, make 1 comparison below to see if element is here
        comps_so_far++;

        if (valArr[leftIndex] == val)
        {
            // element FOUND! return its index
            return leftIndex;
        }
        else
        {
            // element NOT in array --- return -1, failure
            return -1;
        }
    }

    // if get here --- there's still more to search;
    else
    {
        // look at element in MIDDLE of this range;
        midIndex = static_cast<int>(ceil( 
             leftIndex + 
             (static_cast<double>
                 (rightIndex - leftIndex)/2)
                       ));

        // base case #3 --- element IS in the middle;
        if (valArr[midIndex] == val)
        {
            // this comparison was made...
            comps_so_far++;
            return midIndex;
        }
     
        // element is NOT in the middle...

        else
        {
            // above if-comparison failed, and am making 1 comparison
            //    below...
            comps_so_far += 2;

            // recursive case #1: val is LESS THAN 
            //    middle value;
            //    continue looking in LEFT of range;
            if (val < valArr[midIndex])
            {
                return count_bin(valArr, 
                                 leftIndex, midIndex-1, 
                                 val, comps_so_far);
            }
            
            // recursive case #2: val is MORE THAN 
            //    middle value;
            //    continue looking in RIGHT of range;
            else
            {
                return count_bin(valArr, 
                                 midIndex+1, rightIndex,
                                 val, comps_so_far);
            }
        }
    }
}