Sunday, March 22, 2009

Binary search - finding a value quickly in a sorted array

Given an array of items, that are sorted, the fastest way to search through them is using a Binary Search. The time to search in log (n) so that for 1000 items, there are only ~10 loops, to search 1,000,000 items, we only have 20 loops, and to search through 1 billion items is only about 30 loops. This is very fast and does return a -1 if it can't find the proper item.

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: