human
Find closest number in array | Returns element closest to target in arr [ ].
Corner cases.
Doing binary search.
If target is less than array element , then search in left.
If target is greater than previous to mid , return closest of two.
Repeat for left half.
If target is greater than mid.
update i.
Only single element left after search.
Method to compare which one is the more close . We find the closest by taking the difference between the target and both values . It assumes that val2 is greater than val1 and target lies between these two ..
Driver code"
How can the above be solved in Python?
assistant
#Here is code to find closest number in array and the other steps required.
 def findClosest ( arr , n , target ) :
	if ( target <= arr [ 0 ] ) :
		return arr [ 0 ]
	if ( target >= arr [ n - 1 ] ) :
		return arr [ n - 1 ]
	i = 0 ; j = n ; mid = 0
	while ( i < j ) :
		mid = ( i + j ) // 2
		if ( arr [ mid ] == target ) :
			return arr [ mid ]
		if ( target < arr [ mid ] ) :
			if ( mid > 0 and target > arr [ mid - 1 ] ) :
				return getClosest ( arr [ mid - 1 ] , arr [ mid ] , target )
			j = mid
		else :
			if ( mid < n - 1 and target < arr [ mid + 1 ] ) :
				return getClosest ( arr [ mid ] , arr [ mid + 1 ] , target )
			i = mid + 1
	return arr [ mid ]
def getClosest ( val1 , val2 , target ) :
	if ( target - val1 >= val2 - target ) :
		return val2
	else :
		return val1
arr = [ 1 , 2 , 4 , 5 , 6 , 6 , 8 , 9 ]
n = len ( arr )
target = 11
print ( findClosest ( arr , n , target ) )