Floor and Ceil Value
Given a sorted array of integers, find the floor and ceil of given number x in it. The floor and ceil value of a number points to the largest previous or the smallest following integer respectively.
Problem description:
The problem wants you to use the knowledge of mathematics as the floor is the value which is the largest integer less than or equal to x and ceil value is the smallest greater than or equal to x. We are required to approach the problem in a way such that the time complexity should change to linear to logarithmic.
Input:
The first line of the input is the T number of test cases. Each test case consists of integer n and x, size of the array, and the element whose floor and ceil value is to be evaluated respectively. Then each of the following lines contains n elements.
Output:
Print the floor and ceil value of the element x.
Examples:
Input:
T=1
N=5,X=3
1,2,4,5,6
Output:
floor: 2
ceil: 4
(a) Brute Force Approach:
In this approach we will iterate through the array and simply find the floor and ceil of the element x in O(n) time.
The floor will the largest element smaller than or equal to element x and the ceil will be the smallest element greater than or equal to element x.
Pseudo Code:
Time Complexity for the above approach in the worst case is: O(n)
Space Complexity for the above approach in the worst case is: O(1)
b) Binary Search Approach:
In this approach, we will use the concept of binary search to solve the problem. We will find the mid and then recur for the left or right side of the mid index according to the comparison.
Pseudo Code:
FOR CEIL: start and end are the range end points. //initialise ceil with -1. ceil=-1 CEIL(arr[],start,end): -> if x is equal to mid element then return mid element. -> if x is less than the mid element then ceil of the element x lies in left half of the range i.e in arr[start,mid], so we will change our celi value to mid element and search in left half arr[start,mid-1]. -> if x is greater than the mid element then ceil of the element x lies in the right half of the range i.e in arr[mid+1,end]. FOR FLOOR: start and end are the range end points. //initialise floor with -1. floor=-1 FLOOR(arr[],start,end): -> if x is equal to mid element then return mid element -> if x is less than mid element then floor lies in the left half of the range i.e arr[start,mid] -> if x is greater than the mid element then floor lies in the right half of the range i.e arr[mid,end],assign floor equal to mid. The floor lies in arr[mid+1,end] half.Time Complexity for the above approach in the worst case is: O(log(n))
Space Complexity for the above approach in the worst case is: O(1)
C++ Implementation (Brute Force Approach):
Output:
C++ Implementation (Binary Search Approach):
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer