DeveloperBreeze

Binary Search in Python

python
# Function to perform binary search on a sorted array
def binary_search(arr, target):
    low, high = 0, len(arr) - 1

    while low <= high:
        mid = (low + high) // 2

        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1

    return -1

# Usage: Perform binary search on a sorted array
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 5
result = binary_search(arr, target)

Related Posts

More content you might like

Tutorial
javascript

JavaScript DSA (Data Structures and Algorithms) Tutorial: A Beginner's Guide

Data Structures and Algorithms (DSA) are fundamental concepts in computer science and software development. Understanding these concepts is crucial for writing efficient code and solving complex problems. This tutorial will introduce you to the basics of DSA using JavaScript, covering essential data structures and algorithms, and how they can be implemented in JavaScript.

Data structures are ways to organize and store data so that it can be accessed and modified efficiently. The choice of data structure can greatly affect the performance of your application, making it essential to understand when and how to use them.

Aug 30, 2024
Read More
Code
javascript

Prime Number Check and Prime Number Generation in JavaScript

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Generate Fibonacci Sequence

No preview available for this content.

Jan 26, 2024
Read More
Code
java

Swap Two Numbers Without Using a Temporary Variable

int a = 5, b = 10;

a = a + b;
b = a - b;
a = a - b;

System.out.println("a = " + a + ", b = " + b);

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!