I agree (or if I am under 13 my parent or guardian agrees on my behalf) to the terms and conditions of use and that: - My test statistics may be published on the site leaderboard against my username - My teacher(s) can review my test scores - I can receive feedback on my tests from my teacher(s)
Computer Science & Programming solved. All in one platform.
1. To trial the platform and take tests, please take a few seconds to SIGN UP and SET UP FREE. 2. Searching for something specific? See our text overview of all tests. Includes 'real teacher' usevideos.
A binary search algorithm takes the data and keeps dividing it in half until it finds the item it is looking for.
How to code a Binary search - step by step
A step by step explanation of how to code a Binary search in python using a relevant example: searching a friend list (e.g. facebook) for a friend!
#1 Write a Python program to search using the binary search method
#2 Comment each line of the python solution below to show your understanding of the algorithm
Try it yourself
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
if item < item_list[mid]:
last = mid - 1
first = mid + 1
Explanation with Example
Imagine that you have a database of customers and want to search for the customer John Smith. We first need the database to be ordered into alphabetical order by surname. We then search for the record ‘John Smith’ by surname.
The binary search will split the database in half, and compare the midpoint (the middle name) to the name ‘John Smith’. It will see whether the midpoint comes before or after ‘Smith’ and will throw away the set of records that doesn’t contain ‘Smith’ as a surname. It will keep dividing the records in that way until it reaches two records left, one of which is ‘John Smith’. It will then throw away the other record and output John Smith’s details. Binary search effectively divides the data in half and throws away, or ‘bins’ the half that does not contain the search term. (Source: BBC Bitesize)
Above example represented as a flow chart
In pseudocode this would look like:
OUTPUT "Which customer do you want to find?"
INPUT user inputs John Smith
STORE the user's input in the customer_name variable
customer_found = False
(we need to create a flag that identifies if the customer is found)
WHILE customer_found = False:
Find midpoint of list
IF customer_name = record at midpoint of list THEN
customer_found = True
ELSE IF customer comes before the midpoint THEN
throw away the second half of the list
throw away the first part of the list
OUTPUT customer details