I have an array below, the concept is to allow the user to enter a number and if the number is contained in the array, the program should display the number as well as the position of the number.
But if the number is not present, the message program should display "No such number exist in the array".

How can I do this using Binary Search.
:confused:

int A[] = {14,52,87,36,12,2,3,1};

One thing to note... Binary search requires an Ordered List,
and the array above is not ordered.

Assuming your arrays are ordered...
You could just use the pseudo-code for it...
http://en.wikipedia.org/wiki/Binary_search
Or better is to construct it yourself from scratch.

Start with L=0 (leftest element) R=9 say (Rightest element)
Your first guess is the middle one, so just take
M=Math.floor(L+R).

if array[M] is the value you want, you are done.
If array[M] is greater than the one you want, you can squash down the right hand side to restrict your range. So R=M-1.
If array[M] is smaller than the one you want, you can push up the left hand side to restrict your range. So L=M+1.

Then just repeat it, and you will get to your value very very quickly since binary search is exponential, so even if your array had as many elements as atoms in the universe, you would find your answer almost instantly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.