<jupyter_start><jupyter_text>Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers.Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9}             Target number = 11Output : 99 is closest to 11 in given array Idea:     - Merely an extension to Binary Search Idea    - check if value is greater than middle element       - then the value is in the right half    - check if value is lesser than the middle element       - then the value is in the left half    - check if value is equal to the middle, then return    - when length is 2, then get the number which has minimum absolute difference<jupyter_code>def closest_value_in_array(arr, val):
    """
    """
    if val >= arr[-1]:
        return arr[-1]
    if val <= arr[0]:
        return arr[0]
    
    N = len(arr)
    if N==0:
        return None
    elif N==1:
        return arr[0]
    else:
        if val >= arr[-1]:
            return arr[-1]
        if val <= arr[0]:
            return arr[0]

        if N == 2:
            left = abs(val-arr[0])
            right = abs(val-arr[1])
            if left >= right:
                return arr[1]
            else:
                return arr[0]
        else:
            mid_index = len(arr)//2
            if val > arr[mid_index]:
                return closest_value_in_array(arr[mid_index:], val)
            elif val < arr[mid_index]:
                return closest_value_in_array(arr[: mid_index+1], val)
            else:
                return val

        
print(closest_value_in_array([1, 2, 4, 5, 6, 6, 8, 9], 11))<jupyter_output>9
{'fraction_non_alphanumeric': 0.09491733006736068, 'fraction_numerical': 0.02694427434170239, 'mean_word_length': 1.8172413793103448, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '373665', 'license': 'MIT', 'n_tokens_mistral': 513, 'n_tokens_neox': 478, 'n_words': 185, 'path': 'leet/plan/algorithms/divide_and_conquer/algorithms/divide-and-conquer/closest_value_in_array/closest_value_in_array.ipynb', 'repo_name': 'manojkumar-github/DataStructures-DynamicProgramming-in-Python-JAVA-Cplusplus', 'size': '1633'}