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:
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: