An Introduction to
Algorithm
OBJECTIVES
● Understand the concept of an algorithm.
● Define and use the three constructs for
developing algorithms:
● sequence, decision, and repetition.
● Understand and use three tools to represent
algorithms:
● flowchart, pseudocode, and structure chart.
● Understand the concept of modularity and
subalgorithms.
CONCEPT
Algorithms
∙ Algorithm comes from the name of a Persian mathematician Abu
Ja’far Mohammed ibn-i Musa al Khowarizmi.
∙ A special method useable by a computer for solution of a problem.
∙ The statement of the problem specifies in general terms the desired
input/output relationship.
∙ For example, sorting a given sequence of numbers into
nondecreasing order provides fertile ground for introducing many
standard design techniques and analysis tools.
Informal definition of an algorithm
used in a computer
Criteria of an Algorithm
• Input
✔ 0 or more quantities are externally supplied
• Output
✔ At least 1 quantity is produced
• Definiteness
✔ Each instruction is clear and unambiguous
• Finiteness
✔ Terminates at a finite number of states
• Effectiveness
✔ Instruction must be basic to carry out principle
Area of study
• How to devise an Algorithm
✔ Study various techniques
• How to validate an Algorithm
✔ Show that it computes the correct answer for all possible legal input.
• How to analyze an Algorithm
✔ Time complexity
✔ Space complexity
• How to test a program
✔ Debugging
✔ Profiling
Finding the largest integer among five integers
Defining actions in FindLargest algorithm
FindLargest refined
Generalization of FindLargest
THREE CONSTRUCTS
Three constructs
ALGORITHM
REPRESENTATIO
N
Flowcharts for three constructs
Pseudocode for three constructs
Example 1
Write an algorithm in pseudocode that finds
the average of two numbers
Solution: Average of two
AverageOfTwo
Input: Two numbers
1. Add the two numbers
2. Divide the result by 2
3. Return the result by step 2
End
Example 2
Write an algorithm to change a numeric
grade to a pass/no pass grade.
Solution: Pass/no pass Grade
Pass/NoPassGrade
Input: One number
1. if (the number is greater than or equal to 70)
then
1.1 Set the grade to “pass”
else
1.2 Set the grade to “nopass”
End if
1. Return the grade
End
Example 3
Write an algorithm to find the largest of
1000 numbers.
Solution: Find largest of 1000 numbers
FindLargest
Input: 1000 positive integers
1. Set Largest to 0
2. Set Counter to 0
3. while (Counter less than 1000)
3.1 if (the integer is greater than Largest)
then
3.1.1 Set Largest to the value of the integer
End if
3.2 Increment Counter
End while
4. Return Largest
End
SUBALGORITHMS
Figure 8-9
Concept of a subalgorithm
Find largest
FindLargest
Input: A list of positive integers
1. Set Largest to 0
2. while (more integers)
2.1 FindLarger
End while
3. Return Largest
End
Subalgorithm:
FindLarger
Input: Largest and current integer
1. if (the integer is greater than Largest)
then
1.1 Set Largest to the value of the integer
End if
End