Find floor and ceil in an unsorted array using C++.

C++Server Side ProgrammingProgramming

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
raja
Published on 29-Oct-2019 12:03:00
Advertisements