Professional Documents
Culture Documents
209 0809F L05 Section04 01 IntroductionToAlgorithms Notes0001
209 0809F L05 Section04 01 IntroductionToAlgorithms Notes0001
Section 4.1
Contents
1 Algorithms 2
1.1 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Properties of Algorithms . . . . . . . . . . . . . . . . . . . . . . 2
2 Examples of Algorithms 2
2.1 Pseudocode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Maximum of Three Numbers . . . . . . . . . . . . . . . . . . . . 3
2.3 Tracing Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4 Maximum Value of a Sequence . . . . . . . . . . . . . . . . . . . 5
1
1 Algorithms
1.1 Algorithms
Algorithms
2 Examples of Algorithms
2.1 Pseudocode
Pseudocode
2
• We relax syntax requirements of actual computer languages
• Only care about eliminating ambiguity
• Idea: Can translate pseudocode into actual code with minimal effort
1. max3(a,b,c){
2. large = a
// if b is greater than large, update large
3. if (b > large)
4. large =b
// if c is greater than large, update large
5. if (c > large)
6. large = c
7. return large
8. }
3
2.3 Tracing Algorithms
Tracing Algorithms
Trace of max3
Find the largest of the numbers a, b and c
Input: a, b, c
Output: large (the largest of a, b and c)
1. max3(a,b,c){
2. large = a
// if b is greater than large, update large
3. if (b > large)
4. large = b
// if c is greater than large, update large
5. if (c > large)
6. large = c
7. return large
8. }
Input: a = 7, b = 2, c = 9
Input: a = 4, b = 6, c = 6
4
2.4 Maximum Value of a Sequence
Finding the Maximum Value of a Sequence
Find the largest of the numbers s1 , s2 , . . . , sn
Input: s, n
Output: large (the largest value
in the sequence s)
1. max(s,n){
2. large = s1
3. for i = 2 to n
4. if (si > large)
5. large = si
6. return large
7. }
Input: s = 3, 6, 1, 6, 11, 7;
n=6
Summary
Summary
You should be able to:
• Trace an algorithm