Binary Search Algorithm: Explanation and Python Tutorial. Binary search is the powerhouse of computer science... Pretty much. One of the most basic introductory concepts in algorithms is binary search, but don't be fooled, binary search is incredibly powerful. Basically, the idea behind it is you are given a (sorted) list of items, you can leverage the sorted-ness to determine where something is much faster than scanning the whole list.

Binary search is the powerhouse of computer science... Pretty much. One of the most basic introductory concepts in algorithms is binary search, but don't be fooled, binary search is incredibly powerful. Basically, the idea behind it is you are given a (sorted) list of items, you can leverage the sorted-ness to determine where something is much faster than scanning the whole list.

Let's start with guessing a random number between 1 to 10. One way we could do it is to scan the entire list one at a time.. 1, 2, 3... until we get to the right number. But, this is slow! Instead, we can use the computer's feedback to cut down the possibility space in half every time, if we start guessing from the middle. This is what we call divide-and-conquer. The whole gist of binary search is based on this principle.

In a sorted list, we can first guess the middle element and after receiving feedback, we can narrow down the possibilities to either side of that element (if it's not that element itself). We repeat this process until we have either found the element or determined that it's not present.

If our list is "n" elements long, binary search only takes a maximum of log(n) tries to find the answer, whereas linear (naive) search takes a maximum of n tries and average of n/2 tries. This means.. for a list of 1000 items, binary search takes 10 tries when linear search takes on average 500, but could take up to 1000 (and that's assuming the value you're looking for is in the list)!!

Understood? Good. Now we'll code it up and I'll show you exactly how much faster binary search is, compared to naive search!

Link to code: https://github.com/kying18/beginner-projects/blob/master/binary_search.py

🔵 Intellipaat Data Science with Python course: https://intellipaat.com/python-for-data-science-training/In this Data Science With Python Training video, you...

In Conversation With Dr Suman Sanyal, NIIT University,he shares his insights on how universities can contribute to this highly promising sector and what aspirants can do to build a successful data science career.

Enroll in our Data Science with Python training in Chennai. Best Data Science with Python Training courses in Chennai for 100% Job Placements Support.

🔥Intellipaat Python for Data Science Course: https://intellipaat.com/python-for-data-science-training/In this python for data science video you will learn e...

Master Applied Data Science with Python and get noticed by the top Hiring Companies with IgmGuru's Data Science with Python Certification Program. Enroll Now