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

1 Answer

0 votes
// ceiling of N = the smallest element in an array greater than or equal to N

function find_the_ceiling(arr, N) {
    const size = arr.length;
    
    if (N <= arr[0]) {
        return 0;
    }
    
    for (let i = 0; i < size; i++) {
        if (arr[i] == N) {
            return i;
        }
        if (arr[i] < N && arr[i + 1] >= N) {
            return i + 1;
        }
    }
    
    return -1;
}

const arr = [1, 2, 7, 8, 15, 19, 20, 24, 28];
const N = 9;

const index = find_the_ceiling(arr, N);

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




/*
run:
   
The ceiling of 9 is 15

*/

 



answered Jan 20, 2024 by avibootz

Related questions

1 answer 101 views
1 answer 119 views
1 answer 162 views
1 answer 149 views
1 answer 99 views
1 answer 115 views
...