enh(Java): add comments for binary search (#776)

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:41:47 +05:30 committed by GitHub
parent 7985059f7d
commit bfcae851a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 4 additions and 1 deletions

View File

@ -6,6 +6,9 @@ class BinarySearch {
{ {
if (r >= l) { if (r >= l) {
int mid = l + (r - l) / 2; 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 // If the element is present at the
// middle itself // middle itself