Finding Floor and Ceil of a Sorted Array using C++ STL


In this tutorial, we will be discussing a program to find the floor and ceil of a sorted array using C++ STL.

To find the floor and ceil of a sorted array we will use lower_bound() and upper_bound() functions from STL respectively.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//finding floor of given array
void printFloor(int arr[], int n1,
int findFloor[], int n2){
   int low;
   cout << "Floor : ";
   for (int i = 0; i < n2; i++) {
      low = (lower_bound(arr, arr + n1, findFloor[i]) - arr);
      if (arr[low] > findFloor[i])
         cout << arr[low - 1] << " ";
      else
         cout << arr[low] << " ";
   }
   cout << endl;
}
//fincding ceil of given array
void printCeil(int arr[], int n1,
int findCeil[], int n2){
   int up;
   cout << "Ceil : ";
   for (int i = 0; i < n2; i++) {
      up = (upper_bound(arr, arr + n1, findCeil[i]) - arr);
      if (arr[up] > findCeil[i] && arr[up - 1] == findCeil[i]) {
         cout << arr[up - 1] << " ";
      }
      else
         cout << arr[up] << " ";
   }
   cout << endl;
}
int main(){
   int arr[] = { 1, 2, 4, 7, 11, 12, 23, 30, 32 };
   int n1 = sizeof(arr) / sizeof(arr[0]);
   cout << "Original Array: ";
   for (unsigned int i = 0; i < n1; i++)
      cout << " " << arr[i];
   cout << "\n";
   int find[] = { 1, 3, 5, 7, 20, 24 };
   int n2 = sizeof(find) / sizeof(find[0]);
   cout << "Values: ";
   for (unsigned int i = 0; i < n2; i++)
      cout << find[i] << " ";
   cout << "\n";
   printFloor(arr, n1, find, n2);
   printCeil(arr, n1, find, n2);
   return 0;
}

Output

Original Array: 1 2 4 7 11 12 23 30 32
Values: 1 3 5 7 20 24
Floor : 1 2 4 7 12 23
Ceil : 1 4 7 7 23 30

Updated on: 23-Mar-2020

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements