# Floor in a Sorted Array in C++

In this problem, we are given a sorted array arr[] and an integer value x. Our task is to create a program to find the floor in a sorted array.

Floor of X in sorted array arr is the largest element of the array arr[] which is smaller than or equal to x.

Let’s take an example to understand the problem

Input: arr[] = {2, 5, 6, 8, 9, 12, 21, 25}, x = 10
Output: 9

Explanation − In the above array 9 is the largest number which is smaller than or equal to 10.

## Solution Approach

A simple solution to the problem is directly by traversing the array and finding the elements that satisfy the condition. While traversing the array,

we will check each element, if it is greater than x, return the previous element as the floor of x.

## Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;

int findFloorSortedArray(int arr[], int n, int x){
if (x >= arr[n - 1])
return (n-1);
if (x < arr[0])
return -1;
for (int i = 1; i < n; i++)
if (arr[i] > x)
return (i - 1);
return -1;
}
int main(){
int arr[] = {2, 5, 6, 8, 9, 12, 21, 25};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int floorIndex = findFloorSortedArray(arr, n - 1, x);
if (floorIndex == -1)
cout<<"The floor of "<<x<<" doesn't exist in the array";
else
cout<<"The floor of "<<x<<" in the array is "<<arr[floorIndex];
return 0;
}

## Output

The floor of 10 in the array is 9

## Alternate method

An alternate method to solve the problem is by using the binary searching algorithm as the array is sorted and our task is based on finding values. In this solution, we will be searching for the element in the middle index of the array. Then according to the middle element, we will be further searching the number in the first half(smaller half) or second half (greater half) of the array. And continue this until the whole array is traversed or the element is found at the middle of a sub-array.

## Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;

int findFloorSortedArray(int arr[], int start, int end, int x){
if (start > end)
return -1;
if (x >= arr[end])
return end;
int mid = (start + end) / 2;
if (arr[mid] == x)
return mid;
if (mid > 0 && arr[mid - 1] <= x && x < arr[mid])
return mid - 1;
if (x < arr[mid])
return findFloorSortedArray(arr, start, mid - 1, x);
return findFloorSortedArray(arr, mid + 1, end, x);
}
int main(){
int arr[] = {2, 5, 6, 8, 9, 12, 21, 25};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int floorIndex = findFloorSortedArray(arr, 0, n - 1, x);
if (floorIndex == -1)
cout<<"The floor of "<<x<<" doesn't exist in the array";
else
cout<<"The floor of "<<x<<" in the array is "<<arr[floorIndex];
return 0;
}

## Output

The floor of 10 in the array is 9

Updated on: 01-Feb-2022

336 Views