Skip to main content

Command Palette

Search for a command to run...

Binary Search Algorithm Implementation

Updated
1 min readView as Markdown
A

Aspiring DevOps Engineer • Sharing my knowledge via blogs

Here’s an implementation of the binary search algorithm in Python. This program takes an array of integers and a target element as input, returning the position of the element if found or stating that it’s not present.

Binary Search Implementation in Python

Step 1: Define the Binary Search Function

def binary_search(arr, target):
    left, right = 0, len(arr) - 1
while left <= right:
        mid = left + (right - left) // 2
        if arr[mid] == target:
            return mid 
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

Step 2: Using the Binary Search Function

You can test the function with an example:

arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
target = 7

functionresult = binary_search(arr, target)

if result != -1:
    print(f"Element {target} is present at index {result}.")
else:
    print(f"Element {target} is not present in the array.")

Example Output

Element 7 is present at index 3.

Conclusion

This program implements a binary search algorithm that efficiently searches for an element in a sorted array of integers. It returns the index of the element if found or indicates that it is not present. If you have any questions or need further assistance, feel free to ask!

More from this blog

Blissman's thoughts

104 posts