Calculate Floor & Ceiling
Ceil The Floor
Since the array is sorted, we can use binary search to efficiently find:
Floor → greatest number ≤
x
.Ceiling → smallest number ≥
x
.
Binary search helps narrow down both floor and ceiling in O(log n) time.
Steps
Initialize
floor = -1
andceiling = -1
.Use binary search on the array:
If
a[mid] == x
, both floor and ceiling arex
.If
a[mid] < x
, updatefloor = a[mid]
and move right.If
a[mid] > x
, updateceiling = a[mid]
and move left.
Once the loop ends, return
[floor, ceiling]
.
Complexity
Space Complexity
Time Complexity
Code
Last updated