Open In App

Floor in a Sorted Array

Last Updated : 30 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a sorted array and a value x, the floor of x is the largest element in the array smaller than or equal to x. Write efficient functions to find the floor of x

Examples:

Input: arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 5
Output: 2
Explanation: 2 is the largest element in 
arr[] smaller than 5

Input: arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 20
Output: 19
Explanation: 19 is the largest element in
arr[] smaller than 20

Input : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 0
Output : -1
Explanation: Since floor doesn’t exist, output is -1.

Recommended Practice

Naive Approach: To solve the problem follow the below idea:

The idea is simple, traverse through the array and find the first element greater than x. The element just before the found element is the floor of x

Follow the given steps to solve the problem:

  • Traverse through the array from start to end.
  • If the current element is greater than x print the previous number and break out of the loop
  • If there is no number greater than x then print the last element
  • If the first number is greater than x then print that the floor of x doesn’t exist

Below is the implementation of the above approach:

C++




// C++ program to find floor of a given number
// in a sorted array
#include <iostream>
using namespace std;
 
/* An inefficient function to get
index of floor of x in arr[0..n-1] */
int floorSearch(int arr[], int n, int x)
{
    // If last element is smaller than x
    if (x >= arr[n - 1])
        return n - 1;
 
    // If first element is greater than x
    if (x < arr[0])
        return -1;
 
    // Linearly search for the first element
    // greater than x
    for (int i = 1; i < n; i++)
        if (arr[i] > x)
            return (i - 1);
 
    return -1;
}
 
/* Driver program to check above functions */
int main()
{
    int arr[] = { 1, 2, 4, 6, 10, 12, 14 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 7;
    int index = floorSearch(arr, n - 1, x);
    if (index == -1)
        cout << "Floor of " << x
             << " doesn't exist in array ";
    else
        cout << "Floor of " << x << " is " << arr[index];
    return 0;
}
 
// This code is contributed by shivanisinghss2110


C




// C/C++ program to find floor of a given number
// in a sorted array
#include <stdio.h>
 
/* An inefficient function to get
index of floor of x in arr[0..n-1] */
int floorSearch(int arr[], int n, int x)
{
    // If last element is smaller than x
    if (x >= arr[n - 1])
        return n - 1;
 
    // If first element is greater than x
    if (x < arr[0])
        return -1;
 
    // Linearly search for the first element
    // greater than x
    for (int i = 1; i < n; i++)
        if (arr[i] > x)
            return (i - 1);
 
    return -1;
}
 
/* Driver program to check above functions */
int main()
{
    int arr[] = { 1, 2, 4, 6, 10, 12, 14 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 7;
    int index = floorSearch(arr, n - 1, x);
    if (index == -1)
        printf("Floor of %d doesn't exist in array ", x);
    else
        printf("Floor of %d is %d", x, arr[index]);
    return 0;
}


Java




// Java program to find floor of
// a given number in a sorted array
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
    /* An inefficient function to get index of floor
of x in arr[0..n-1] */
    static int floorSearch(int arr[], int n, int x)
    {
        // If last element is smaller than x
        if (x >= arr[n - 1])
            return n - 1;
 
        // If first element is greater than x
        if (x < arr[0])
            return -1;
 
        // Linearly search for the first element
        // greater than x
        for (int i = 1; i < n; i++)
            if (arr[i] > x)
                return (i - 1);
 
        return -1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 4, 6, 10, 12, 14 };
        int n = arr.length;
        int x = 7;
        int index = floorSearch(arr, n - 1, x);
        if (index == -1)
            System.out.print("Floor of " + x
                             + " doesn't exist in array ");
        else
            System.out.print("Floor of " + x + " is "
                             + arr[index]);
    }
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


Python3




# Python3 program to find floor of a
# given number in a sorted array
 
# Function to get index of floor
# of x in arr[low..high]
 
 
def floorSearch(arr, n, x):
    # If last element is smaller than x
    if (x >= arr[n - 1]):
        return n - 1
 
    # If first element is greater than x
    if (x < arr[0]):
        return -1
 
    # Linearly search for the first element
    # greater than x
    for i in range(1, n):
        if (arr[i] > x):
            return (i - 1)
 
    return -1
 
 
# Driver Code
arr = [1, 2, 4, 6, 10, 12, 14]
n = len(arr)
x = 7
index = floorSearch(arr, n-1, x)
 
if (index == -1):
    print("Floor of", x, "doesn't exist \
                    in array ", end="")
else:
    print("Floor of", x, "is", arr[index])
 
# This code is contributed by Smitha Dinesh Semwal.


C#




// C# program to find floor of a given number
// in a sorted array
using System;
 
class GFG {
 
    /* An inefficient function to get index of floor
of x in arr[0..n-1] */
    static int floorSearch(int[] arr, int n, int x)
    {
        // If last element is smaller than x
        if (x >= arr[n - 1])
            return n - 1;
 
        // If first element is greater than x
        if (x < arr[0])
            return -1;
 
        // Linearly search for the first element
        // greater than x
        for (int i = 1; i < n; i++)
            if (arr[i] > x)
                return (i - 1);
 
        return -1;
    }
 
    // Driver Code
    static void Main()
    {
        int[] arr = { 1, 2, 4, 6, 10, 12, 14 };
        int n = arr.Length;
        int x = 7;
        int index = floorSearch(arr, n - 1, x);
        if (index == -1)
            Console.WriteLine("Floor of " + x
                              + " doesn't exist in array ");
        else
            Console.WriteLine("Floor of " + x + " is "
                              + arr[index]);
    }
}
 
// This code is contributed
// by mits


PHP




<?php
// PHP program to find floor of
// a given number in a sorted array
 
/* An inefficient function
   to get index of floor
   of x in arr[0..n-1] */
 
function floorSearch($arr, $n, $x)
{
    // If last element is smaller
    // than x
    if ($x >= $arr[$n - 1])
        return $n - 1;
 
    // If first element is greater
    // than x
    if ($x < $arr[0])
        return -1;
 
    // Linearly search for the
    // first element greater than x
    for ($i = 1; $i < $n; $i++)
    if ($arr[$i] > $x)
        return ($i - 1);
 
    return -1;
}
 
// Driver Code
$arr = array (1, 2, 4, 6, 10, 12, 14);
$n = sizeof($arr);
$x = 7;
$index = floorSearch($arr, $n - 1, $x);
if ($index == -1)
    echo "Floor of ", $x,
         "doesn't exist in array ";
else
    echo "Floor of ", $x,
         " is ", $arr[$index];
     
// This code is contributed by ajit
?>


Javascript




<script>
 
// JavaScript program to find floor of
// a given number in a sorted array
 
    /* An inefficient function to get index of floor
of x in arr[0..n-1] */
    function floorSearch(arr, n, x)
    {
        // If last element is smaller than x
        if (x >= arr[n - 1])
            return n - 1;
   
        // If first element is greater than x
        if (x < arr[0])
            return -1;
   
        // Linearly search for the first element
        // greater than x
        for (let i = 1; i < n; i++)
            if (arr[i] > x)
                return (i - 1);
   
        return -1;
    }
 
// Driver Code
 
        let arr = [ 1, 2, 4, 6, 10, 12, 14 ];
        let n = arr.length;
        let x = 7;
        let index = floorSearch(arr, n - 1, x);
        if (index == -1)
             document.write(
                "Floor of " + x
                + " doesn't exist in array ");
        else
             document.write(
                "Floor of " + x + " is "
                + arr[index]);
                         
</script>


Output

Floor of 7 is 6

Time Complexity: O(N). To traverse an array only one loop is needed.
Auxiliary Space: O(1). No extra space is required

Floor in a Sorted Array using binary search:

To solve the problem follow the below idea:

There is a catch in the problem, the given array is sorted. The idea is to use Binary Search to find the floor of a number x in a sorted array by comparing it to the middle element and dividing the search space into half

Follow the given steps to solve the problem:

  • The algorithm can be implemented recursively or through iteration, but the basic idea remains the same.
  • There are some base cases to handle 
    • If there is no number greater than x then print the last element
    • If the first number is greater than x then print -1
  • create three variables low = 0, mid and high = n-1 and another variable to store the answer
  • Run a loop or recurse until and unless low is less than or equal to high.
  • check if the middle ( (low + high) /2) element is less than x, if yes then update the low, i.e low = mid + 1, and update the answer with the middle element. In this step we are reducing the search space to half.
  • Else update the high , i.e high = mid – 1
  • Print the answer

Below is the implementation of the above approach:

C++




// A C/C++ program to find floor
// of a given number in a sorted array
#include <bits/stdc++.h>
using namespace std;
 
/* Function to get index of floor of x in
   arr[low..high] */
int floorSearch(int arr[], int low, int high, int x)
{
    // If low and high cross each other
    if (low > high)
        return -1;
 
    // If last element is smaller than x
    if (x >= arr[high])
        return high;
 
    // Find the middle point
    int mid = (low + high) / 2;
 
    // If middle point is floor.
    if (arr[mid] == x)
        return mid;
 
    // If x lies between mid-1 and mid
    if (mid > 0 && arr[mid - 1] <= x && x < arr[mid])
        return mid - 1;
 
    // If x is smaller than mid, floor
    // must be in left half.
    if (x < arr[mid])
        return floorSearch(arr, low, mid - 1, x);
 
    // If mid-1 is not floor and x is
    // greater than arr[mid],
    return floorSearch(arr, mid + 1, high, x);
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 4, 6, 10, 12, 14 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 7;
 
    // Function call
    int index = floorSearch(arr, 0, n - 1, x);
    if (index == -1)
        cout << "Floor of " << x
             << " doesn't exist in array ";
    else
        cout << "Floor of " << x << " is " << arr[index];
    return 0;
}
 
// this code is contributed by shivanisinghss2110


C




// A C/C++ program to find floor
// of a given number in a sorted array
#include <stdio.h>
 
/* Function to get index of floor of x in
   arr[low..high] */
int floorSearch(int arr[], int low, int high, int x)
{
    // If low and high cross each other
    if (low > high)
        return -1;
 
    // If last element is smaller than x
    if (x >= arr[high])
        return high;
 
    // Find the middle point
    int mid = (low + high) / 2;
 
    // If middle point is floor.
    if (arr[mid] == x)
        return mid;
 
    // If x lies between mid-1 and mid
    if (mid > 0 && arr[mid - 1] <= x && x < arr[mid])
        return mid - 1;
 
    // If x is smaller than mid, floor
    // must be in left half.
    if (x < arr[mid])
        return floorSearch(arr, low, mid - 1, x);
 
    // If mid-1 is not floor and x is
    // greater than arr[mid],
    return floorSearch(arr, mid + 1, high, x);
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 4, 6, 10, 12, 14 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 7;
 
    // Function call
    int index = floorSearch(arr, 0, n - 1, x);
    if (index == -1)
        printf("Floor of %d doesn't exist in array ", x);
    else
        printf("Floor of %d is %d", x, arr[index]);
    return 0;
}


Java




// Java program to find floor of
// a given number in a sorted array
import java.io.*;
 
class GFG {
 
    /* Function to get index of floor of x in
    arr[low..high] */
    static int floorSearch(int arr[], int low, int high,
                           int x)
    {
        // If low and high cross each other
        if (low > high)
            return -1;
 
        // If last element is smaller than x
        if (x >= arr[high])
            return high;
 
        // Find the middle point
        int mid = (low + high) / 2;
 
        // If middle point is floor.
        if (arr[mid] == x)
            return mid;
 
        // If x lies between mid-1 and mid
        if (mid > 0 && arr[mid - 1] <= x && x < arr[mid])
            return mid - 1;
 
        // If x is smaller than mid, floor
        // must be in left half.
        if (x < arr[mid])
            return floorSearch(arr, low, mid - 1, x);
 
        // If mid-1 is not floor and x is
        // greater than arr[mid],
        return floorSearch(arr, mid + 1, high, x);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 4, 6, 10, 12, 14 };
        int n = arr.length;
        int x = 7;
 
        // Function call
        int index = floorSearch(arr, 0, n - 1, x);
        if (index == -1)
            System.out.println(
                "Floor of " + x
                + " doesn't exist in array ");
        else
            System.out.println("Floor of " + x + " is "
                               + arr[index]);
    }
}
// This code is contributed by Prerna Saini


Python3




# Python3 program to find floor of a
# given number in a sorted array
 
# Function to get index of floor
# of x in arr[low..high]
 
 
def floorSearch(arr, low, high, x):
 
    # If low and high cross each other
    if (low > high):
        return -1
 
    # If last element is smaller than x
    if (x >= arr[high]):
        return high
 
    # Find the middle point
    mid = int((low + high) / 2)
 
    # If middle point is floor.
    if (arr[mid] == x):
        return mid
 
    # If x lies between mid-1 and mid
    if (mid > 0 and arr[mid-1] <= x
            and x < arr[mid]):
        return mid - 1
 
    # If x is smaller than mid,
    # floor must be in left half.
    if (x < arr[mid]):
        return floorSearch(arr, low, mid-1, x)
 
    # If mid-1 is not floor and x is greater than
    # arr[mid],
    return floorSearch(arr, mid + 1, high, x)
 
 
# Driver Code
if __name__ == "__main__":
    arr = [1, 2, 4, 6, 10, 12, 14]
    n = len(arr)
    x = 7
 
    # Function call
    index = floorSearch(arr, 0, n-1, x)
 
    if (index == -1):
        print("Floor of", x, "doesn't exist\
                      in array ", end="")
    else:
        print("Floor of", x, "is", arr[index])
 
# This code is contributed by Smitha Dinesh Semwal.


C#




// C# program to find floor of
// a given number in a sorted array
using System;
 
class GFG {
 
    /* Function to get index of floor of x in
    arr[low..high] */
    static int floorSearch(int[] arr, int low, int high,
                           int x)
    {
 
        // If low and high cross each other
        if (low > high)
            return -1;
 
        // If last element is smaller than x
        if (x >= arr[high])
            return high;
 
        // Find the middle point
        int mid = (low + high) / 2;
 
        // If middle point is floor.
        if (arr[mid] == x)
            return mid;
 
        // If x lies between mid-1 and mid
        if (mid > 0 && arr[mid - 1] <= x && x < arr[mid])
            return mid - 1;
 
        // If x is smaller than mid, floor
        // must be in left half.
        if (x < arr[mid])
            return floorSearch(arr, low, mid - 1, x);
 
        // If mid-1 is not floor and x is
        // greater than arr[mid],
        return floorSearch(arr, mid + 1, high, x);
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 1, 2, 4, 6, 10, 12, 14 };
        int n = arr.Length;
        int x = 7;
 
        // Function call
        int index = floorSearch(arr, 0, n - 1, x);
        if (index == -1)
            Console.Write("Floor of " + x
                          + " doesn't exist in array ");
        else
            Console.Write("Floor of " + x + " is "
                          + arr[index]);
    }
}
 
// This code is contributed by nitin mittal.


Javascript




<script>
 
// javascript program to find floor of
// a given number in a sorted array
 
/* Function to get index of floor of x in
arr[low..high] */
function floorSearch(
    arr , low,
    high , x)
{
    // If low and high cross each other
    if (low > high)
        return -1;
 
    // If last element is smaller than x
    if (x >= arr[high])
        return high;
 
    // Find the middle point
    var mid = (low + high) / 2;
 
    // If middle point is floor.
    if (arr[mid] == x)
        return mid;
 
    // If x lies between mid-1 and mid
    if (
        mid > 0 && arr[mid - 1] <= x && x < arr[mid])
        return mid - 1;
 
    // If x is smaller than mid, floor
    // must be in left half.
    if (x < arr[mid])
        return floorSearch(
            arr, low,
            mid - 1, x);
 
    // If mid-1 is not floor and x is
    // greater than arr[mid],
    return floorSearch(
        arr, mid + 1, high,
        x);
}
 
/* Driver program to check above functions */
var arr = [ 1, 2, 4, 6, 10, 12, 14 ];
var n = arr.length;
var x = 7;
var index = floorSearch(
    arr, 0, n - 1,
    x);
if (index == -1)
    document.write(
        "Floor of " + x + " doesn't exist in array ");
else
    document.write(
        "Floor of " + x + " is " + arr[index]);
 
// This code is contributed by Amit Katiyar
</script>


Output

Floor of 7 is 6

Time Complexity: O(log N). To run a binary search.
Auxiliary Space: O(1). As no extra space is required.

 



Previous Article
Next Article

Similar Reads

Absolute difference between floor of Array sum divided by X and floor sum of every Array element when divided by X
Given an array A[] and a positive integer X. The task is to find the absolute difference between the floor of the total sum divided by X and the sum of the floor of each element of A[] divided by X. Examples: Input: A[] = {1, 2, 3, 4, 5, 6}, X = 4Output: 2Explanation : Sum of A[] = 1 + 2 + 3 + 4 + 5 + 6 = 21Sum of A[] divided by X = 21 / 4 = 5Sum o
6 min read
Value of continuous floor function : F(x) = F(floor(x/2)) + x
Given an array of positive integers. For every element x of array, we need to find the value of continuous floor function defined as F(x) = F(floor(x/2)) + x, where F(0) = 0. Examples : Input : arr[] = {6, 8} Output : 10 15 Explanation : F(6) = 6 + F(3) = 6 + 3 + F(1) = 6 + 3 + 1 + F(0) = 10 Similarly F(8) = 15 Basic Approach: For a given value of
5 min read
Finding Floor and Ceil of a Sorted Array using C++ STL
Given a sorted array, the task is to find the floor and ceil of given numbers using STL.Examples: Input: arr[] = {1, 2, 4, 7, 11, 12, 23, 30, 32}, values[] = { 1, 3, 5, 7, 20, 24 } Output: Floor Values: 1 2 4 7 12 23 Ceil values: 1 4 7 7 23 30 In case of floor(): lower_bound() method os STL will be used to find the lower bound. This returns an iter
3 min read
Count number of common elements between a sorted array and a reverse sorted array
Given two arrays consisting of N distinct integers such that the array A[] and B[] are sorted in ascending and descending order respectively, the task is to find the number of values common in both arrays. Examples: Input: A[] = {1, 10, 100}, B[] = {200, 20, 2}Output: 0 Input: A[] = {2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999}, B[] = {109, 99, 68
15+ min read
Circularly Sorted Array (Sorted and Rotated Array)
Circularly sorted arrays are arrays that are sorted in ascending or descending order and then rotated by a number of steps. Let us take an example to know more about circularly sorted arrays: Consider an array: arr[] = {23, 34, 45, 12, 17, 19}The elements here, {12, 17, 19, 23, 34, 45} are sorted 'In-order' but they are rotated to the left by 3 tim
7 min read
Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array
Given two sorted arrays A[] and B[] of size N, the task is to check if it is possible to merge two given sorted arrays into a new sorted array such that no two consecutive elements are from the same array. Examples: Input: A[] = {3, 5, 8}, B[] = {2, 4, 6}Output: Yes Explanation: Merged array = {B[0], A[0], B[1], A[1], B[2], A[2]} Since the resultan
15+ min read
Sum of floor division of all pairs from given array
Given an array arr[] of size N, the task is to find the sum of the floor value of (arr[i] / arr[j]) for all pairs of indices (i, j). Examples: Input: arr[] = { 1, 2, 3 } Output: 9 Explanation: Sum = (arr[i] / arr[j]) (a[0] / a[0]) + (a[0] / a[1]) + (a[0] / a[2]) + (a[1] / a[1]) + (a[1] / a[2]) + (a[2] / a[2]) + (a[1] / a[0]) + (a[2] / a[0]) + (a[2]
9 min read
Decimal equivalent of concatenation of absolute difference of floor and rounded-off values of array elements as a Binary String
Given an array arr[] consisting of N floating-point numbers, the task is to print the decimal representation of the binary array constructed from the absolute difference between the floor and round-off value for each array element. Examples: Input: arr[] = {1.2, 2.6, 4.2, 6.9, 3.1, 21.6, 91.2}Output: 42Explanation:Below is the image to illustrate t
6 min read
Check if an element is present in an array using at most floor(N / 2) + 2 comparisons
Given an array A[] of size N and an integer X, the task is to check if X exists in A[] with no more than floor(N/2) + 2 comparisons. Note: For any index i, (i &lt; N) or (A[i] == X) are considered as separate comparisons. Examples: Input: A[] = {-3, 5, 11, 3, 100, 2, 88, 22, 7, 900, 23, 4, 1}, X = 88Output: Yes 8Explanation: X = 88 exists in the gi
7 min read
Make the Array sum 0 by using either ceil or floor on each element
Given an array arr[] consisting of N floating point integers, the task is to modify the array by performing ceil() or floor() on every array element such that the sum of array elements is close to 0. Examples: Input: arr[] = {6.455, -1.24, -3.87, 2.434, -4.647}Output: {6, -2, -3, 3, -4}Explanation:Perform the floor operation on array elements at in
7 min read
three90RightbarBannerImg