CodeBlanks Logo Icon CodeBlanks

Left right pointers

Narrow the range with low and high pointers.

Left right pointers

Binary search defines the search range with left and right pointers. Initially left=0, right=n-1.

At each step, the middle is computed: mid = (left + right) // 2. Depending on the target, left or right is updated.

Range update

If the target is greater than arr[mid], left = mid + 1: search the right half. If smaller, right = mid - 1: search the left half.

Adding +1 and -1 prevents mid from being checked again. This is important to avoid infinite loops.

Practice Find mid

Write find_mid(left, right). Return the middle index. Print 4 with print(find_mid(0, 9)).

Starter code

solution.py
def find_mid(left, right):
    # Middle index

Sample solution

solution.py
def find_mid(left, right):
    # Middle index
    return (left + right) // 2
print(find_mid(0, 9))

Expected output

4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Mid computation

Question
mid = (left + ____) // 2
Answer
mid = (left + right) // 2

Explanation: right is right.

2 Left right pointers: match the terms

Term Meaning
left Left
right Right
mid Middle
left <= right Loop condition

3 What if target is greater than arr[mid]?

  • return mid
  • return -1
  • right = mid - 1
  • left = mid + 1 Correct answer

Explanation: left = mid + 1 is set.

All lessons in Beginner