Skip to Content
40 Algorithms Every Programmer Should Know
book

40 Algorithms Every Programmer Should Know

by Imran Ahmad
June 2020
Intermediate to advanced
382 pages
11h 39m
English
Packt Publishing
Content preview from 40 Algorithms Every Programmer Should Know

Binary Search

The pre-requisite of the binary search algorithm is sorted data. The algorithm iteratively divides a list into two parts and keeps a track of the lowest and highest indices until it finds the value it is looking for:

def BinarySearch(list, item):    first = 0    last = len(list)-1    found = False while first<=last and not found:             midpoint = (first + last)//2             if list[midpoint] == item:                     found = True             else:                     if item < list[midpoint]:                             last = midpoint-1                     else:                             first = midpoint+1     return found

The output is as follows:

Note that calling the BinarySearch function will return True if the value is found in the input list.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

50 Algorithms Every Programmer Should Know - Second Edition

50 Algorithms Every Programmer Should Know - Second Edition

Imran Ahmad
Grokking Algorithms

Grokking Algorithms

Aditya Bhargava

Publisher Resources

ISBN: 9781789801217Supplemental Content