- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find floor and ceil in an unsorted array using C++.
Here we will see how to find the floor and ceiling in an unsorted array. The floor value is larger element which is smaller than or equal to x, and the ceiling value is smallest value which is larger than x. If the array A = [5, 6, 8, 9, 6, 5, 5, 6], and x is 7, then the floor value is 6, and the ceiling value is 8.
To solve this problem, we will follow the linear search approach. We will traverse the array and track two distances with respect to x.
- Min distance of element greater than or equal to x
- Min distance of element less than or equal to x
- Finally, a print element with min distance
Example
#include<iostream> using namespace std; void floorCeilingPair(int arr[], int n, int x) { int floor_index, ceiling_index; int floor_dist = INT_MAX, ceil_dist = INT_MAX; for (int i=0; i<n; i++) { if (arr[i] >= x && ceil_dist > (arr[i] - x)) { ceiling_index = i; ceil_dist = arr[i] - x; } if (arr[i] <= x && floor_dist > (x - arr[i])) { floor_index = i; floor_dist = x - arr[i]; } } if (floor_dist == INT_MAX) cout << "Floor not found" << endl; else cout << "Floor value is " << arr[floor_index] << endl; if (ceil_dist == INT_MAX) cout << "Ceiling not found" << endl; else cout << "Ceil value is " << arr[ceiling_index] << endl; } int main() { int arr[] = {5, 6, 8, 9, 6, 5, 5, 6}; int n = sizeof(arr)/sizeof(int); int x = 7; floorCeilingPair(arr, n, x); }
Output
Floor value is 6 Ceil value is 8
- Related Articles
- Finding Floor and Ceil of a Sorted Array using C++ STL
- Ceil and floor functions in C++
- Floor and Ceil from a BST in C++
- floor() and ceil() function Python
- Python – PyTorch ceil() and floor() methods
- Find k closest numbers in an unsorted array in C++
- Find start and ending index of an element in an unsorted array in C++
- Find Mean and Median of an unsorted Array in Java
- Find the largest pair sum in an unsorted array in C++
- Find ceil of a/b without using ceil() function in C++.
- Precision of floating point numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())
- Program for Mean and median of an unsorted array in C++
- k-th missing element in an unsorted array in C++
- Swift Program to Find Mean of an Unsorted Array
- Swift Program to Find Median of an Unsorted Array

Advertisements