What if you could find the closest match in a huge list instantly without checking every item?
Why Floor and Ceil in Sorted Array in DSA Javascript?
Imagine you have a long list of sorted numbers, like heights of students in a class. You want to quickly find the closest height that is just smaller or equal (floor) or just bigger or equal (ceil) to a given height.
If you try to check each number one by one from the start, it will take a lot of time, especially if the list is very long. You might also make mistakes by missing the closest smaller or bigger number.
Using the floor and ceil concept with a smart search method, you can quickly jump to the right place in the list without checking every number. This saves time and avoids errors.
function findFloor(arr, x) {
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] <= x) return arr[i];
}
return null;
}function findFloor(arr, x) {
let left = 0, right = arr.length - 1, floor = null;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] <= x) {
floor = arr[mid];
left = mid + 1;
} else {
right = mid - 1;
}
}
return floor;
}This lets you find the closest smaller or bigger number in a sorted list instantly, making your programs faster and smarter.
When booking a flight, you want to find the closest available seat price that is just below or above your budget. Floor and ceil help find these prices quickly.
Manual search is slow and error-prone for large sorted lists.
Floor and ceil with binary search find closest smaller or bigger values fast.
This technique improves speed and accuracy in many real-world tasks.