Question: Assignment: Write a public static method named findClosest ( int [ ] array, int target ) that uses the binary search technique to find the

Assignment: Write a public static method named findClosest(int[] array, int target) that uses the binary search technique to find the element in an int array that is closest to the target value.
Requirements:
Assume the input array is sorted in ascending order;
Assume the input array cannot be empty or null;
Assume the input array does not contain duplicate values;
If two numbers
are
are equally distant to a third number
, pick the smaller between
and
;
The method should return the int value that is the closest to the target value.
Hints:
To evaluate the distance between two numbers
and
, use the absolute value of their difference
. This is implemented in Java by the Math.abs method;
Use the binary search to split the search range into halves, but instead of looking for an exact match, track the closest number encountered so far.
Consider edge cases, such as the target being smaller than the smallest element or larger than the largest element of the array.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!