0
0
DSA Javascriptprogramming~3 mins

Why Floor and Ceil in Sorted Array in DSA Javascript?

Choose your learning style9 modes available
The Big Idea

What if you could find the closest match in a huge list instantly without checking every item?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
function findFloor(arr, x) {
  for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i] <= x) return arr[i];
  }
  return null;
}
After
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;
}
What It Enables

This lets you find the closest smaller or bigger number in a sorted list instantly, making your programs faster and smarter.

Real Life Example

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.

Key Takeaways

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.