Search for a command to run...
Nearest value below and above x
Try your own input
Change the array and replay the algorithm from step one.
Current step
Floor of 5 is the largest value ≤ 5; ceil is the smallest value ≥ 5. Both are found the same way — record a candidate, then keep searching the side that might hold a better one. Note these return values, not indices.
Two Binary Searches
1function findFloor(nums, n, x) {2 let low = 0, high = n - 1;3 let ans = -1;4 5 while (low <= high) {6 const mid = Math.floor((low + high) / 2);7 8 // A candidate — a larger floor may lie right9 if (nums[mid] <= x) {10 ans = nums[mid];11 low = mid + 1;12 } else {13 high = mid - 1;14 }15 }16 return ans;17}18 19function findCeil(nums, n, x) {20 let low = 0, high = n - 1;21 let ans = -1;22 //x: 5n: 6floor: -1ceil: -123 while (low <= high) {24 const mid = Math.floor((low + high) / 2);25 26 // A candidate — a smaller ceil may lie left27 if (nums[mid] >= x) {28 ans = nums[mid];29 high = mid - 1;30 } else {31 low = mid + 1;32 }33 }34 return ans;35}36 37function getFloorAndCeil(nums, x) {38 const n = nums.length;39 const floor = findFloor(nums, n, x);40 const ceil = findCeil(nums, n, x);41 return [floor, ceil];42}