awelgorithms

Upper bound is the first index greater

Updated

Upper bound is the first index i with a[i] > target, or n if none. Equals are still too small for this cut: if a[mid] <= target then L = mid+1 else R = mid.

What to focus on

Start L=0, R=n. Loop while L < R. Return L. Upper bound of 4 in [1, 4, 4, 9] is index 3.

Worked examples

first > 4

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

Result: upper bound 3

first > 1

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

Result: upper bound 1

past the only slot

a = [7], target 7
  1. L=0 R=1 mid=0 a[0]=7 <=7 so L=1
  2. L=1 R=1

Result: upper bound 1

Try it

Write upperBound(a, t). a is a sorted array. t is the target. L, mid, and R are indices. R starts at n. If a[mid] <= t then L = mid+1, else R = mid. Return the first index i with a[i] > t, or n. [1, 4, 4, 9] t=4 must return 3. [1, 4, 4, 9] t=4 → 3 [1, 4, 9] t=1 → 1 [7] t=7 → 1

a is sorted non-decreasing and non-empty. t is an integer. L, mid, and R are indices.