Reputation: 13
I've seen this code and it's supposed to be fine, I don't understand why if for example "left + right" is an odd number, doing "a[middle] == 0" doesn't give error because it doesn't exist in arrays decimal positions. Thank you.
/** Searches the value 0 within a[left..right].
* Precondition: 0 <= left, right < a.length,
* a[left..right] is sorted in ascending order. */
public static int intercepts(double[] a, int left, int right) {
if (left > right) { return -1; }
else {
int middle = (left + right) / 2;
if (a[middle] == 0) { return middle; }
else if (a[middle] > 0) {
return intercepts(a, left, middle - 1);
} else {
return intercepts(a, middle + 1, right); }
}
}
Upvotes: 0
Views: 845
Reputation: 66
Since the two operands (left
and right
) are integers then integer arithmetic is used. When the division is applied, the remainder of the result will be "rounded" down to zero.
Example
5/2 = 2
7/3 = 2
8/3 = 2
See the following article for a better explanation. Int division: Why is the result of 1/3 == 0?
Upvotes: 3
Reputation: 14365
left
, right
and 2
are all integers, therefore an integer division will be performed and the result will also be an integer. Integer division rounds toward 0, so all decimals are simply cut off.
public static void main (String[] args) {
int middle = 5 / 2;
System.out.println(middle); // 2
}
Upvotes: 3