Please send questions to
st10@humboldt.edu .
/*--------------------------------------------------
created by st10 at Mon Nov 17 00:46:59 PST 2003
--------------------------------------------------*/
#include <iostream>
#include <cmath>
using namespace std;
/*--------------------------------------------------
Contract: binSearch : int[] int int int -> int
Purpose: See if val is contained within ordered array
valArr within the range of indices
[leftIndex, rightIndex]; return the index
where found if so, and -1 if not.
Examples: if arr1 == {1, 3, 8, 27, 56, 77, 78, 79, 100}:
binSearch(arr1, 50, 0, 8) == -1
binSearch(arr1, 150, 0, 8) == -1
binSearch(arr1, 0, 0, 8) == -1
binSearch(arr1, 1, 0, 8) == 0
binSearch(arr1, 100, 0, 8) == 8
binSearch(arr1, 56, 0, 9) == 4
--------------------------------------------------*/
int binSearch(int valArr[], int val,
int leftIndex, int rightIndex)
{
int midIndex;
// 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)
{
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)
{
return midIndex;
}
// element is NOT in the middle...
else
{
// recursive case #1: val is LESS THAN
// middle value;
// continue looking in LEFT of range;
if (val < valArr[midIndex])
{
return binSearch(valArr, val,
leftIndex, midIndex-1);
}
// recursive case #2: val is MORE THAN
// middle value;
// continue looking in RIGHT of range;
else
{
return binSearch(valArr, val,
midIndex+1, rightIndex);
}
}
}
}