Do exercise 14.1 on pages 269-270 except for implementation of the best-fit algorithm in java. That is, do the exercise starting from the third paragraph onwards.
Exercise 14.x1: Consider the following two nearly identical Java programs,
each of which uses an array of Integers, s, as a stack,
with sp serving the role of stack pointer. Each program
repeats 100 times the following two stages:
(1) push the Integers 0 up to 100000, (2) pop them all back off.
public class Bar {
public static void main(String[] args){
Integer[] s = new Integer[100000];
int sp = 0;
for(int i = 0; i < 100; i++){
for(int j = 0; j < 100000; j++){
s[sp++] = j;
}
while(sp > 0){
--sp;
}
}
}
}
public class Baz {
public static void main(String[] args){
Integer[] s = new Integer[100000];
int sp = 0;
for(int i = 0; i < 100; i++){
for(int j = 0; j < 100000; j++){
s[sp++] = j;
}
while(sp > 0){
s[--sp] = null;
}
}
}
}
Answer the following questions about these two programs:
Why might Bar be faster than Baz?
Why might Baz be faster than Bar? (Hints: (1) What chapter is this
problem associated with? (2) The assignment s[sp++] = j uses a feature known as autoboxing, whereby it is a shorthand for s[sp++] = new Integer(j).)
By guessing which of these effects is larger, which of the two programs do you expect to be faster?
Which one actually is faster? How many times faster? To time
a java program, you can use the shell command time, as in
time java Bar