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

1 Answer

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

class Program {
    private static int find_the_ceiling(int[] arr, int N) {
    	int size = arr.length;
    		
    	if (N <= arr[0]) {
    		return 0;
    	}
    
    	for (int i = 0; i < size; i++) {
    		if (arr[i] == N) {
    			return i;
    		}
    		if (arr[i] < N && arr[i + 1] >= N) {
    			return i + 1;
    		}
    	}
    
    	return -1;
    }
    
    public static void main(String[] args) {
        int[] arr = {1, 2, 7, 8, 14, 19, 20, 24, 28};
	    int N = 9;

	    int index = find_the_ceiling(arr, N);

	    if (index == -1) {
		    System.out.print("The ceiling doesn't exist in array");
	    }
	    else  {
		    System.out.print("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 248 views
1 answer 215 views
1 answer 171 views
1 answer 200 views
1 answer 189 views
...