Lecture 08 Algorithms
Lecture 08 Algorithms
Making it efficient
(eventually)
Algorithm Example
How to
How to
compare two
Where and When and continue the
list items to
how to start how to stop determine search when
you haven’t
the search? the search? which is
found the
“before”
another? word yet?
Characteristics of Algorithm
Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases),
and their inputs/outputs should be clear and must lead to only one meaning.
Finiteness − Algorithms must terminate after a finite number of steps. Stopping may mean
that you get the expected output OR you get a response that no solution is possible.
Effectiveness - It means that all those steps that are required to get to output must be
feasible with the available resources. It should not contain any unnecessary and redundant
steps which could make an algorithm ineffective. For Eg: suppose you are cooking a recipe and
you chop vegetables which are not be used in the recipe then it is a waste of time.
Independent − An algorithm should have step-by-step directions, which should be
independent of any programming code.
Completeness
1. Go to shop
2. Buy Chocolate Muffins
3. Return home
Is this complete?
Computing without computers, Paul Curzon
Completeness
1. Go to shop
2. If shop has Chocolate Muffins
• Then buy Chocolate Muffins
• Else if the shop has Croissants
• Then buy Croissants
• Else buy nothing
3. Return home
Determinism
1. Go to shop
2. If shop has Chocolate Muffins
• Then buy Chocolate Muffins
• Else if the shop has Croissants
• Then buy Croissants
• Else buy nothing
3. Return home
Determinism
1. Go to shop
2. If shop has Chocolate Muffins
Then buy Chocolate Muffins
Else if the shop has Croissants
Then buy Croissants
Else buy anything
3. Return home
Is this deterministic?
Computing without computers, Paul Curzon
Termination
An algorithm should always
finish and produce a result
How to write
Algorithms
Type I: Algorithm:
Sequential 1.Start
2. Declare variables area, radius.
Flow of 3: Read the value, radius.
the algorithm 4: Compute area= pi *radius^2.
is sequential 5. Display "The area is", area
Ex: Find the 6. Stop
area of the
circle
Type II:
Selection/
Branching Algorithm:
1.Start
Flow of 2.Declare variables a,b.
the algorithm 3. Read the values, a,b.
is Branching 4.If a > b is true
4.1 Display a is the largest number.
Ex: Find the
4.2 goto step 6
largest number
5. otherwise
among two
5.1 Display b is the largest number.
different numbers
6.Stop
Type III:
Repetition/ Algorithm:
1.Start
Looping
2. Initialize number=1
Flow of 3. Print the value of number.
the algorithm 4. Let number =number + 1.
is Repetition 5. Repeat the step 3,4 until number > 11.
Ex: Display the 6. Stop
numbers from 1
to 10