Binary Search Algorithm

Finding Contact from Telephone Directory

                What will you do, if you have to find out contact number in an old fashioned Telephone Directory? 

One thing you might do is flipping pages from beginning until you reach the page with Contact name starting with the First letter of your query. This method takes fewer efforts if you want to find out contact with Initial from starting alphabets of the alphabetical order. The same method takes more flipping of pages if you want to find out contact with Initial from last letters of alphabets of the alphabetical order.
Another easy and more accepted method than former is to open Telephone Directory at the middle
and check out current page. If it contains query’s Initial letter, then search complete. If it contains contacts with initial before query’s initial, then Second half of the directory remains to search Else First half of the Directory search. Then you go through the same process opening the middle of remaining Searchable Directory until you complete your search. This method is more efficient than first regardless of Query’s initial. If we cannot have the query, has to choose one of the methods Then this is better than the former one.

Other Searching Cases 
Suppose, you have one of those big books (let’s say 1000 pages long). Unfortunately, you forgot your book at home on the table and your Dog chewed some of the pages. Now you want to check whether page no. 345 is intact or chewed out. Another case is that I think of a number from 1 to 100 and you have to guess it in minimum chances. Each time you guess a number, I would reply to go lower or go higher and once you guess the number correctly the guesses that it took you reach it will be counted. In this both cases you can apply above two methods to find out the answer. You can go sequentially or You can eliminate half possibilities at the time. 

 Linear Search And Binary Search

Above mention, the First method of search in a sequence is called Linear Search. Second Method of each time eliminate half possibilities is called Binary Search. Binary search has restrictions on some cases. You cannot perform the binary search on randomly organized elements. Binary search can be performed on any range of data in which result has borderline of its after elements and before elements.




Now, when we understood what is binary search we can implement it in any Programming Language. I demonstrate implementation of searching integer in array of integers by both ways linear Search and Binary Search in C/C++.
Linear Search
Binary Search


Programming Puzzle

 

                One building has 100 floors. Egg will break if we throw it from Nth floor And Same egg will not break if we throw from (N-1)th floor. SO puzzle is to find out number of minimum throws to get N?
Write the answer in the comments and also explain your method.

Comments