siri
siri

Reputation: 13

Given an array of sorted integers and find the closest value to the given number in c. Array may contain duplicate values

For example we have 5 values(a,b,c,e,d) in an array which may contain duplicate values.The values of a,b,c,d,e are calculated by another function and got assigned with some values. let the user input value be x. we need to find the closest value to x in the array and the output must be in a,b,c,e,d. if the closest number is one of the duplicates the alphabetical order must be considered.

for example:

Array: a,b,c,e,d

a=6,b=5,c=3,d=9,e=9 are the values assigned to them by a function.

for x : 5,
output : b

for x :11,
output : d

for x : 4,
output :c

Upvotes: 0

Views: 317

Answers (1)

chqrlie
chqrlie

Reputation: 144780

Try and implement the following algorithm:

  • get the element at the middle of the array ;
  • if this element has the value x, the array contains it, you know what to print ;
  • if the element is larger, look in the first half of the array ;
  • otherwise look in the second half of the array ;

Once the array portion you search into has a size of 0, you have found the place where x would be inserted to preserve the ordering. The closest value is either the one of the left or the one on the right, if any. Compute the differences to determine what to print.

Upvotes: 1

Related Questions