Open In App

Ceiling in a sorted array

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
73 Likes
Like
Report

Given a sorted array and a value x, find index of the ceiling of x. The ceiling of x is the smallest element in an array greater than or equal to x.

Note: In case of multiple occurrences of ceiling of x, return the index of the first occurrence.

Examples : 

Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x = 5
Output: 2
Explanation: Smallest number greater than 5 is 8, whose index is 2.

Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x = 20
Output: -1
Explanation: No element greater than 20 is found. So output is -1.

Input: arr[] = [1, 1, 2, 8, 10, 10, 12, 19], x = 0
Output: 0
Explanation: Smallest number greater than 0 is 1, whose indices are 0 and 1. The index of the first occurrence is 0.

[Naive Method] - Linear Search - O(n) Time and O(1) Space

  1. If x is smaller than or equal to the first element in the array then return 0(index of the first element).
  2. Else linearly search for an index i such that x lies between arr[i] and arr[i+1]. 
  3. If we do not find an index i in step 2, then return -1. 
C++
C Java Python C# JavaScript

Output
ceiling of 3 is 8

[Expected Approach] - Binary Search - O(Log n) Time and O(1) Space

Since the input array is sorted, we can use binary search.

  • Find the mid point.
  • Else If arr[mid] < x, go to the right side
  • Else (arr[mid] >= x), we found a potential candidate for ceiling. Go to the left side and try finding a smaller value which is greater than or equal to x.

Let us understand the approach with an example

arr = [1, 2, 8, 10, 10, 12, 19] , x = 3

Initial: lo = 0, hi = 6, mid = 3 → arr[3] = 10 (res = 10, Move Left)

Step 2: lo = 0, hi = 2, mid = 1 → arr[1] = 2 (Move Right)

Step 3: lo = 2, hi = 2, mid = 2 → arr[2] = 8 (res = 8, Move Left)

Final: lo > hi, return res = 2

C++
C Java Python C# JavaScript

Output
Ceiling of 3 is 8

Using Library Methods

We can use the following library methods in different languages.

The lower_bound() method in C++, Arrays.binarySearch() in Java and bisect_left() in Python

C++
Java Python C# JavaScript

Output
Ceil Element of 8 is 8

Related Articles: 
Floor in a Sorted Array 
Find floor and ceil in an unsorted array=


Next Article

Similar Reads