How would I implement a binary search using just an array?
+3
A:
Assuming you're looking for a language-independant answer, Wikipedia has all the info...
Ty
2008-10-30 06:06:54
+12
A:
Ensure that your array is sorted since this is the crux of a binary search.
Any indexed/random-access data structure can be binary searched. So when you say using "just an array", I would say arrays are the most basic/common data structure that a binary search is employed on.
You can do it recursively (easiest) or iteratively. Time complexity of a binary search is O(log N) which is considerably faster than a linear search of checking each element at O(N). Here are some examples from Wikipedia: Binary Search Algorithm:
Recursive:
BinarySearch(A[0..N-1], value, low, high) {
if (high < low)
return -1 // not found
mid = low + ((high - low) / 2)
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid // found
}
Iterative:
BinarySearch(A[0..N-1], value) {
low = 0
high = N - 1
while (low <= high) {
mid = low + ((high - low) / 2)
if (A[mid] > value)
high = mid - 1
else if (A[mid] < value)
low = mid + 1
else
return mid // found
}
return -1 // not found
}
Simucal
2008-10-30 06:13:30
Remember to watch for overflow when calculating mid. (see http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html )
Firas Assaad
2008-10-30 06:55:04
@Firas Assad, Thanks, updated code to show the fix associated with preventing the overflow
Simucal
2008-10-30 14:49:50
+1
A:
The single comparison version is fast and concise
int bsearch_double(const double a[], int n, double v) {
int low = 0, mid;
while (n - low > 1) {
mid = low + (n - low) / 2;
if (v < a[mid]) n = mid;
else low = mid;
}
return (a[low] == v) ? low : -1;
}
Jed
2008-10-31 21:25:49