Академический Документы
Профессиональный Документы
Культура Документы
Experimental Studies
Write a program
implementing the
algorithm
Run the program with
inputs of varying size and
composition
Use a method like
System.currentTimeMillis() to
get an accurate measure
of the actual running time
Plot the results
Limitations of Experiments
It is necessary to implement and test the algorithm
in order to determine its running time which may
be difficult
Results may not be indicative of the running time
on other inputs not included in the experiment.
In order to compare two algorithms, the same
hardware and software environments must be used
Pseudocode
Example: find
High-level description
max element of
of an algorithm
an array
More structured than Algorithm
arrayMax(A, n)
English prose
Input array A of n integers
Less detailed than a
Output maximum element of A
program
currentMax A[0]
Preferred notation for
for i 1 to n 1 do
describing algorithms
if A[i] currentMax then
Hides program design
currentMax A[i]
issues
return currentMax
Pseudocode Details
Control flow
if then [else ]
while do
repeat until
for do
Indentation replaces braces
Method declaration
Algorithm method (arg [, arg])
Input
Output
Method call
var.method (arg [, arg])
Return value
return expression
Expressions
Assignment
(like in Java)
Equality testing
(like in Java)
n2 Superscripts and other
mathematical formatting
allowed
Primitive Operations
Examples:
Basic computations
Evaluating an expression
performed by an algorithm
(if i<n)
Identifiable in pseudocode
Assigning a value to a
variable (i5)
Largely independent from
Indexing into an array
the programming language
(A[4])
Exact definition not
Calling a method
important (we will see why
(O.method(arg))
later)
Returning from a method
Assumed to take a
(return i)
Performing an arithmetic
constant amount of time in
operation (i+j)
the RAM model
Algorithm arrayMax(A, n)
1) currentMax A[0]
2) for i 1 to n 1 do
3)
if A[i] currentMax then
4)
currentMax A[i]
5)
i i+1
6) return currentMax
1
n
(n 1)
(n 1)
(n 1)
1
Total
4n 1
Growth Rates
Growth rates of
functions:
Linear n
Quadratic n2
Cubic n3
n2
n3
16
64
64
512
10
100
1000
100
104
106
1000
106
109
Constant Factors
The growth rate is
not affected by
constant factors
or
lower-order
terms
Examples
10n is a linear
function
n2 10n is a
quadratic
function
Example:
We determine that algorithm arrayMax executes at most 8n
- 2 primitive operations
We say that algorithm arrayMax runs in O(n) time
Arithmetic Progression
The running time of
prefixAverages1 is
O(1 + 2 + + n)
The sum of the first n
integers is n(n + 1) / 2
- There is a simple visual
proof of this fact
Thus, algorithm
prefixAverages1 runs in
O(n2) time
(Try it yourself)
Algorithm arrayMax(A, n)
Input array A of n integers
Output maximum element
of A
currentMax A[0]
for i 1 to n 1 do
if A[i] currentMax then
currentMax A[i]
return
currentMax