Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Finding Floor and Ceil of a Sorted Array using C++ STL
Next article icon

Find floor and ceil in an unsorted array

Last Updated : 08 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an unsorted array arr[] and an element x, find floor and ceiling of x in arr[0..n-1].
Floor of x is the largest element which is smaller than or equal to x. Floor of x doesn’t exist if x is smaller than smallest element of arr[].
Ceil of x is the smallest element which is greater than or equal to x. Ceil of x doesn’t exist if x is greater than greatest element of arr[].

Examples: 

Input : arr[] = {5, 6, 8, 9, 6, 5, 5, 6}                x = 7  Output : Floor = 6           Ceiling = 8    Input : arr[] = {5, 6, 8, 9, 6, 5, 5, 6}                x = 6  Output : Floor = 6           Ceiling = 6    Input : arr[] = {5, 6, 8, 9, 6, 5, 5, 6}                x = 10  Output : Floor = 9           Ceiling doesn't exist.
Recommended Practice
Ceil The Floor
Try It!

Method 1 (Use Sorting):

  1. Sort input array. 
  2. Use binary search to find floor and ceiling of x. Refer this and this for implementation of floor and ceiling in a sorted array.

C++




#include <bits/stdc++.h>
using namespace std;
  
// Solution
vector<int> floorAndCeil(vector<int> arr, int n, int x)
{
    vector<int> result(2);
  
    int low = 0, high = n - 1;
  
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] > x) {
            high = mid - 1;
        }
        else if (arr[mid] < x) {
            low = mid + 1;
        }
        else {
            result[0] = arr[mid];
            result[1] = arr[mid];
            return result;
        }
    }
  
    // if loop breaks
    result[0] = (high == -1) ? -1 : arr[high];
    result[1] = (low == arr.size()) ? -1 : arr[low];
  
    return result;
}
  
// Driver
int main()
{
    vector<int> arr = { 5, 6, 8, 9, 6, 5, 5, 6 };
    int n = arr.size();
    int x = 7;
  
    vector<int> result = floorAndCeil(arr, n, x);
    cout << "floor is " << result[0] << endl;
    cout << "ceil is " << result[1] << endl;
    return 0;
} // this code is contributed by devendradany
 
 

Java




import java.util.*;
  
public class Main {
  
    // Solution
    public static int[] floorAndCeil(int[] arr, int n,
                                     int x)
    {
  
        int[] result = new int[2];
  
        int low = 0, high = n - 1;
  
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] > x) {
                high = mid - 1;
            }
            else if (arr[mid] < x) {
                low = mid + 1;
            }
            else {
                Arrays.fill(result, arr[mid]);
                return result;
            }
        }
  
        // if loop breaks
        result[0] = (high == -1) ? -1 : arr[high];
        result[1] = (low == arr.length) ? -1 : arr[low];
  
        return result;
    }
  
    // Driver
    public static void main(String[] args)
    {
  
        int[] arr = { 5, 6, 8, 9, 6, 5, 5, 6 };
        int n = arr.length;
        int x = 7;
  
        int[] result = floorAndCeil(arr, n, x);
        System.out.println("floor is " + result[0]);
        System.out.println("ceil is " + result[1]);
    }
}
 
 

Python3




#Equivalent Python code for the given Java code
  
#The binary search algorithm used in the code can be implemented similarly in Python
  
def floor_and_ceil(arr, n, x):
    result = [0, 0]
  
    low = 0
    high = n - 1
  
    while low <= high:
        mid = low + (high - low) // 2
        if arr[mid] > x:
            high = mid - 1
        elif arr[mid] < x:
            low = mid + 1
        else:
            result = [arr[mid], arr[mid]]
            return result
  
    # if loop breaks
    result[0] = -1 if high == -1 else arr[high]
    result[1] = -1 if low == n else arr[low]
  
    return result
  
if __name__ == '__main__':
    arr = [5, 6, 8, 9, 6, 5, 5, 6]
    n = len(arr)
    x = 7
      
    result = floor_and_ceil(arr, n, x)
    print("floor is", result[0])
    print("ceil is", result[1])
 
 

C#




using System;
  
public class GFG {
  
  // Solution
  public static int[] floorAndCeil(int[] arr, int n,
                                   int x)
  {
  
    int[] result = new int[2];
  
    int low = 0, high = n - 1;
  
    while (low <= high) {
      int mid = low + (high - low) / 2;
      if (arr[mid] > x) {
        high = mid - 1;
      }
      else if (arr[mid] < x) {
        low = mid + 1;
      }
      else {
        result[0] = arr[mid];
        result[1] = arr[mid];
        return result;
      }
    }
  
    // if loop breaks
    result[0] = (high == -1) ? -1 : arr[high];
    result[1] = (low == arr.Length) ? -1 : arr[low];
  
    return result;
  }
  
  static public void Main()
  {
  
    int[] arr = { 5, 6, 8, 9, 6, 5, 5, 6 };
    int n = arr.Length;
    int x = 7;
  
    int[] result = floorAndCeil(arr, n, x);
    Console.WriteLine("floor is " + result[0]);
    Console.WriteLine("ceil is " + result[1]);
  }
}
  
// This code is contributed by akashish__
 
 

Javascript




// JavaScript code equivalent to given Python code
  
function floorAndCeil(arr, n, x) {
let result = [0, 0];
let low = 0;
let high = n - 1;
  
while (low <= high) {
    let mid = low + Math.floor((high - low) / 2);
    if (arr[mid] > x) {
        high = mid - 1;
    } else if (arr[mid] < x) {
        low = mid + 1;
    } else {
        result = [arr[mid], arr[mid]];
        return result;
    }
}
  
// if loop breaks
result[0] = (high == -1) ? -1 : arr[high];
result[1] = (low == n) ? -1 : arr[low];
  
return result;
}
  
let arr = [5, 6, 8, 9, 6, 5, 5, 6];
let n = arr.length;
let x = 7;
  
let result = floorAndCeil(arr, n, x);
console.log('floor is '+result[0]);
console.log('ceil is '+result[1]);
 
 
Output
floor is 6  ceil is 8

Time Complexity : O(n log n) 
Auxiliary Space : O(1)

This solution is works well if there are multiple queries of floor and ceiling on a static array. We can sort the array once and answer the queries in O(Log n) time.

Method 2 (Use Linear Search:

The idea is to traverse array and keep track of two distances with respect to x. 

  1. Minimum distance of element greater than or equal to x. 
  2. Minimum distance of element smaller than or equal to x.

Finally print elements with minimum distances. 

C++




// C++ program to find floor and ceiling in an 
// unsorted array. 
#include<bits/stdc++.h> 
using namespace std; 
  
// Function to floor and ceiling of x in arr[] 
void floorAndCeil(int arr[], int n, int x) 
{ 
    // Indexes of floor and ceiling 
    int fInd, cInd; 
  
    // Distances of current floor and ceiling 
    int fDist = INT_MAX, cDist = INT_MAX; 
  
    for (int i=0; i<n; i++) 
    { 
        // If current element is closer than 
        // previous ceiling. 
        if (arr[i] >= x && cDist > (arr[i] - x)) 
        { 
        cInd = i; 
        cDist = arr[i] - x; 
        } 
  
        // If current element is closer than 
        // previous floor. 
        if (arr[i] <= x && fDist > (x - arr[i])) 
        { 
        fInd = i; 
        fDist = x - arr[i]; 
        } 
    } 
  
    if (fDist == INT_MAX) 
    cout << "Floor doesn't exist " << endl; 
    else
    cout << "Floor is " << arr[fInd] << endl; 
  
    if (cDist == INT_MAX) 
    cout << "Ceil doesn't exist " << endl; 
    else
    cout << "Ceil is " << arr[cInd] << endl; 
} 
  
// Driver code 
int main() 
{ 
    int arr[] = {5, 6, 8, 9, 6, 5, 5, 6}; 
    int n = sizeof(arr)/sizeof(int); 
    int x = 7; 
    floorAndCeil(arr, n, x); 
    return 0; 
} 
 
 

Java




// Java program to find floor and ceiling in an
// unsorted array.
import java.io.*;
  
class GFG 
{
     // Function to floor and ceiling of x in arr[]
    public static void floorAndCeil(int arr[], int x)
    {
        int n = arr.length;
          
        // Indexes of floor and ceiling
        int fInd = -1, cInd = -1;
   
        // Distances of current floor and ceiling
        int fDist = Integer.MAX_VALUE, cDist = Integer.MAX_VALUE;
   
        for (int i = 0; i < n; i++)
        {
            // If current element is closer than
            // previous ceiling.
            if (arr[i] >= x && cDist > (arr[i] - x))
            {
                cInd = i;
                cDist = arr[i] - x;
            }
   
            // If current element is closer than
            // previous floor.
            if (arr[i] <= x && fDist > (x - arr[i]))
            {
                fInd = i;
                fDist = x - arr[i];
            }
        }
   
        if(fDist == Integer.MAX_VALUE)
            System.out.println("Floor doesn't exist " );
        else
            System.out.println("Floor is " +  arr[fInd]);
   
        if(cDist == Integer.MAX_VALUE)
            System.out.println("Ceil doesn't exist ");
        else
            System.out.println("Ceil is  " + arr[cInd]);
    }
      
    public static void main (String[] args) 
    {
        int arr[] = {5, 6, 8, 9, 6, 5, 5, 6};
        int x = 7;
        floorAndCeil(arr, x);
    }
}
 
 

Python 3




# Python 3 program to find 
# floor and ceiling in an
# unsorted array.
  
import sys
  
# Function to floor and
# ceiling of x in arr[]
def floorAndCeil(arr, n, x):
  
    # Distances of current
    # floor and ceiling
    fDist = sys.maxsize
    cDist = sys.maxsize
  
    for i in range(n):
      
        # If current element is closer 
        # than previous ceiling.
        if (arr[i] >= x and 
            cDist > (arr[i] - x)):
          
            cInd = i
            cDist = arr[i] - x
  
        # If current element is closer 
        # than previous floor.
        if (arr[i] <= x and fDist > (x - arr[i])):
          
            fInd = i
            fDist = x - arr[i]
  
    if (fDist == sys.maxsize):
        print("Floor doesn't exist ")
    else:
        print("Floor is " + str(arr[fInd])) 
  
    if (cDist == sys.maxsize):
        print( "Ceil doesn't exist ")
    else:
        print("Ceil is " + str(arr[cInd]))
  
# Driver code
if __name__ == "__main__":
    arr = [5, 6, 8, 9, 6, 5, 5, 6]
    n = len(arr)
    x = 7
    floorAndCeil(arr, n, x)
  
# This code is contributed 
# by ChitraNayal
 
 

C#




// C# program to find floor and ceiling in an
// unsorted array.
using System;
  
class GFG {
      
    // Function to floor and ceiling of x in arr[]
    public static void floorAndCeil(int []arr, int x)
    {
        int n = arr.Length;
          
        // Indexes of floor and ceiling
        int fInd = -1, cInd = -1;
  
        // Distances of current floor and ceiling
        int fDist = int.MaxValue,
            cDist =int.MaxValue;
              
        for (int i = 0; i < n; i++)
        {
              
            // If current element is closer than
            // previous ceiling.
            if (arr[i] >= x && cDist > (arr[i] - x))
            {
                cInd = i;
                cDist = arr[i] - x;
            }
  
            // If current element is closer than
            // previous floor.
            if (arr[i] <= x && fDist > (x - arr[i]))
            {
                fInd = i;
                fDist = x - arr[i];
            }
        }
  
        if(fDist == int.MaxValue)
            Console.Write("Floor doesn't exist " );
        else
            Console.WriteLine("Floor is " + arr[fInd]);
  
        if(cDist == int.MaxValue)
        Console.Write("Ceil doesn't exist ");
        else
            Console.Write("Ceil is " + arr[cInd]);
    }
      
    // Driver code
    public static void Main () 
    {
        int []arr = {5, 6, 8, 9, 6, 5, 5, 6};
        int x = 7;
          
        floorAndCeil(arr, x);
    }
}
  
// This code is contributed by nitin mittal.
 
 

PHP




<?php
// PHP program to find 
// floor and ceiling in 
// an unsorted array.
  
// Function to floor and 
// ceiling of x in arr[]
function floorAndCeil($arr,
                      $n, $x)
{
    // Indexes of floor
    // and ceiling
    $fInd = 0;
    $cInd = 0;
  
    // Distances of current
    // floor and ceiling
    $fDist = 999999;
    $cDist = 999999;
  
    for ($i = 0; $i < $n; $i++)
    {
        // If current element 
        // is closer than
        // previous ceiling.
        if ($arr[$i] >= $x && 
            $cDist > ($arr[$i] - $x))
        {
            $cInd = $i;
            $cDist = $arr[$i] - $x;
        }
  
        // If current element 
        // is closer than
        // previous floor.
        if ($arr[$i] <= $x && 
            $fDist > ($x - $arr[$i]))
        {
            $fInd = $i;
            $fDist = $x - $arr[$i];
        }
    }
  
    if ($fDist == 999999)
        echo "Floor doesn't ". 
             "exist " . "\n" ;
    else
        echo "Floor is " . 
              $arr[$fInd] . "\n";
  
    if ($cDist == 999999)
        echo "Ceil doesn't " .
             "exist " . "\n";
    else
        echo "Ceil is " . 
             $arr[$cInd] . "\n";
}
  
// Driver code
$arr = array(5, 6, 8, 9,
             6, 5, 5, 6);
$n = count($arr);
$x = 7;
floorAndCeil($arr, $n, $x);
  
// This code is contributed
// by Sam007
?>
 
 

Javascript




<script>
// Javascript program to find floor and ceiling in an
// unsorted array.
      
    // Function to floor and ceiling of x in arr[]
    function floorAndCeil(arr,x)
    {
        let n = arr.length;
            
        // Indexes of floor and ceiling
        let fInd = -1, cInd = -1;
     
        // Distances of current floor and ceiling
        let fDist = Number.MAX_VALUE, cDist = Number.MAX_VALUE;
     
        for (let i = 0; i < n; i++)
        {
            // If current element is closer than
            // previous ceiling.
            if (arr[i] >= x && cDist > (arr[i] - x))
            {
                cInd = i;
                cDist = arr[i] - x;
            }
     
            // If current element is closer than
            // previous floor.
            if (arr[i] <= x && fDist > (x - arr[i]))
            {
                fInd = i;
                fDist = x - arr[i];
            }
        }
     
        if(fDist == Number.MAX_VALUE)
            document.write("Floor doesn't exist <br>" );
        else
            document.write("Floor is " +  arr[fInd]+"<br>");
     
        if(cDist == Number.MAX_VALUE)
            document.write("Ceil doesn't exist <br>");
        else
            document.write("Ceil is  " + arr[cInd]+"<br>");
    }
      
    let arr=[5, 6, 8, 9, 6, 5, 5, 6];
    let x = 7;
    floorAndCeil(arr, x);
      
    // This code is contributed by rag2127
</script>
 
 
Output
Floor is 6  Ceil is 8

Time Complexity : O(n) 
Auxiliary Space : O(1)

Related Articles : 
Ceiling in a sorted array 
Floor in a sorted array



Next Article
Finding Floor and Ceil of a Sorted Array using C++ STL

D

DANISH_RAZA
Improve
Article Tags :
  • Arrays
  • DSA
  • Matrix
Practice Tags :
  • Arrays
  • Matrix

Similar Reads

  • 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
    3 min read
  • Ceiling in a sorted array
    Given a sorted array and a value x, find index of the ceiling of x. The ceiling of x is the smallest element in an array greater than or equal to x. Note: In case of multiple occurrences of ceiling of x, return the index of the first occurrence. Examples : Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x
    13 min read
  • Floor in a Sorted Array
    Given a sorted array and a value x, find the element of the floor of x. The floor of x is the largest element in the array smaller than or equal to x. Examples: Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x = 5Output: 1Explanation: Largest number less than or equal to 5 is 2, whose index is 1 Input: a
    9 min read
  • k-th missing element in an unsorted array
    Given an unsorted sequence a[], the task is to find the K-th missing contiguous element in the increasing sequence of the array elements i.e. consider the array in sorted order and find the kth missing number. If no k-th missing element is there output -1. Note: Only elements exists in the range of
    6 min read
  • Find first and last positions of an element in a sorted array
    Given a sorted array arr[] with possibly some duplicates, the task is to find the first and last occurrences of an element x in the given array. Note: If the number x is not found in the array then return both the indices as -1. Examples: Input : arr[] = [1, 3, 5, 5, 5, 5, 67, 123, 125], x = 5Output
    15+ min read
  • Front and Back Search in unsorted array
    Given an unsorted array of integers and an element x, find if x is present in array using Front and Back search. Examples : Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170} x = 110; Output : Yes Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170} x = 175; Output : No A simple so
    5 min read
  • Find start and ending index of an element in an unsorted array
    Given an array of integers, task is to find the starting and ending position of a given key. Examples: Input : arr[] = {1, 2, 3, 4, 5, 5} Key = 5Output : Start index: 4 Last index: 5Explanation: Starting index where 5is present is 4 and ending index is 5. Input :arr[] = {1, 3, 7, 8, 6}, Key = 2Outpu
    11 min read
  • Single Element in a Sorted Array
    Given a sorted array in which all elements appear twice and one element appears only once, the task is to find the element that appears once. Examples: Input: arr[] = {1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8}Output: 4Explanation: All numbers except 4 occur twice in the array. Input: arr[] = {1, 1, 3, 3, 4,
    11 min read
  • Search for an element in a Mountain Array
    Given a mountain array arr[] and an integer X, the task is to find the smallest index of X in the given array. If no such index is found, print -1. Examples: Input: arr = {1, 2, 3, 4, 5, 3, 1}, X = 3Output: 2Explanation: The smallest index of X(= 3) in the array is 2. Therefore, the required output
    14 min read
  • Find the Kth occurrence of an element in a sorted Array
    Given a sorted array arr[] of size N, an integer X, and a positive integer K, the task is to find the index of Kth occurrence of X in the given array. Examples: Input: N = 10, arr[] = [1, 2, 3, 3, 4, 5, 5, 5, 5, 5], X = 5, K = 2Output: Starting index of the array is '0' Second occurrence of 5 is at
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences