VOOZH about

URL: https://www.geeksforgeeks.org/c/implementing-upper_bound-and-lower_bound-in-c/

⇱ Implementing upper_bound() and lower_bound() in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Implementing upper_bound() and lower_bound() in C

Last Updated : 12 Jul, 2025

Given a sorted array arr[] of N integers and a number K, the task is to write the C program to find the upper_bound() and lower_bound() of K in the given array.
Examples: 
 

Input: arr[] = {4, 6, 10, 12, 18, 20}, K = 6 
Output: 
Lower bound of 6 is 6 at index 1 
Upper bound of 6 is 10 at index 2
Input: arr[] = {4, 6, 10, 12, 18, 20}, K = 20 
Output: 
Lower bound of 20 is 20 at index 5 
Upper bound doesn't exist 
 


 


Approach: The idea is to use Binary Search. Below are the steps: 
 

  • For lower_bound(): 
    1. Initialise the startIndex as 0 and endIndex as N - 1.
    2. Compare K with the middle element(say arr[mid]) of the array.
    3. If the middle element is greater equals to K then update the endIndex as a middle index(mid).
    4. Else Update startIndex as mid + 1.
    5. Repeat the above steps until startIndex is less than endIndex.
    6. After all the above steps the startIndex is the lower_bound of K in the given array.
  • For upper_bound(): 
    1. Initialise the startIndex as 0 and endIndex as N - 1.
    2. Compare K with the middle element(say arr[mid]) of the array.
    3. If the middle element is less than equals to K then update the startIndex as middle index + 1(mid + 1).
    4. Else Update endIndex as mid.
    5. Repeat the above steps until startIndex is less than endIndex.
    6. After all the above steps the startIndex is the upper_bound of K in the given array.


Below is the iterative and recursive implementation of the above approach:
 


Output: 
Lower bound of 6 is 6 at index 1
 Upper bound of 6 is 10 at index 2

 

Time Complexity: O(log2 N), where N is the number of elements in the array.
 Auxiliary Space: O(1).

Comment
Article Tags:
Article Tags: