0% found this document useful (0 votes)
5 views38 pages

Ehb208e 3

Uploaded by

kubrabakal01
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)
5 views38 pages

Ehb208e 3

Uploaded by

kubrabakal01
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/ 38

Data Structures

BLG221E

Algorithm
s

BLG221E
ALGORITHMS AND FLOWCHARTS

Computer programming can be divided into two


phases:

• Problem solving phase


– Make an ordered sequence of steps that solves
a problem
– these sequence of steps is called an
algorithm

• Implementation phase
– implement using a programming language
Steps in Problem Solving

First produce a general algorithm


(pseudocode can be used)

Afterwards, refine your steps.

Pseudocode is an artificial and informal


language that helps programmers develop
algorithms. Pseudocode may be an informal
English, combinations of computer languages and
spoken language. Whatever works for you.
Example 1:
Write an algorithm to determine a student’s final
grade and indicate whether it is passing (>60)
or failing. The final grade is calculated as the
average of four marks.

Pseudocode of algorithm:
 Input a set of 4 marks
 Calculate their average by summing and dividing
by 4
 if average is below 60
Print “FAIL”
else
Print “PASS”
The Flowchart
Flowchart is another algorithm representation but graphical.
 A flowchart must have a one START
start and one stop
 Steps in a flowchart must Input
M1,M2,M3,M4
connect. Can’t leave a step
“hanging” with no
connection. GRADE(M1+M2+M3+M4)/4

N IS Y
GRADE<60

PRINT PRINT
“PASS” “FAIL”

STOP
Flowchart Symbols We see some of the
most common
Name Symbol Use in Flowchart
flowchart symbols in
this picture.
Oval Denotes the beginning or end of the program

Parallelogram Denotes an input operation

Rectangle Denotes a process to be carried out


e.g. addition, subtraction, division etc.

Diamond Denotes a decision (or branch) to be made.


The program should continue along one of
two routes. (e.g. IF/THEN/ELSE)

Hybrid Denotes an output operation

Flow line Denotes the direction of logic flow in the program


Example
1
Write an algorithm and then draw the flowchart that will
calculate the roots of a quadratic equation
2
ax
quadratic equation:  bx  c 0
2
Hint: d = sqrt b
(  4ac ),

and the roots are:


x1 = (–b + d)/2a and x2 = (–b – d)/2a
Pseudocode:
 Input the coefficients (a, b, c) of the quadratic
equation
 Calculate d
 Calculate x1
 Calculate x2
 Print x1 and x2
Example 1

START
Algorithm:
 Step 1: Input a, b, c Input
a, b, c
 Step 2: d  sqrtb 
( b  4 a c )
 Step 3: x1  (–b + d) / (2 x a) d  sqrt(b x b – 4 x a x c)
 Step 4: x2  (–b – d) / (2 x a) x (–b + d) / (2 x a)
1

 Step 5: Print x1, x2


X2  (–b – d) / (2 x a)

Print
x1 ,x2

STOP
Example 2 (Your job)
Draw the flowchart of the factorial calculation.
Example 3 (Your job)
Draw the flowchart of finding the smallest element of the
given list.
THREE CONSTRUCTS
Computer scientists have defined three
constructs for a structured program or
algorithm.

The idea is that a program must be made of a


combination of only these three constructs:
sequence, decision (selection) and repetition.

It has been proven that there is no need for any


other constructs. Using only these constructs
makes a program or an algorithm easy to
understand, debug or change.
Sequence: The first construct is called the sequence. An algorithm
and eventually a program is a sequence of instructions, which can
be a simple instruction or either of the other two constructs.
Decision: Some problems cannot be solved with only a sequence of
simple instructions. Sometimes we need to test a condition. If the
result of testing is true, we follow a sequence of instructions: if it is
false, we follow a different sequence of instructions.
Repetition: In some problems, the same sequence of instructions
must be repeated. We handle this with the repetition or loop
construct.
Figure: Pseudocode for three constructs
BASIC ALGORITHMS

Several algorithms are used in computer science.


We discuss the most common here.

Summation Sorting

Product

Smallest and
largest
Summation Algorithm
One commonly used algorithm in computer science is
summation. We can add two or three integers very easily,
but how can we add many integers?
The solution is simple: we use add operator in a loop.

A summation algorithm has


three logical parts:

1. Initialization of the sum


(variable) to zero at the
beginning.
2. The loop, which in each
iteration adds a new
integer to the sum.
3. Return of the result after
exiting from the loop.
Product Algorithm
Another common algorithm is finding the product of a list
of integers. The solution is simple: use the multiplication
operator in a loop.
A product algorithm
has three logical
parts:
1. Initialization of the
product (variable) to
one at the beginning.
2. The loop, which in each
iteration multiplies a
new integer with the
product.
3. Return of the result
after exiting from the
loop.
Find Smallest and Largest Algorithm
Largest Algorithm: The idea is to write a decision
construct to find the larger of two integers. If we put
this construct in a loop, we can find the largest of a
list of integers.

Smallest Algorithm: The idea is to write a decision


construct to find the smaller of two integers. If we
put this construct in a loop, we can find the smallest
of a list of integers.
Sorting Algorithm
One of the most common applications in
computer science is sorting. People are surrounded by
data.

If the data was not ordered, it would take hours


and hours to find a single piece of information.
Imagine the difficulty of finding someone’s telephone
number in a telephone book that is not ordered.

In this section, we introduce three sorting


algorithms: selection sort, bubble sort and
insertion sort.
Selection Sort Algorithm
• In a selection sort, the list to be sorted is divided into two
sublists—sorted and unsorted—which are separated by an
imaginary wall.
• We find the smallest element from the unsorted sublist and
swap it with the element at the beginning of the unsorted
sublist.
• After each selection and swap, the imaginary wall between the
two sublists moves one element ahead.
right

Figure: Selection sort algorithm


Bubble Sort Algorithm
An example of bubble sort. Starting from the beginning
of the list, every adjacent pair are compared.
We swap their position if they are not in the right order
(the latter one is smaller than the former one).
After each iteration, one less element (the last one) is
needed to be compared until there are no more
elements left to be compared.
Insertion Sort Algorithm
The insertion sort algorithm is one of the most common
sorting techniques, and it is often used by card players.
Each card is picked up from the unsorted list and is
inserted into the proper place of the sorted list.
Searching Algorithm
Another common algorithm in computer science is
searching, which is the process of finding the location
of a target value among a list of objects.

There are two basic searches for lists:


sequential search and binary search.

Sequential search can be used to locate an item in


any list, whereas binary search requires the list first
to be sorted.
Sequential search
Sequential search is used if the list to be searched
is not ordered. Generally, we use this technique
only for small lists, or lists that are not searched
often.
In a sequential search, we start searching for
the target from the beginning of the list. We
continue until we either find the target or reach
the end of the list.
Figure: An example of a sequential search
Binary search
The sequential search algorithm is very slow. If we
have a list of a million elements, we must do a
million comparisons in the worst case. If the list is
not sorted, this is the only solution.

If the list is sorted, however, we can use a more


efficient algorithm called binary search. Generally
speaking, programmers use a binary search when a
list is large.
Binary search
A binary search starts by testing the sorted data at the
middle of the sorted list.

• This determines whether


the target is in the first
half or the second half of
the list.
• If it is in the first half,
there is no need to
further check the second
half. If it is in the second
half, there is no need to
further check the first
half.
• In other words, we
eliminate half the list
from further
consideration.
SUBALGORITHMS
The three programming constructs (sequence, repetition and
desicion) allow us to create an algorithm for any solvable problem.
An algorithm can be broken into small units called subalgorithms.
Each subalgorithm is in turn divided into smaller subalgorithms.
Iteration and recursion
In general, there are two approaches to writing algorithms
for solving a problem: Iteration and recursion.

An algorithm is defined This solution usually


recursively whenever the involves a loop. An
algorithm appears within algorithm is iterative
the definition itself. whenever the definition
does not involve the
algorithm itself.
Recursion
• In some problems, it may be natural to define the
problem in terms of the problem itself.
• Recursion is useful for problems that can be
represented by a simpler version of the same
problem.

Example:
• the factorial function
6! = 6 * 5 * 4 * 3 * 2 * 1

We could write:
6! = 6 * 5!
Example 2: factorial function
In general, we can express the factorial
function as follows:
n! = n * (n-1)!
Is this correct? Well… almost.

The factorial function is only defined for


positive integers. So we should be a bit more
precise:

n! = 1 (if n is equal to 1)
n! = n * (n-1)! (if n is larger than 1)
Factorial function
For certain problems (such as the factorial
function), a recursive solution often leads to short
and elegant code. Compare the recursive solution
with the iterative solution:
Recursive solution Iterative
solution
int fac (int numb){ int fac (int numb) {
if(numb<=1)
return 1; int product=1;
else
return numb*fac(numb- while(numb>1)
1); {
} product
*= numb;

numb--; }

return product;
Recursion
We have to pay a price for recursion:
calling a function consumes more time and memory
than adjusting a loop counter.
High performance applications (graphic action games,
simulations of nuclear explosions) hardly ever use
recursion.
In less demanding applications recursion is an
attractive alternative for iteration (for the right
problems!)
Recursion
If we use iteration, we must be careful not to
create an infinite loop by accident:

for(int incr=1; incr!=10;incr+=2)


...
Oops!
int result = 1;
while(result >0) {
...
result++;
}
Oops!
Recursion
Similarly, if we use recursion we must be
careful not to create an infinite chain of
function calls:
int fac (int numb) {
return numb * fac(numb-1);
}

Oops!
No
terminatio
n condition

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy