Floor in a Sorted Array

16 Feb, 2022
Given a sorted array and a value x, the floor of x is the largest element in array smaller than or equal to x. Write efficient functions to find floor of x.Examples:  
Input : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 5
Output : 2
2 is the largest element in 
arr[] smaller than 5.

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

Input : arr[] = {1, 2, 8, 10, 10, 12, 19}, x = 0
Output : -1
Since floor doesn't exist,
output is -1.
 
Simple MethodApproach: 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.Algorithm:  
Traverse through the array from start to end.If the current element is greater than x print the previous number and break the loop.If there is no number greater than x then print the last elementIf the first number is greater than x then print -1
Traverse through the array from start to end.
If the current element is greater than x print the previous number and break 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 -1
 
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find floor of a given number// in a sorted array#include <iostream>using namespace std; /* An inefficient function to getindex 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++ program to find floor of a given number// in a sorted array#include <stdio.h> /* An inefficient function to getindex 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 program to find floor of// a given number in a sorted arrayimport java.io.*;import java.util.*;import java.lang.*; class GFG {     /* An inefficient function to get index of floorof 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 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 Codearr = [1, 2, 4, 6, 10, 12, 14]n = len(arr)x = 7index = 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# program to find floor of a given number// in a sorted arrayusing System; class GFG {     /* An inefficient function to get index of floorof 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 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?>
<script> // JavaScript program to find floor of// a given number in a sorted array     /* An inefficient function to get index of floorof 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.
Complexity Analysis:  
Time Complexity : O(n). To traverse an array only one loop is needed so the time complexity is O(n).
Space Complexity: O(1). No extra space is required, So the space complexity is constant
  Efficient MethodApproach: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. Algorithm:  
The algorithm can be implemented recursively or through iteration, but the basic idea remains the same.There is some base cases to handle. If there is no number greater than x then print the last elementIf the first number is greater than x then print -1create three variables low = 0, mid and high = n-1 and another variable to store the answerRun 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.elow = mid + 1, and update answer with the middle element. In this step we are reducing the search space to half.Else update the high , i.e high = mid – 1Print the answer.
The algorithm can be implemented recursively or through iteration, but the basic idea remains the same.
There is some base cases to handle. If there is no number greater than x then print the last elementIf the first number is greater than x then print -1
If there is no number greater than x then print the last elementIf the first number is greater than x then print -1
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.elow = mid + 1, and update 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.
 
C++
C
Java
Python3
C#
Javascript
// A C/C++ program to find floor// of a given number in a sorted array#include <iostream>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 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, 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
// 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 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, 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 program to find floor of// a given number in a sorted arrayimport 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 program to check above functions */    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, 0, n - 1,            x);        if (index == -1)            System.out.println(                "Floor of " + x + " dosen't exist in array ");        else            System.out.println(                "Floor of " + x + " is " + arr[index]);    }}// This code is contributed by Prerna Saini
# 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 Codearr = [1, 2, 4, 6, 10, 12, 14]n = len(arr)x = 7index = 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# program to find floor of// a given number in a sorted arrayusing 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 program to check above functions */    public static void Main()    {        int[] arr = { 1, 2, 4, 6, 10, 12, 14 };        int n = arr.Length;        int x = 7;        int index = floorSearch(arr, 0, n - 1,                                x);        if (index == -1)            Console.Write("Floor of " + x + " dosen't exist in array ");        else            Console.Write("Floor of " + x + " is " + arr[index]);    }} // This code is contributed by nitin mittal.
<script> // javascript program to find floor of// a given number in a sorted array /* Function to get index of floor of x inarr[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 + " dosen'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.
Complexity Analysis:  
Time Complexity : O(log n). To run a binary search, the time complexity required is O(log n).
Space Complexity: O(1). As no extra space is required, so the space complexity is constant.
This article is contributed by Mayank Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
jit_t
Akanksha_Rai
Mithun Kumar
andrew1234
code_hunt
amit143katiyar
simranarora5sos
shivanisinghss2110
adityakumar129
Amazon
Binary Search
Divide and Conquer
Searching
Amazon
Searching
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge Sort
QuickSort
Binary Search
Count Inversions in an array | Set 1 (Using Merge Sort)
Median of two sorted arrays of different sizes
Binary Search
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
Find the Missing Number