int find_closest(int A[], int N, int target) {
if(target < A[0]) return A[0];
if(target > A[N-1]) return A[N-1];
int low = 0, high = N-1;
while(low <= high) {
int mid = low + (high - low) / 2;
if(A[mid] == target) return target;
else if(A[mid] < target) low = mid+1;
else high = mid-1;
} // after this step, if 'target' is still not found, 'low' is always a bit larger than 'target'
if(A[low] - target < target - A[low-1])
return A[low];
else
return A[low-1];
}