My loop here takes an array of integers but any type that accepts the < operator will work. The idea is not to return the searched for value, but to return its index.
int BinarySearch (const int* pSortedArray, int lengthSortedArray, int valueToFind)
{
int Begin = 0;
int End = lengthSortedArray-1;
while (Begin <= End)
{
int Middle = (Begin + End) / 2; // compute pivot point.
if (valueToFind > pSortedArray [Middle])
{
Begin = Middle + 1; // repeat search in top half.
}
else if (valueToFind < pSortedArray [Middle])
{
End = Middle - 1; // repeat search in bottom half.
}
else
{
return Middle; // return found item
}
}
return -1; // failed to find value
}
No comments:
Post a Comment