Invariant on "Find K Closest Elements" problem
If x - arr[mid] &lt;= arr[mid+k] - x, then for any l that l &gt; mid, we have

x - arr[l-1] &lt;= x - a[mid] &lt;= arr[mid+k] - x &lt;= arr[l+k] - x,
arr[l-1] - x &lt;= arr[l+k] - x,


which means |arr[l-1] - x| &lt;= |arr[l+k] - x|. So for any range [l, l+k] where l &gt; mid, we can move it to left until l == mid while the elements contained are no farther from x, therefore it is safe to set right = mid.

Otherwise, the proof is similar.