12 | February 2009 | LINuX For you | www.
openITis.
com
S.
G.
Ganesh
The Joy of Programming | Guest Column
H
ow does one calculate the average of two integers,
say i and j? Trivial you would say: it is (i + j) / 2.
Mathematically, that’s correct, but...
More
12 | February 2009 | LINuX For you | www.
openITis.
com
S.
G.
Ganesh
The Joy of Programming | Guest Column
H
ow does one calculate the average of two integers,
say i and j? Trivial you would say: it is (i + j) / 2.
Mathematically, that’s correct, but it can overflow
when i and j are either very large or very small when using
fixed-width integers in C-based languages (like Java).
Many other languages like Lisp and Python do not have
this problem.
Avoiding overflow when using fixed-width
integers is important, and many subtle bugs occur because
of this problem.
In his popular blog post [1], Joshua Bloch (Java expert and
author of books on Java intricacies) writes about how a bug
[2] in binarySearch and mergeSort algorithms was found in
his code in java.
util.
Arrays class in JDK.
It read as follows:
1: public static int binarySearch(int[] a, int key) {
2: int low = 0;
3: int high = a.
length - 1;
4:
5: while (low <= high) {
6: int mid = (low + high) / 2;
7: int midVal = a[mid];
Less