

Here is a Python code that implements the binary search algorithm:

```
def binary_search(arr, x):
    low = 0
    high = len(arr) - 1
    mid = 0

    while low <= high:

        mid = (high + low) // 2

        # Check if x is present at mid
        if arr[mid] < x:
            low = mid + 1

        # If x is greater, ignore left half
        elif arr[mid] > x:
            high = mid - 1

        # If x is smaller, ignore right half
        else:
            return mid

    # If we reach here, then the element
    # was not present
    return -1

# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10

# Function call
result = binary_search(arr, x)

if result != -1:
    print("Element is present at index", str(result))
else:
    print("Element is not present in array")
```

This code defines a function `binary_search` that takes an array `arr` and a value `x` as input. It initializes the `low` and `high` variables to represent the range of the array to search. In each iteration, it calculates the `mid` value as the average of `low` and `high`. If `x` is less than the value at `mid`, it updates `low` to `mid + 1`. If `x` is greater, it updates `high` to `mid - 1`. If `x` is equal to the value at `mid`, it returns `mid` as the index where `x` is found. If the loop ends without finding `x`, it returns `-1` to indicate that `x` is not in the array.

The binary search algorithm is a classic algorithm for searching sorted lists. It is often used in computer science and is a fundamental part of many algorithms and data structures.