input: from typing import List
  
  def closest_num(arr: List[int], num: int) -> int:
      """Find the closest value to a given number in a given array.
      >>> closest_num([5, 4, 8, 7], 6)
      7
      >>> closest_num([5, 4, 8, 7], 8)
      8
      """
      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]
output:     if abs(arr[left] - num) <= abs(arr[right] - num):
          return arr[left]
      else:
          return arr[right]