473,385 Members | 1,582 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,385 developers and data experts.

Binary Search

7
Binary search is used to locate a value in a sorted list of values.
It selects the middle element in the array of sorted values, and compares it with the target value; that is the key we are searhing for in the array.
If it islower than the target value then the search is made after that middle element and till the end of the array. If it is equal then the target value is found and the middle is returned. Otherwise, search is made from the beginning of the array till middle -1. If the lower limit is larger than the upper limit, the ones that determine the search area, then the target value is not in the array.

I present an example code for a binary search function.


Expand|Select|Wrap|Line Numbers
  1.  
  2. /**
  3.  *
  4.  *
  5.  *    FILE: bsearch.h
  6.  *
  7.  *
  8.  *    Description:
  9.  *
  10.  *        Function prototype for binarySearch function.
  11.  *
  12.  *
  13.  */
  14.  
  15.  
  16.  
  17. #ifndef _bsearch_h
  18.  
  19.  
  20.  
  21. #define _bsearch_h
  22.  
  23.  
  24.  
  25.  
  26.  
  27. /**
  28.  *
  29.  *    Synopsis:
  30.  *
  31.  *        int binarySearch( int a[], int key, int size )
  32.  *
  33.  *
  34.  *    Description:
  35.  *
  36.  *        Function binarySearch performs a binary search in a 
  37.  *        sorted array a searching for a key.
  38.  *
  39.  *
  40.  *    Parameters:
  41.  *
  42.  *        a[]: sorted array of integers.
  43.  *
  44.  *        key: key to be searched for in a[].
  45.  *
  46.  *        size: size of a[].
  47.  *
  48.  *
  49.  *    Assertions:
  50.  *
  51.  *        none.
  52.  *
  53.  *
  54.  *    Returns:
  55.  *
  56.  *        Function binarySearch returns -1 if key is not in a[].
  57.  *        Otherwise in returns the i, for which a[ i ] == key.
  58.  *
  59.  *
  60.  */
  61. int binarySearch( int a[], int key, int size );
  62.  
  63.  
  64.  
  65.  
  66.  
  67. #endif 


Expand|Select|Wrap|Line Numbers
  1. /**
  2.  *
  3.  *
  4.  *    FILE: binarySearch.c
  5.  *
  6.  *
  7.  *    Description:
  8.  *
  9.  *        File contains binarySearch functions declared in bsearch.h file.
  10.  *
  11.  *
  12.  */
  13.  
  14.  
  15.  
  16.  
  17.  
  18. #include "bsearch.h"
  19.  
  20.  
  21.  
  22.  
  23.  
  24. /**
  25.  *------------------------------------------------------------
  26.  *
  27.  *    Function _binarySearch is called by binarySearch function with
  28.  *    low = 0 and high = size - 1, to secure the search boundaries of 
  29.  *    the array.
  30.  *
  31.  *------------------------------------------------------------
  32.  */
  33. static int _binarySearch( int a[], int key, int low, int high );
  34.  
  35.  
  36.  
  37.  
  38.  
  39. int binarySearch( int a[], int key, int size ){
  40.  
  41.  
  42.  
  43.     return ( _binarySearch( a, key, 0, size - 1 ) );
  44.  
  45.  
  46.  
  47. }    //    int binarySearch( int a[], int key, int size )
  48.  
  49.  
  50.  
  51.  
  52. /**
  53.  *------------------------------------------------------------
  54.  *
  55.  *    Search key value in a[].
  56.  *
  57.  *------------------------------------------------------------
  58.  */
  59. static int _binarySearch( int a[], int key, int low, int high ){
  60.  
  61.  
  62.  
  63.     if ( low > high ){
  64.  
  65.  
  66.  
  67.         return ( -1 );                                /** key not found in a[]                                                */
  68.  
  69.  
  70.  
  71.     }
  72.     else{
  73.  
  74.  
  75.  
  76.         int middle = ( low + high ) / 2;
  77.  
  78.  
  79.  
  80.         if ( a[ middle ] == key ){
  81.  
  82.  
  83.  
  84.             return ( middle );                        /** key found in a[]                                                    */
  85.  
  86.  
  87.  
  88.         }
  89.         else if ( a[ middle ] < key ){
  90.  
  91.  
  92.  
  93.             /**
  94.              *
  95.              *    key we are searching is larger than the value of a[ middle ]
  96.              *    and since array is sorted, the search will continue in the side
  97.              *    after the middle index; that is from middle + 1 till high.
  98.              *
  99.              */
  100.             return ( _binarySearch( a, key, middle + 1, high ) );
  101.  
  102.  
  103.  
  104.         }
  105.         else{
  106.  
  107.  
  108.  
  109.             /**
  110.              *
  111.              *    key we are searching is lower than the value of a[ middle ]
  112.              *    and since array is sorted, the search will continue in the side
  113.              *    before the middle index; that is from low till high - 1.
  114.              *
  115.              */
  116.             return ( _binarySearch( a, key, low, middle - 1 ) );
  117.  
  118.  
  119.  
  120.         }
  121.  
  122.  
  123.  
  124.     }
  125.  
  126.  
  127.  
  128. }    //    static int _binarySearch( int a[], int key, int low, int high ) 

Expand|Select|Wrap|Line Numbers
  1. /**
  2.  *
  3.  *
  4.  *    FILE: main.c
  5.  *
  6.  *
  7.  *    Description:
  8.  *
  9.  *        Test binarySearch function.
  10.  *
  11.  *
  12.  */
  13.  
  14.  
  15.  
  16.  
  17.  
  18. #include "bsearch.h"
  19.  
  20.  
  21.  
  22. #include <assert.h>
  23.  
  24.  
  25.  
  26.  
  27.  
  28. /**
  29.  *
  30.  *    Simple check for binarySearch function
  31.  *
  32.  */
  33. int main( void ){
  34.  
  35.  
  36.  
  37.     int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
  38.  
  39.  
  40.  
  41.     int i;
  42.  
  43.  
  44.  
  45.     for ( i = 0 ; i < 21 ; ++i ){
  46.  
  47.  
  48.  
  49.         assert( binarySearch( a, i, 21 ) == i );
  50.  
  51.  
  52.  
  53.     }
  54.  
  55.  
  56.  
  57.     for ( ; i < 50 ; ++i ){
  58.  
  59.  
  60.  
  61.         assert( binarySearch( a, i, 21 ) == -1 );
  62.  
  63.  
  64.  
  65.     }
  66.  
  67.  
  68.  
  69.     return ( 0 );
  70.  
  71.  
  72.  
  73. }    //    int main( void ) 
Jun 15 '08 #1
0 6947

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

Similar topics

5
by: Ravi | last post by:
I recently had to write some code which required me to use a binary search tree (BST) due to running time concerns. I found that there is no BST class in the Standard C++ library. I have been told...
4
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,...
9
by: Hemang Shah | last post by:
Hello fellow Coders! ok, I"m trying to write a very simple application in C#. (Yes its my first program) What I want to do is : 1) Open a binary file 2) Search this file for a particular...
8
by: Gordon Knote | last post by:
Hi can anyone tell me what's the best way to search in binary content? Best if someone could post or link me to some source code (in C/C++). The search should be as fast as possible and it would...
1
by: Andrew | last post by:
Hi, im trying to create a small function which can create a binary tree from the entries in a text file and after that we can perform all the usual operations like search, insert and delete etc....
10
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;
2
by: Timmy | last post by:
The bigger problem is with the Binary Search. The program crashes when it's excuted. and Visual Studio 2005 indicates stack over flow and shows a break at that function. Sequential search is...
0
by: Vince Filby | last post by:
Hi, We are working with distributing Lucene.net. We have Master Index Server which takes responsibility of distributing the index searching to multiple Index Servers by calling the remote...
2
by: jhansi | last post by:
create a binary file and insert the records and query on those inserted record.. queries are: query based on search by name,search by age and search by designation. the problem is i have...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.