Advanced Programming Techniques
Advanced Programming Techniques
Programming
Techniques
Lecture 3
Efficiency
• In computer science, often the question is
not how to solve a problem, but how to
solve a problem well
• Many sorting algorithms are well-known;
the problem is not to find a way to sort
words, but to find a way to efficiently sort
words.
• We are interested in solutions that
optimize the use of computing and human
resources
Efficiency
• If it's possible to solve a problem by using a brute force technique,
such as trying out all possible combinations of solutions (for
instance, sorting a group of words by trying all possible orderings
until you find one that is in order), then why is it necessary to find
a better approach?
• if you had a fast enough computer, maybe it wouldn't be. But as it
stands, we do not have access to computers fast enough.
• For instance, if you were to try out all possible orderings of 100
words, that would require 100! (100 factorial) orders of words.
• That's a number with a 158 digits; were you to compute
1,000,000,000 possibilities per second, you would still be left with
the need for over 1x10^149 seconds, which is longer than the
expected life of the universe.
• Clearly, having a more efficient algorithm to sort words would be
handy; and, of course, there are many that can sort 100 words
within the life of the universe.
Resources
• Resources relevant to execution are
– Processor
– internal memory
• Algorithms should be economical in
the use of resources
• No general recipe for efficiency
• Avoid redundant computations
Example
• Common mistake is to recalculate
expressions in a loop
x :=0;
for i:= 1 to n do
begin
x:=x+0.01;
y:=(a*a*a+c)*x*x+b*b*x
writeln(‘x = ‘,x,’y = ‘,y);
end;
Example
• Redundant computations are avoided by
precomputing
a3c := a*a*a+c;
b2 := b*b;
x := 0;
for i:= 1 to n do
begin
x:=x+0.01;
y:=(a3c)*x*x+b2*x
writeln(‘x = ‘,x,’y = ‘,y);
end;
• Eliminate redundancies in the innermost
loops of computations
Array Processing
• Inefficiencies creep into array
processing:
• Example
p:=1;
for i:= 2 to n do
if(a[i]>a[p]) then p:=i;
max:=a[p];
2 1 2 4 8 4
• g(n)=3n2+6n+3 and
lim 3n2+6n+3 =3
n∞ n2