0% found this document useful (0 votes)
60 views46 pages

Lec 17-18 Algorithms Updated

This document provides an introduction to algorithms and problem solving. It defines what constitutes a well-defined problem and uses an example of transporting items across a river to illustrate. The document then presents the steps to solve problems, which include defining the problem, considering possible solutions, selecting the best solution, applying it, and iterating if needed. It defines an algorithm as a precise sequence of steps that solves a problem and discusses why algorithms are useful. The document also covers analyzing and selecting among algorithms as well as common algorithm techniques.

Uploaded by

Asad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views46 pages

Lec 17-18 Algorithms Updated

This document provides an introduction to algorithms and problem solving. It defines what constitutes a well-defined problem and uses an example of transporting items across a river to illustrate. The document then presents the steps to solve problems, which include defining the problem, considering possible solutions, selecting the best solution, applying it, and iterating if needed. It defines an algorithm as a precise sequence of steps that solves a problem and discusses why algorithms are useful. The document also covers analyzing and selecting among algorithms as well as common algorithm techniques.

Uploaded by

Asad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Introduction to Computing

Lecture
(Algorithms)

1
DEFINING THE PROBLEM
• A well-defined problem has five components:

– A clearly defined initial situation given.


– A clearly defined goal.
– A clearly defined set of resources.
– A clearly defined constraints.
– Ownership.
CASE STUDY
• You are at a river that you want to cross with all
your goods. Your goods consist of a chicken, a
bag of grain and your cat. You have to cross the
river in your boat but can only take one
passenger with you at a time – the chicken, the
cat or the bag of grain. You can’t leave the
chicken alone with the grain as the chicken will
eat the grain. You can’t leave your cat alone with
the chicken as cat will eat the chicken. However,
you know that cat does not eat grain. How do
you get everything across the river intact?
PROBLEM
• Initial Situation: You, the Chicken, the Bag of
Grain and the Cat are on one bank of a river
with access to a boat.

• Resources: The boat and your knowledge and


problem-solving skills.

• Constraints: You can take only one passenger,


you must not leave Cat with the Chicken, you
must not leave the Chicken with the Grain.
• Goal: You, the Chicken, the Bag of Grain and
the Cat on the opposite bank of river.

• Ownership: You will be involved in planning


the solution and carrying it out.
SOLUTION
• Take the chicken across the river and leave it on the
other side. Return to where you have left Cat and
the Grain.

• Take Cat across the river and leave him on the other
side. Take back the chicken.

• Leave the chicken where you started. Take the bag


of grain across the river and leave it with the Rover.

• Go back and fetch the chicken and take it across the


river with you.
SOLVING PROBLEMS
When faced with a problem:
1. We first clearly define the problem
2. Think of possible solutions
3. Select the one that we think is the best
under the prevailing circumstances
4. And then apply that solution
5. If the solution woks as desired, fine; else we
go back to step 2

7
SOLVING PROBLEM IS ITERATIVE PROCESS
• It is quite common to first solve a problem for a
particular/special case
• Then for another
• And, possibly another
• And watch for patterns and trends that emerge
• And to use the knowledge form those patterns
and trends in coming up with a general solution

8
• If you want to solve a problem, it helps if you have
experienced that problem or similar ones before.

• Generally, there are many ways of solving a


problem. The experienced people find the method
easily to solve a problem. So again experienced
counts.

• The process or set of processes that can be used


to solve a problem is termed as the “algorithm”.
Algorithm (Definition)
• 1st Definition:
Sequence of steps that can be taken to solve a
problem.

• Better Definition:
A precise sequence of a limited number of
unambiguous, executable steps that terminates
in the form of a solution.
THREE REQUIREMENT
1. Sequence is:
a. Precise
b. Consists of limited number of steps

2. Each step is:


a. Unambiguous
b. Executable

3. The sequence of steps terminates in the


form of a solution.
WHY ALGORITHMs ARE USEFULL?
• Once you write an algorithm for a particular
problem. That’s it.

• Next time the same problem arrived again,


you don’t need to do discovery process. It is
already written you just follow it.

• Once the algorithm is known, that recipe you


follow blindly, without thinking.
WHAT IS AN ALGORITHM?
• So, algorithm is knowledge through a problem
can be solved.

• So, to solve a particular problem if you want to


know what kind of knowledge is required. All
of that is embedded in the algorithm of this
problem.
ANALYSIS OF ALGORITHM
• Analysis in the context of algorithms is concerned with
predicting the resources that are requires:
– Computational Time
– Memory
– Bandwidth
– Logic functions

• However, Time – generally measured in terms of number of


steps required to execute an algorithm. Is the resource of
most interest.

• By analyzing several candidate algorithms, the most


efficient one can be indentified.
SELECTING AMONG ALGORITHMS
• Sometimes there are four or five algorithms for the
same problem. By investigating we get to know that all
the algorithm take same resources.

• Ockham’s Razor:
• When choosing among competing, successful solutions
to a problem, chose the one which is least complex.

• The principal is called the “Ockham’s Razor” after


William of Ockham- famous 13th century English
Philosopher.
ALGORITHM TECHNIQUES
• Different kind of algorithm strategies are there
which people follow to write an algorithm:

– Greedy Algorithm
– Deterministic Algorithm
– Randomized Algorithm
– Brute Force Strategy
TRAVELING SALESMAN PROBLEM
• A salesman needs to visit each of the n cities.
120 C 70
B F
60
100 40 30
80 D 50
A G
90

70 110
E

• Is there is a route that takes the salesman through


every city and back to starting city A at a cost of
$520?
A FEW QUESTIONS
• Is that the best possible sequence?
• How do you know?
• How do I determine the best sequence?
How do I determine the sequence that I draw is
the best one, shortened one and optimist one.

Solution: you have to list down all possible


combinations, compute all possible distances.
Have to find minimum distance.
SELECTION OF ALGORITHMIC APPLICATION
AREAS
• Search
• Sort
• Cryptography
• Parallel (algorithm to run on parallel computer)
• Numeric
• Graphical
• Quantum Computing
• Combinatory
SYNTAX & SEMANTICS
• An algo. is correct if its:
– Syntax is correct.
– Semantics are correct.

• Semantics:
The concept embedded in an algorithm(the soul!)

• Syntax:
The actual representation of an algorithm(the
body!)
WARNING!
• An algorithm can be syntactically correct, yet
semantically incorrect- very dangerous
situation!

• Syntactic correctness is easier to check as


compared with semantic.
ALGORITHM REPRESENTATION

• Generally, software developers represent


them in one of three forms:

– Pseudo Code
– Flowcharts
– Actual Code
– Structured English
FLOWCHART
• A graphical representation of a process (e.g.
an algorithm), in which graphic objects are
used to indicate the steps & decisions that are
taken as the process moves along from start to
finish.
Start or stop

Process

Input or output
Flowchart
Elements Decision

Flow line
Connector

Off-page connector
PSEUDO CODE
• Language that is typically used for writing
algorithms.

• Similar to programming language, but not as


rigid.

• Plain English plus some formulas are used to


write pseudo code.
STRUCTURED ENGLISH
• Structured English is a very limited, highly
restricted subset of the English language.

• Non-programmers should also find it easy to


understand.

• There is no standard for structured English.


ACTUAL CODE
• Algorithm in the form of actual code written in
any programming language like C++, Java etc.
ALGORITHM BUILDING BLOCKS
• All problems can be solved by employing
any one of the following building blocks or
their combinations:

1. Sequences (of instructions).


2. Conditionals .
3. Loops (repetition).

• An algorithm is used any one of the


building blocks or its combination.
SEQUENCES
• A sequence of instructions that are executed in the
precise order they are written in:
Pseudo Code Flowchart

Calculate Percentage
Calculate Percentage
Sum ← Num1 + Num2
Average ← Sum/2 Sum ← Num1 + Num2

Average ← Sum/2
CONDITIONALS
• Select between alternate courses of action
depending upon the evaluation of condition:
Pseudo Code Flowchart

True False
condition
If (condition = true)
statement block 1
Else
statement statement
statement block 2 block 1 block 2
End If
LOOPs
• Loop through a set of statements as long as a
condition is true:
Pseudo Code Flowchart
Loop while (condition=true)
Do statement block
End Loop

statement
True
block condition

False
EXAMPLE OF CONDITIONS
• Toss a coin, if the head will occur, then I will
not do my homework assignment. If the tail
will occur, then I will do my homework
assignment.

• So, the conditions always have one of two


outcomes and course of action is determine
accordingly.
REMEMBER
• With the help of these three building blocks
i.e. Sequences, Conditions and Loops. you can
write any algorithm.

• We will go through the problem statement


and present the algorithm in three different
formats:
1. Pseudo Code
2. Flowchart
3. Actual Code
Example
• Write an Pseudo code and draw a flowchart that
calculates the sum and average of two numbers.

• Pseudo code
– Input Number1
– Input Number2
– Sum ← Number1 + Number2
– Average ← Sum/2
– Output Sum, Average

34
Flow Chart
START

Input
Num1, Num2

Sum ← Number1 +
Number2

Average ← Sum/2

Output Sum,
Average

STOP 35
EXAMPLES
• Students appears in an examination, which
consists of total 10 subjects. Each subject having
maximum marks of 100.
– The roll number of the student, his/her name, and the
marks obtained by him/her in various subjects, are
supplied as input data.
– We want to make a list of only those students who
have passed (obtained 50% or more marks) in the
examination.
– In the end, we also want to print out the total number
of students who have passed.
– The input data of all students is terminated by a trailer
record, which has sentinel value of 9999999 for Roll No.
Start Flowchart for the Exam Process
Count = 0

Read
Input
Add 1 to Count

Write
Is RollNo = No Add marks of all Output
999999? Subjects (Total) Yes
Yes No
Percentage = Is percentage
Write Count
Total / 10 = >50?
37
Stop
SOLUTION IN PSEUDO CODE
1) Set Count to zero
2) Read first student record
3) Repeat while RollNo is not equal to 9999999 {
Calculate Total Marks
Calculate Percentage = Total / 10
IF Percentage => 50
Write Output
Add 1 to Count
ENDIF
}
4) Write Count
5) Stop
EXAMPLES
• Draw a flowchart and write pseudo code that
reads three numbers, determine the largest
number and print the largest number with an
identifying message?
SOLUTION IN PSEUDO CODE
1) Let the number be integer and non-negative
2) Set the largest number MAX
2) Read input N1, N2, N3
3) IF(N1 > N2 && N1 > N3)
MAX = N1
ENDIF
IF(N2 > N1 && N2 > N3)
MAX = N2
ENDIF
ELSE
MAX = N3
4) Print “The largest number is: ” MAX
5) Stop
Flowchart of the Example
START

Read A, B, C

Yes If
No If No
A is larger B>A && B>C
A>B && A>C
Print A

Yes
B is larger C is larger
Print B Print C

STOP
EXAMPLE
• A company plans to pay bonus to their employees, the details are
given below:

– Those earning Rs. 30,000 or above are to be paid 20 percent of their salary.

– Those earning less than Rs. 30,000 are to be paid Rs. 1000

– The input records contain the employee number, name and salary of the
employees.

– The output to be printed should contain the employee number, name,


amount of bonus and new salary to be paid to each employee.

• HINT: Formula to calculate Bonus is:


Pros and Cons of Flowcharts (1)
• I personally don’t find flowcharts very useful

• The process of writing an algorithm in the form of a


flowchart is just too cumbersome

• And then converting this graphical form into code is


not straight forward

• However, there is another kind of flowcharts –


called Structured Flowcharts – that may be better
suited for software developers
43
Pros and Cons of Flowcharts (2)
• The good thing about flowcharts is that their
symbols are quite intuitive and almost universally
understood

• Their graphical nature makes the process of


explaining an algorithm to one’s peers quite
straightforward

44
Pros and Cons of Pseudo Code (1)
• Quite suitable for SW development as it is closer in
form to real code

• One can write the pseudo code, then use it as a


starting point or outline for writing real code

• Many developers write the pseudo code first and


then incrementally comment each line out while
converting that line into real code

45
Pros and Cons of Pseudo Code (2)
• Pseudo code can be constructed quite quickly as
compared with a flowchart

• Unlike flowcharts, no standard rules exist for writing


pseudo code

46

You might also like