0% found this document useful (0 votes)
19 views58 pages

EHB208E 3 Lesson

Uploaded by

seyitsavas45
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)
19 views58 pages

EHB208E 3 Lesson

Uploaded by

seyitsavas45
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/ 58

Data Structures

BLG221E

Algorithm
s

EHB208E
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
EXAMPLE
How do you print the first non-repeated character from a
string?
EXAMPLE
How can a given string be reversed using recursion?
EXAMPLE
1.How do you check if a string contains only digits?

2.How are duplicate characters found in a string?

3.How do you remove duplicates from an array in place?


Steps in Problem Solving

First produce a general algorithm


(pseudocode can be used)

Afterwards, refine your steps. Pseudoco


de
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 and one stop
 Steps in a flowchart must connect. Can’t leave a
step “hanging” with no connection.
Name Symbol Use in Flowchart

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


We see some of the
most common
Flow line Denotes the direction of logic flow in the program flowchart symbols in
Flowchart Symbols
this picture.
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
“go to”
command not
allowed

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 to make a program or an algorithm easy
to understand, debug, or change.
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.
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 four sorting


algorithms: selection sort, bubble sort, merge
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.
And, this imaginary wall is placed at the left most part of the list.
• 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
Starting from the beginning of the list, every adjacent
pair are compared.
We swap their positions if they are not in the right order
After each iteration, one less element 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.
list to be sorted
How many passes does an insertion sort algorithm
consist of?
a) N
b) N-1
c) N+1
d) N2
View Answer
Answer: b
Explanation: An insertion algorithm consists of N-1 passes
when an array of N elements is given
Consider an array of length 5, arr[5] = {9,7,4,2,1}.
What are the steps of insertions done while running
insertion sort on the array?
a) 7 9 4 2 1 4 7 9 2 1 2 4 7 9 1 1 2 4 7 9
b) 9 7 4 1 2 9 7 1 2 4 9 1 2 4 7 1 2 4 7 9
c) 7 4 2 1 9 4 2 1 9 7 2 1 9 7 4 1 9 7 4 2
d) 7 9 4 2 1 2 4 7 9 1 4 7 9 2 1 1 2 4 7 9

View Answer
Answer: a
Explanation: The steps performed while running insertion sort on given
array are:
Initial : 9 7 4 2 1 key = 7
7 9 4 2 1 key = 4
4 7 9 2 1 key = 2
2 4 7 9 1 key = 1
12479
Merge Sort Algorithm
• To sort an array A[p . . r]:
• Divide
– Divide the n-element sequence to be sorted into two
subsequences of n/2 elements each
• Conquer
– Sort the subsequences recursively using merge sort
– When the size of the sequences is 1 there is nothing
more to do
• Combine
– Merge the two sorted subsequences
Example – Size of the list is Power of
2

1 2 3 4 5 6 7 8

Divide 5 2 4 7 1 3 2 6 q=4

1 2 3 4 5 6 7 8

5 2 4 7 1 3 2 6

1 2 3 4 5 6 7 8

5 2 4 7 1 3 2 6

1 2 3 4 5 6 7 8

5 2 4 7 1 3 2 6
Example – Size of the list is Power of 2

1 2 3 4 5 6 7 8

Conquer 1 2 2 3 4 5 6 7
and Merge
Merge algorith
1 2 3 4 5 6 7 8 m is
2 4 5 7 1 2 3 6 called

1 2 3 4 5 6 7 8

2 5 4 7 1 3 2 6

1 2 3 4 5 6 7 8

5 2 4 7 1 3 2 6
Example – Size of the list is Not a Power of 2
1 2 3 4 5 6 7 8 9 10 11

Divide 4 7 2 6 1 4 7 3 5 2 6 q=6

1 2 3 4 5 6 7 8 9 10 11

q=3 4 7 2 6 1 4 7 3 5 2 6 q=9

1 2 3 4 5 6 7 8 9 10 11

4 7 2 6 1 4 7 3 5 2 6

1 2 3 4 5 6 7 8 9 10 11

4 7 2 6 1 4 7 3 5 2 6

1 2 4 5 7 8

4 7 6 1 7 3
Example – Size of the list is Not a Power of 2
1 2 3 4 5 6 7 8 9 10 11
Conquer
and 1 2 2 3 4 4 5 6 6 7 7
Merge
Merge algorith
1 2 3 4 5 6 7 8 9 10 11
m is
1 2 4 4 6 7 2 3 5 6 7 called

1 2 3 4 5 6 7 8 9 10 11

2 4 7 1 4 6 3 5 7 2 6

1 2 3 4 5 6 7 8 9 10 11

4 7 2 1 6 4 3 7 5 2 6

1 2 4 5 7 8

4 7 6 1 7 3
Merging Algorithm

14 23 45 98 6 33 42 67
Merging Algorithm

14 23 45 98 6 33 42 67

Merge
Merging Algorithm

14 23 45 98 6 33 42 67

Merge
Merging Algorithm

14 23 45 98 6 33 42 67

6 14

Merge
Merging Algorithm

14 23 45 98 6 33 42 67

6 14 23

Merge
Merging Algorithm

14 23 45 98 6 33 42 67

6 14 23 33

Merge
Merging Algorithm

14 23 45 98 6 33 42 67

6 14 23 33 42

Merge
Merging Algorithm

14 23 45 98 6 33 42 67

6 14 23 33 42 45

Merge
Merging Algorithm

14 23 45 98 6 33 42 67

6 14 23 33 42 45 67

Merge
Merging Algorithm

14 23 45 98 6 33 42 67

6 14 23 33 42 45 67 98

Merge
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 starts by testing the sorted data at the
middle of the sorted list

This
This determines
determines
whether
whether the the target
target is is
in
in the
the first
first half
half oror the
the
second
second halfhalf of
of the
the list.
list.
If
If it
it is
is in
in the
the first
first half,
half,
there
there is is no
no need
need to to
further
further check
check the
the
second
second half.half. If
If it
it is
is inin
the
the second
second half,
half, there
there
is
is no
no need
need to to further
further
check
check thethe first
first half.
half.
In
In other
other words,
words, we we
eliminate
eliminate half half the
the listlist
from
from further
further
consideration.
consideration.
SUB-ALGORITHMS
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 sub-algorithms.


Each sub-algorithm is in turn divided into smaller sub-algorithms.
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
involves a loop.
the algorithm appears
within the definition
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!
Simpler version of the same problem
Example: 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) int product=1;
return 1;
else while(numb>1) {
return numb*fac(numb- prod
1); uct *= 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!)
Iteration
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
Predict the output of following program. Consider the
following recursive function fun(x, y). What is the value of
fun(4, 3)

int fun(int x, int y)


{
if (x == 0)
return y;
return fun(x - 1, x + y);
}
a.13
b.12
c.9
d.10

View Answer
Answer: a
What does the following function print for n = 25?

void fun(int n) {
if (n == 0)
return;

printf("%d", n%2);
fun(n/2);
}

a.11001
b.10011
c.11111
d.00000

View Answer
Answer: b

You might also like