Implement Binary Search Without Recursion in Python



To implement binary search without recursion, the program takes a sorted list and a key as input. It uses the Binary search method, which is an efficient way to find a specific item in a sorted list. It works by repeatedly dividing the list in half.

This method works by first comparing the key with the middle element of the list. If the key matches the middle element, the search is successful, and the index is returned. If the key is less than the middle element, the search continues on the left subarray; if it's greater, the search shifts to the right subarray.

Steps to Apply Binary Search Iteratively

The steps involved in implementing the binary search without recursion are as follows.

  • Define the Function and Initialize Variables

  • Apply Binary Search Logic

  • Return the Result

Defining the Function and Initialization

Start by defining a function that accepts a sorted list and the element to search for. Initialize variables for the starting index, ending index, and middle index.

  • Function Definition: Create a function that takes two parameters: the sorted list and the target element.

  • Initialization: Set the starting index to 0 and the ending index to the last index of the list.

The following code demonstrates the function definition and initialization.

def binary_search(sorted_list, target):  
    low = 0  
    high = len(sorted_list) - 1 

Apply Binary Search Logic

Use a while loop to continue searching as long as the starting index is less than or equal to the ending index. Inside the loop, calculate the middle index and compare the middle element with the target.

  • While Loop: Keep iterating until the starting index exceeds the ending index. Create a function that takes two parameters: the sorted list and the target element.

  • Middle Index Calculation: Calculate the middle index by averaging the starting and ending indices.

  • Element Comparison: Check if the middle element is equal to the target, less than the target, or greater than the target.

If the middle element is less than the target, search the right half. If it's greater, search the left half. If equal, return the index.

    while low <= high:  
        mid = (high + low) // 2  
        if sorted_list[mid] < target:  
            low = mid + 1  
        elif sorted_list[mid] > target:  
            high = mid - 1  
        else:  
            return mid

Return the Result

If the loop completes without finding the target, return -1 to indicate that the element is not in the list. Otherwise, return the index of the found element.

    return -1

Example Code

Following is the complete code that demonstrates the binary search implementation

def binary_search(sorted_list, target):  
    low = 0  
    high = len(sorted_list) - 1  
    
    while low <= high:  
        mid = (high + low) // 2  
        if sorted_list[mid] < target:  
            low = mid + 1  
        elif sorted_list[mid] > target:  
            high = mid - 1  
        else:  
            return mid  
    return -1  

# Example usage  
sorted_list = [1, 9, 11, 21, 34, 54, 67, 90]  
target_element = 1  
print("The list is:")  
print(sorted_list)  

result_index = binary_search(sorted_list, target_element)  

if result_index != -1:  
    print("Element found at index:", result_index)  
else:  
    print("Element not found!")

Output

The list is
[1, 9, 11, 21, 34, 54, 67, 90]
Element found at index  0
Updated on: 2024-12-12T17:32:55+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements