## This article provides a brief introduction to **binary search in Python**. Binary search is a part of computer science algorithms. Binary means that two similar 0 and 1 are a good example of a binary number system in computer science.

## Introduction:

It is called a binary search because it checks whether the middle element of the array is the element you are looking for. Otherwise, the list will be split into two parts. Take one of the newly created subarrays as an array and do with it what you previously did with the original array. This is a dome until you find the desired element.

Binary search uses some sorted elements in an array or list.

Next, create the first, middle, and last three parameters. Now create a loop and run it until the element you are looking for is not found.

Next, first check to see if the center element of the array contains the element you are looking for.

### Recursive binary search in Python

There are some important concepts you need to understand when using this method. First, the length of an array always changes. To track this, we use the starting point of each array. This simply means that whenever you retrieve an array, it takes an intermediate position with respect to the initial value and length of the array. When you split an array to get a subarray, you get a new starting position and a new intermediate position.

**binary search in Python ** function we will define now takes four parameters. The first is a list, which acts as a dictionary for binary search. The second and third indicate the starting position and length of the target array. These two are used to find the average. Since this algorithm involves fetching functions, these two need to be dynamic and cannot be hard-coded. Hardcoding these will cause your function to get stuck in an infinite loop because each time you call the function, the values will be the same and you will get the same average. With all this important information, let’s take a look at Python’s first binary search algorithm.

# Method one def binarySearch (values, l, r, element): # l is the starting reference to find the middle. # It will keep changing time we split the array to get subarrays. # Hence it is not hard coded into the algorithm. # It won't make much importance to the user since the user needs to know the first middle point is in reference with the first index which is zero. # Therefore when calling the function, l will be 0. # R is the lenght of the list. # Python's len() function gives the accurate lenght but indexing starts at one value less. # Hence the lenght will be one value less. # Check if the list has not been exhausted. if r >= l: # We are checking i mid = l + (r - l) // 2 # We start at the middle of the list and check if the element if values[mid] == element: return "Element " + str(element) + " is at " + str(mid + 1) # We check if the element is on the left side of the split array elif values[mid] > element: return binarySearch(values, l, mid-1, element) # Otherwise, the element is in the right side of the split array. else: return binarySearch(values, mid + 1, r, element) # If we fail to find the element in the list we return an absent statement. else: # Element is not present in the array return "Element " + str(element) + " is not in the list"

### Three conditions apply here.

**1.Elements match **

**2. The center element is smaller than the element you are looking for **

**3. The center element is larger than the element you are looking for**

##### If the elements match, the loop terminates successfully.

Otherwise, if the center element is smaller than the element you are looking for, assign the first element one larger than the center element and search for the element in the same way as before. first = middle + 1

The third point is the opposite.

If the center element is greater than the searched element, assign the element one smaller than the center element as the last element and search for the element in the same way as before.

last = middle – 1

myList = [12, 23, 34, 45, 56, 67] mysearch = 23 def binaryFun(myList, mysearch): first = 0 last = len(myList) - 1 mid = 0 while first<=last: mid = (first + last)//2 if myList[mid] == mysearch: return mid elif mysearch > myList[mid]: first = mid + 1 elif mysearch < myList[mid]: last = mid - 1 return "not found" result = binaryFun(myList, mysearch) print(result)

### Output:

**1**

### Loop binary search in Python:

This method is a little simpler than the first method, but the calculations are quite complex. Unlike the previous binary search, there is no recursive function. This means you can hardcode some values since you don’t remember the functions. Instead of a recursive function, binary for i love you implement a loop that increments these values. Since we are not looping over the list, a while loop is used. When we iterate over a list, we don’t split the list either, so the binary search turns into a linear search. The while loop runs as long as the subarray is not exhausted. Let’s take a look at the second binary search algorithm in Python

def binarySearch2(values, element): # The function takes two parameters. # Values is the list that acts as a dictionary to search the element from. # The element is the value being searched for. start = 0 # This is the beginning value of the array in question. # The value will change depending on the array. length = len(values)-1 # This is the length of the array in question. # This number will vary on whether the list is split or not. while start <= length and element >= values[start] and element <=values[length]: #This means that the search loop will run as long as these three conditions are met. # The first is as long as the list has not been exhausted. As long as the start is smaller than or equal to the lenght # The second is that the element is larger than the start value on the list. # The last one is that the element is smaller than the last element on the list. # Find the middle point. mid = start + int(((float(length-start)/(values[length]-values[start]))*(element-values[start]))) # This calculation simply adds the previous mid to an incremented value. # Compare the middle value on the list to the element being searched for. if values[mid] == element: # If we find the element, we print out its value position on the list. return "Element " + str(element) + " is at " + str(mid + 1) if values[mid] < element: #If we fail to get the element in this current loop, we increment and move to the next loop. start = mid + 1 #If we fail to get the number completely, we print out an absent statement. return "Element " + str(element) + " has not been found."

### Thank you for reading my post to the end. Please leave your comments or questions below.

## You Can Also Read:

What are some good Python Projects for Beginners?

Python Pandas : A Complete Introduction for Beginners

Automate Instagram Login Using Python

How to Build a Simple Auto Login Bot with Python