input: Write a function to find the closest value to a given number in a given array.
  def closest_num(arr, num):
      arr.sort()
      n = len(arr)
      left = 0
      right = n - 1
   
      if arr[right] <= num:
          return arr[right]
      elif arr[left] >= num:
          return arr[left]
      while right-left > 1:
          mid = (right+left)//2
          if arr[mid] == num:
              return arr[mid]
          elif arr[mid] > num:
              right = mid
          else:
              left = mid
      return sorted([arr[right], arr[left]])[0]
  assert closest_num([5, 4, 8, 7], 5) == 5
  assert closest_num([5, 4, 8, 7], 6) == 5
  assert closest_num([5, 4, 8, 7], 9) == 8
  assert closest_num([5, 4, 8, 7], 1) == 4
  assert closest_num([], 5) == None
output: def closest_num(arr, num):
      if not arr:
          return None
      arr.sort()
      n = len(arr)
      left = 0
      right = n - 1
      
      if arr[right] <= num:
          return arr[right]
      elif arr[left] >= num:
          return arr[left]
      
      while right - left > 1:
          mid = (right + left) // 2
          if arr[mid] == num:
              return arr[mid]
          elif arr[mid] > num:
              right = mid
          else:
              left = mid
      
      return arr[left] if num - arr[left] <= arr[right] - num else arr[right]