How to find the ceiling of N in a sorted array with JavaScript

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, 14, 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 14
       
*/

 



answered Jan 20, 2024 by avibootz

Related questions

1 answer 198 views
1 answer 194 views
1 answer 215 views
1 answer 171 views
1 answer 200 views
1 answer 179 views
1 answer 189 views
...