mac

Mahaveer Magdum


Binary search in python

Published: Oct 7, 2022

4min read




Let’s talk about searching algorithm called Binary Search, and it’s applications. Usually it is used to find index of element from ’sorted ’ array.


This algorithm only work on sorted array, if array is not sorted then we have to sort it before using binary search.


How it works!


Binary search uses divide-and-conqure method. In this method you divide whole array in two equal part, and check for key element.


Steps:


  • 1) Calculate mid of array.

2) Check if desire element is same as mid (middle) element. Create two equal length array from it.


3) Or if desire element is greater than mid, then discard left side of array. Change mid = mid + 1 and repeat all steps again.


4) Otherwise discard right side of array and change mid = mid - 1. Repeat all steps again.