Friday, 15 April 2011

java - Midpoint Formula Overflow Error -



java - Midpoint Formula Overflow Error -

i'm learning algorithms/big o , curious this.

the utilize of

mid = (low+high)/2;

in order midpoint binary search algorithm discouraged because of possibility of overflow error. why cause overflow error occur, , how

mid = low + (high-low)/2;

prevent error?

thanks.

in first case calculate value (low+high) might huge fit int, if low , high both huge plenty (say if both equal 2^30+1 /or greater/). in sec case, don't calculate (low+high), little trick , go through look (high-low) , look much safer respect int overflow.

still, if don't have array size greater 2^30 (which quite huge array anyway), don't see how can run int overflow when using first expression. utilize first 1 in cases , not worry.

java algorithm binary-search

No comments:

Post a Comment