CodeChef is a non-commercial competitive programming community
Login
Username (New User? Signup) Password (Forgot Password?)
Signup
Login or
Signup with
Connect
Note
  • Publicize your achievements on your Facebook Wall.
  • Challenge your friends or ask them for help.

Site Navigation

  • PRACTICE
    • Easy
    • Medium
    • Hard
    • Challenge
    • Peer
  • COMPETE
    • All Contests
    • June Long 2012
    • May Cook-Off
    • May Long 2012
  • DISCUSS
    • Forums
    • Blog
    • Wiki
    • Facebook
    • Twitter
  • COMMUNITY
    • CodeChef Meetups
    • Campus Chapters
    • Host your Contest
    • User Groups
    • CodeChef TechTalks
    • All Educational Initiatives
  • HELP
    • Frequently Asked Questions
    • FAQ for problem setters
    • Problem Setting
    • Tutorials
    • Long Contest Ranks
    • Short Contest Ranks
    • Event Calendar
  • ABOUT
    • About CodeChef
    • Team CodeChef
    • Press Room
    • CodeChef Financials
    • CodeChef Sponsorships
    • CEO's Corner
    • Contact Us
    • About Directi
Home » Wiki » Tutorial for binary search

Tutorial for binary search

 

Binary search

 

 

Binary search involves dividing the search space by 2 in each iteration to finally arrive at a very small and trivial space.

 

 

Binary Search in an array

Consider a sorted array A[1... n ] with n-elements. Now we want to find the position of a number x within this array. We can do this using binary search with a complexity of O( log n ).

 

Algorithm

Iterative binary search

binary_search( A[1..n], v )
{
    lo := 1
    hi := n
    while( lo <= hi )
    {
        mid := (lo+hi)/2
        if( a[mid] == v )
            return true;
        if( a[mid] > v )
            hi = mid-1;
        else
            lo = mid+1;
    }
    return false;
}

Recursive binary search

binary_search( A[1..n], v, lo, hi )
{

mid := (lo+hi)/2
if( a[mid] == v )
return true;
if( lo >= hi )
return false;
if( a[mid] > v )
return binary_search( A, v, lo, mid-1 );
else
return binary_search( A, v, mid+1, hi );

}

 

Inbuilt-binary search

C++

C++ has 3 functions that are a part of the <algorithms> and are part of the std namespace.

They are binary_search, lower_bound, upper_bound

To search in an array a with n-elements we can use this

[code]binary_search( a, a+n, v )[/code]

where v is the value we are searching for.

 

binary_search returns a boolean value, telling if the value v exists or not.

lower_bound and upper_bound return the pointer locations where the value might be present.

Lower bound returns the i-th location in the array where the either i-1 < 0 or a[i-1] < v

Upper bound returns the i-th location in the array where either i is n or a[i] <= v

 

For e.g.

consider this array

1 2 2 3 3 3 3 5 7 7

we are searching for value 3

1 2 2 3 3 3 3 5 7 7

The lower position 3 is returned by lower bound and the upper one by upper bound.

We can similary use this on vectors, but lower bound and upper bound would return iterators instead of pointers.

For more information you can read the algorithms class here

Java Library

The Java library has inbuilt binary search in the Arrays and Collections class. You can read more here and here

 

Problems involving binary search in an array.

http://www.spoj.pl/problems/ABCDEF

http://www.spoj.pl/problems/NOTATRI

http://www.spoj.pl/problems/SCALE

http://www.spoj.pl/problems/SUMFOUR

http://www.spoj.pl/problems/SUBSUMS

http://www.spoj.pl/problems/ANARC05B

http://www.spoj.pl/problems/RENT

 

 

 

Binary search on functions

 

Consider an increasing function f(x). Now if we are given a value y of f(x) and we wish to compute the root x of this value, then we can use binary search to compute it. However in practice Newton-Raphson and interpolation search are much better and come closer to the real root in much fewer iterations. However there are many more interesting applications of binary search other than on purely “mathematical“ functions.

 

Let us begin then. Consider a function f(x) which is increasing, examples of such functions are given below.

 

While these are not.

 

 

 

So how do we find an x if we are given a value of f(x).

The idea is pretty simple, however we must remember that we cannot get to the exact answer, but an approximate one. However we can define the precision to which we get close to the exact answer. Also, due to the nature of real numbers on computers, we use some slight modifications and avoid using pseudo-code. The following is the C++ implementation to find the root of any increasing function f(x)

 

 

 

double f( double x )
{
	//do something and solve
}

//basically this means inverse function
of x, but we must remember that f(x) is increasing
double f_inverse( double y )
{
	double lo = 0, hi = 1e30; //or choose
a higher value if the final answer may exceed 10^30
	
	//While the difference from the actual
root is not acceptable, or accurate enough
	while( fabs( lo-hi ) > 1e-9 )
	{
		double mid = (lo+hi)/2;
		if( f( mid ) < y )
			lo = mid;
		else
			hi = mid;
	}
	return  (lo+mid)/2;
}

 

Similary we can also use binary to evalute decreasing functions.

 

Exercise :

 

Solve the following problems to get a hang of using binary search

Given integers a and b ( a, b <= 2*109 )

Find a real number x such that xa = b

You cannot use any inbuilt math libraries to solve this.

 

 

Find the smallest number n such that factorial n has exactly k-digits, or report that no such number exists ( Note that you will be working with discrete integers and not real numbers here )

 

Problems to practice

http://www.spoj.pl/problems/PIE

 

You can try to solve these problems which are hard versions of binary search

http://www.spoj.pl/problems/MKUHAR

http://www.spoj.pl/problems/SVADA

http://www.spoj.pl/problems/SUBS

 

 

 

 


Comments

  • Login or Register to post a comment.

can any body please send me

pkpraveen052 @ 20 Mar 2012 07:47 PM
can any body please send me the code for binary search in COBOL>>>>.
CodeChef is a non-commercial competitive programming community
  • About CodeChef
  • About Directi
  • CEO's Corner
  • C-Programming
  • Programming Languages
  • Contact Us
© 2009 Directi Group. All Rights Reserved. CodeChef uses SPOJ © by Sphere Research Labs
In order to report copyright violations of any kind, send in an email to copyright@codechef.com
CodeChef a product of Directi
The time now is:
CodeChef - A Platform for Aspiring Programmers

CodeChef was created as a platform to help programmers make it big in the world of algorithms, computer programming and programming contests. At CodeChef we work hard to revive the geek in you by hosting a programming contest at the start of the month and another smaller programming challenge in the middle of the month. We also aim to have training sessions and discussions related to algorithms, binary search, technicalities like array size and the likes. Apart from providing a platform for programming competitions, CodeChef also has various algorithm tutorials and forum discussions to help those who are new to the world of computer programming.

Practice Section - A Place to hone your 'Computer Programming Skills'

Try your hand at one of our many practice problems and submit your solution in a language of your choice. Our programming contest judge accepts solutions in over 35+ programming languages. Preparing for coding contests were never this much fun! Receive points, and move up through the CodeChef ranks. Use our practice section to better prepare yourself for the multiple programming challenges that take place through-out the month on CodeChef.

Compete - Monthly Programming Contests and Cook-offs

Here is where you can show off your computer programming skills. Take part in our 10 day long monthly coding contest and the shorter format Cook-off coding contest. Put yourself up for recognition and win great prizes. Our programming contests have prizes worth up to Rs.20,000 and $700lots more CodeChef goodies up for grabs.

Discuss

Are you new to computer programming? Do you need help with algorithms? Then be a part of CodeChef's Forums and interact with all our programmers - they love helping out other programmers and sharing their ideas. Have discussions around binary search, array size, branch-and-bound, Dijkstra's algorithm, Encryption algorithm and more by visiting the CodeChef Forums and Wiki section.

CodeChef Community

As part of our Educational initiative, we give institutes the opportunity to associate with CodeChef in the form of Campus Chapters. Hosting online programming competitions is not the only feature on CodeChef. You can also host a coding contest for your institute on CodeChef, organize an algorithm event and be a guest author on our blog.

Go For Gold

The Go for Gold Initiative was launched about a year after CodeChef was incepted, to help prepare Indian students for the ACM ICPC World Finals competition. In the run up to the ACM ICPC competition, the Go for Gold initiative uses CodeChef as a platform to train students for the ACM ICPC competition via multiple warm up contests. As an added incentive the Go for Gold initiative is also offering over Rs.8 lacs to the Indian team that beats the 29th position at the ACM ICPC world finals. Find out more about the Go for Gold and the ACM ICPC competition here.

Domain Name Registration, Web hosting, and Website Design provided by BigRock.com