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.
pull/769/head^2
Rakshit Gondwal 2022-07-20 04:39:09 +05:30 committed by GitHub
parent 4add09632e
commit 7985059f7d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 3 additions and 0 deletions

View File

@ -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)