awelgorithms

Find an exact match by binary search

Updated

Exact find probes mid on the closed range. Equal returns. a[mid] < target sets L = mid+1. a[mid] > target sets R = mid-1. Repeat while L <= R.

What to focus on

mid = Math.floor((L+R)/2). Sorted input only. Equal returns; a miss drops a half.

Worked examples

hit mid first

a = [1, 4, 9], target 4
  1. L=0 R=2 mid=1 a[1]=4 equals 4

Result: found at 1

hit after a drop

a = [1, 2, 3, 4, 9], target 4
  1. L=0 R=4 mid=2 a[2]=3<4 so L=3
  2. L=3 R=4 mid=3 a[3]=4 equals 4

Result: found at 3

one cell hit

a = [7], target 7
  1. L=0 R=0 mid=0 a[0]=7 equals 7

Result: found at 0

Try it

Write exactFind(a, t). a is a sorted array. t is the target. L, mid, and R are indices. Sorted means a[i] ≤ a[i+1]. mid = Math.floor((L+R)/2). Return the index of t. [1, 4, 9] t=4 → found at 1 [1, 2, 3, 4, 9] t=4 → found at 3 [7] t=7 → found at 0

a is sorted non-decreasing and non-empty. The target exists in a. L, mid, and R are indices.