From 7985059f7d7543d1afda33b38fdf631a36e8e889 Mon Sep 17 00:00:00 2001 From: Rakshit Gondwal <98955085+rakshitgondwal@users.noreply.github.com> Date: Wed, 20 Jul 2022 04:39:09 +0530 Subject: [PATCH] enh(CPlusPlus): add binary search (#777) Improved the code by adding the explanation of using (l + (r - l)) rather than using (l - r) while searching for the mid element. --- algorithms/CPlusPlus/Searching/binary-search.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/algorithms/CPlusPlus/Searching/binary-search.cpp b/algorithms/CPlusPlus/Searching/binary-search.cpp index 46cb09ee..0603d02e 100644 --- a/algorithms/CPlusPlus/Searching/binary-search.cpp +++ b/algorithms/CPlusPlus/Searching/binary-search.cpp @@ -7,6 +7,9 @@ int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; + //We use (l + (r - l)) rather than using (l - r) to avoid arithmetic overflow. + //Arithmetic overflow is the situation when the value of a variable increases + //beyond the maximum value of the memory location, and wraps around. // If the element is present at the middle itself if (arr[mid] == x)