Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x = 5
Output: 1
Explanation: Largest number less than or equal to 5 is 2, whose index is 1
Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x = 20
Output: 6
Explanation: Largest number less than or equal to 20 is 19, whose index is 6
Input : arr[] = [1, 2, 8, 10, 10, 12, 19], x = 0
Output : -1
Explanation: Since floor doesn't exist, output is -1.
Traverse the array from start to end. If the first element is greater than x, print "Floor of x doesn't exist." Otherwise, when encountering an element greater than x, print the previous element and exit. If no such element is found, print the last element as the floor of x.
Find the midpoint. If arr[mid]
equals x
, return mid
. If arr[mid]
is greater than x
, search the left half. Otherwise, store arr[mid]
as a potential floor and continue searching the right half for a larger but valid floor value.