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
parent
7985059f7d
commit
bfcae851a0
|
@ -5,7 +5,10 @@ class BinarySearch {
|
||||||
int binarySearch(int arr[], int l, int r, int x)
|
int binarySearch(int arr[], int l, int r, int x)
|
||||||
{
|
{
|
||||||
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
|
||||||
|
|
Loading…
Reference in New Issue