How to find the floor of N in a sorted array with Node.js

1 Answer

0 votes
// floor of N = the largest element in the array smaller than or equal to N

function find_the_floor(arr, N) {
    const size = arr.length;
    
    if (N >= arr[size - 1]) {
        return size - 1;
    }
    
    if (N < arr[0]) {
        return -1;
    }
    
    for (let i = 1; i < size; i++) {
        if (arr[i] > N) {
            return i - 1;
        }
    }
    return -1;
}
        
const arr = [1, 2, 7, 8, 15, 19, 20, 24, 28];
const N = 17;

const index = find_the_floor(arr, N);

if (index == -1) {
    console.log("The floor doesn\'t exist in array");
}
else {
    console.log("The floor of " + N + " is " + arr[index]);
}




/*
run:
   
The floor of 17 is 15
       
*/

 



answered Jan 20, 2024 by avibootz
...