473,545 Members | 2,042 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Binary Search Algorithm

Kelicula
176 Recognized Expert New Member
Why?:
One commonly used algorithm is the binary search.
If you don't already know it, you should read on.
Very helpful. Saves much CPU. Reduces computations exponentially.

When searching though a lot of information to find a match, the first idea that comes to mind is the linear search. Loop through all the values looking for a match. If you find it, return the location, or value and end the search.
However this becomes highly inefficient when the values to be searched become very large. It's a O(N) algorithm. At worse case you may have to search ALL the values to find a match, or even worse find that it's not there!

How?:
If the list of items can be sorted numerically or ASCII. Use a binary search!

First, sort the list.Then compare the value in the very center (round up or down in case of uneven list elements) to your search term. If it is "less than" your term, you know that it must be lower than that point. So you can eliminate the upper range. If the term has a greater value than your center point value, eliminate the lower range.

Thus reducing the amount of items to be searched by half.

Apply this technique to the remaining items continually and reduce the search by half each iteration.

Thus running at the much faster O(log N) algorithm.

Example:

Warning: uses "recursion" , remember to consider function call loads on CPU. In some languages this can actually be slower than linear. See non recursive below.
(taken from Wikipedia)

Expand|Select|Wrap|Line Numbers
  1. BinarySearch(A[0..N-1], value, low, high) {
  2.        if (high < low)
  3.            return -1 // not found
  4.        mid = low + ((high - low) / 2)  // Note: not (low + high) / 2 !!
  5.        if (A[mid] > value)
  6.            return BinarySearch(A, value, low, mid-1)
  7.        else if (A[mid] < value)
  8.            return BinarySearch(A, value, mid+1, high)
  9.        else
  10.            return mid // found
  11.    }
  12.  
There is an optimization here.
Sometimes when dealing with large numbers, or floating point high precision.
mid = (low + high)/2
can overflow and hog memory, resulting in unreliable results.
mid = low + ((high - low)/2)
fixes it. :)
See here...

Non Recursive:
Expand|Select|Wrap|Line Numbers
  1. low = 0
  2.        high = N
  3.        while (low < high) {
  4.            mid = low + ((high - low) / 2)  // Note: not (low + high) / 2 !!
  5.            if (A[mid] < value)
  6.                low = mid + 1; 
  7.            else
  8.                 //can't be high = mid-1: here A[mid] >= value,
  9.                 //so high can't be < mid if A[mid] == value
  10.                 high = mid; 
  11.        }
  12.        // high == low, using high or low depends on taste 
  13.        if ((low < N) && (A[low] == value))
  14.            return low // found
  15.        else
  16.            return -1 // not found      
  17.  

There are MANY sources for this most elementary algorithm. Just type "binary search" into Google.

Happy coding....
Mar 31 '09 #1
6 12134
Markus
6,050 Recognized Expert Expert
I'd never thought of doing it like that.

Thanks a bunch :D
Apr 9 '09 #2
JosAH
11,448 Recognized Expert MVP
Also see Fibonacci Search for a slightly better search than the binary search method.

kind regards,

Jos
Jun 16 '09 #3
Markus
6,050 Recognized Expert Expert
While we're talking about search algorithms, the boyer-moore algorithm is interesting.
Jun 16 '09 #4
Kelicula
176 Recognized Expert New Member
Nice, I had never heard of the Fibonacci search myself.

Very interesting...
Jun 16 '09 #5
loonman
7 New Member
in researching the Fibonacci search code i also noticed the golden ratio search.
what do you think about this alternative?
Sep 11 '09 #6
jkmyoung
2,057 Recognized Expert Top Contributor
? The golden ratio search appears to be a mathematical search based on unknown secondary values. I don't see how that applies in terms of searching for a particular item within an array.

The Fibonacci search reminds me of a priority heap.

--
Re the original binary search:
We should note that if we're ever only going to search once or twice through this array, sorting is not that useful. It becomes much more useful when we are repeatedly searching through this array.

To be honest, I find the low + ((high - low) / 2) to be a waste in this case, requiring an extra operation. You're dealing with integers, and unless the number of elements reaches INT_MAX/2, you don't really need to use it. As stated before, this is more of a floating point addition concern. Further, if concerned about speed you should use >> 1 instead of / 2.
If you get to the point where you are actually reaching extremely large numbers of elements, you may want to consider a Interpolation search (sometimes called a dictionary search), until you reach a certain smaller range, or provide subkeys for ranges.
Mar 22 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

6
8838
by: Alex Gerdemann | last post by:
Hello, I am writing a program where I have a vector (std::vector<std:string> list) that I need to search many times. To accomplish this efficiently, I plan to sort the list using std::sort(list.begin(),list.end()), then run binary searches. I need to get the indices of the elements found so I can construct a matrix where I allocate a row...
4
9004
by: Tarique Jawed | last post by:
Alright I needed some help regarding a removal of a binary search tree. Yes its for a class, and yes I have tried working on it on my own, so no patronizing please. I have most of the code working, even the removal, I just don't know how to keep track of the parent, so that I can set its child to the child of the node to be removed. IE - if...
28
3131
by: joshc | last post by:
If I have an array of data that I know to be sorted in increasing order, and the array is less than 50 elements, and I want to find the first element greater than a certain value, is a simple linear search the best here(for loop from beginning to end of array)? It seems like some other search algorithm like binary or whatever would be of no...
2
1872
by: willamette3597 | last post by:
Could Someone tell me Where can I get The result though the Binary Search eg. max , min , mid ,want; While ( max > min ) { mid = (min + max )/2 ; if ( mid > want ) max = mid + 1; else min = mid -1 ; Line1 :
3
1336
by: Peter Schmitz | last post by:
Hi, one of the main task of my currently developed application is to search in small buffers for given patterns (average buffer size 1000 bytes). Now, for some reasons I can't use the provided C std libs, so I need to implement my own - but unfortunately I cannot find any hints about how to program such an algorithm, so that it is really...
10
9756
by: free2cric | last post by:
Hi, I have a single link list which is sorted. structure of which is like typedef struct mylist { int num; struct mylist *next;
11
2405
by: Bob Rock | last post by:
Hello, I have an array of strings and need to find the matching one with the fastest possible code. I decided to order the array and then write a binary search algo. What I came up with is the following. I noticed that if I set: int upper = strings.GetUpperBound(0); I never match the last element in the array (i.e. "iii")
1
1045
by: phanipep | last post by:
When is the binary search used for searching in a list? Give the binary search algorithm. Compare the performance of binary search with linear search?
1
1616
by: Channveer | last post by:
how to write the C code in Linux to find the time taken by the binary search algorithm ?
0
7478
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7410
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7668
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7437
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7773
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5343
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4960
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3466
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1025
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.