Re: Beginner Projects
- From: Patricia Shanahan <pats@xxxxxxx>
- Date: Thu, 30 Aug 2007 07:19:43 -0700
Joshua Cranmer wrote:
Roedy Green wrote:On Thu, 30 Aug 2007 00:32:11 -0400, Lew <lew@xxxxxxxxxxxxx> wrote,
quoted or indirectly quoted someone who said :
. OTOH, this counts as "premature optimization" in many cases.
It is simpler code, so I don't count it as optimisation. Optimisation
that gets you in trouble is verbose, harder-to-maintain code. I
figure every student should be familiar with odd/even idiom.
Sometimes it can save you.
int mid = (low + high) / 2;
int mid = (low + high) >>> 1;
The first one breaks when low + high > 2^31-1, the second one doesn't (only when low + high > 2^32 - 1).
Maybe there is something I'm not understanding here. I just did some
tests, and as far as I can tell, whenever they differ the first method
gets the right answer. Could you suggest some inputs that demonstrate
the benefit of the second version?
Results:
low=0, high=2147483647, mid1=1073741823, mid2=1073741823
! low=-5, high=-3, mid1=-4, mid2=2147483644
! low=-5, high=-2, mid1=-3, mid2=2147483644
low=-100, high=2147483647, mid1=1073741773, mid2=1073741773
! low=-2147483648, high=1000, mid1=-1073741324, mid2=1073742324
! low=-2147483648, high=2147483647, mid1=0, mid2=2147483647
Test program:
public class MidTest {
public void test(int low, int high){
int mid1 = (low + high) / 2;
int mid2 = (low + high) >>> 1;
if(mid1 != mid2){
System.out.print("! ");
}
System.out.printf(
"low=%d, high=%d, mid1=%d, mid2=%d%n",
low,high,mid1,mid2);
}
public static void main(String[] args) {
MidTest tester = new MidTest();
tester.test(0,Integer.MAX_VALUE);
tester.test(-5,-3);
tester.test(-5,-2);
tester.test(-100,Integer.MAX_VALUE);
tester.test(Integer.MIN_VALUE,1000);
tester.test(Integer.MIN_VALUE,Integer.MAX_VALUE);
}
}
.
- Follow-Ups:
- Re: Beginner Projects
- From: Joshua Cranmer
- Re: Beginner Projects
- References:
- Beginner Projects
- From: Pseudo Silk Kimono
- Re: Beginner Projects
- From: Roedy Green
- Re: Beginner Projects
- From: Lew
- Re: Beginner Projects
- From: Roedy Green
- Re: Beginner Projects
- From: Joshua Cranmer
- Beginner Projects
- Prev by Date: Re: Beginner Projects
- Next by Date: Re: Beginner Projects
- Previous by thread: Re: Beginner Projects
- Next by thread: Re: Beginner Projects
- Index(es):
Relevant Pages
|