
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
Advertisements