SlideShare ist ein Scribd-Unternehmen logo
1 von 56
8.1
88
AlgorithmsAlgorithms
Foundations of Computer Science © Cengage
Learning
8.2
 Define an algorithm and relate it to problem solving.
 Define three construct and describe their use in algorithms.
 Describe UML diagrams and pseudocode and how they are
used in algorithms.
 List basic algorithms and their applications.
 Describe the concept of sorting and understand the
mechanisms behind three primitive sorting algorithms.
 Describe the concept of searching and understand the
mechanisms behind two common searching algorithms.
 Define subalgorithms and their relations to algorithms.
 Distinguish between iterative and recursive algorithms
ObjectivesObjectives
After studying this chapter, the student should be ableAfter studying this chapter, the student should be able
to:to:
8.3
8-1 CONCEPT8-1 CONCEPT
In this section we informally define anIn this section we informally define an algorithmalgorithm andand
elaborate on the concept using an example.elaborate on the concept using an example.
8.4
Informal definition
An informal definition of an algorithm is:
Algorithm: a step-by-step method for solving a
problem or doing a task.
i
Figure 8.1 Informal definition of an algorithm used in a computer
8.5
Example
We want to develop an algorithm for finding the largest
integer among a list of positive integers. The algorithm
should find the largest integer among a list of any values (for
example 5, 1000, 10,000, 1,000,000). The algorithm should
be general and not depend on the number of integers.
To solve this problem, we need an intuitive approach.
First use a small number of integers (for example, five), then
extend the solution to any number of integers.
Figure 8.2 shows one way to solve this problem. We
call the algorithm FindLargest. Each algorithm has a name to
distinguish it from other algorithms. The algorithm receives
a list of five integers as input and gives the largest integer as
output.
8.6
Figure 8.2 Finding the largest integer among five integers
8.7
Defining actions
Figure 8.2 does not show what should be done in each step.
We can modify the figure to show more details.
Figure 8.3 Defining actions in FindLargest algorithm
8.8
Refinement
This algorithm needs refinement to be acceptable to the
programming community. There are two problems. First, the
action in the first step is different than those for the other
steps. Second, the wording is not the same in steps 2 to 5.
We can easily redefine the algorithm to remove these two
inconveniences by changing the wording in steps 2 to 5 to
“If the current integer is greater than Largest, set Largest to
the current integer.” The reason that the first step is different
than the other steps is because Largest is not initialized. If
we initialize Largest to −∞ (minus infinity), then the first
step can be the same as the other steps, so we add a new step,
calling it step 0 to show that it should be done before
processing any integers.
8.9 Figure 8.4 FindLargest refined
8.10
Generalization
Is it possible to generalize the algorithm? We want to find
the largest of n positive integers, where n can be 1000,
1,000,000, or more. Of course, we can follow Figure 8.4 and
repeat each step. But if we change the algorithm to a
program, then we need to actually type the actions for n
steps!
There is a better way to do this. We can tell the computer to
repeat the steps n times. We now include this feature in our
pictorial algorithm (Figure 8.5).
8.11
Figure 8.5 Generalization of FindLargest
8.12
8-2 THREE CONSTRUCTS8-2 THREE CONSTRUCTS
Computer scientists have definedComputer scientists have defined three constructsthree constructs for afor a
structured program or algorithm. The idea is that astructured program or algorithm. The idea is that a
program must be made of a combination of only theseprogram must be made of a combination of only these
three constructs:three constructs: sequencesequence,, decisiondecision (selection) and(selection) and
repetitionrepetition (Figure 8.6). It has been proven there is no(Figure 8.6). It has been proven there is no
need for any other constructs. Using only theseneed for any other constructs. Using only these
constructs makes a program or an algorithm easy toconstructs makes a program or an algorithm easy to
understand, debug or change.understand, debug or change.
8.13
Figure 8.6 Three constructs
8.14
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. This is called the decision (selection) construct.
8.15
Repetition
In some problems, the same sequence of instructions must be
repeated. We handle this with the repetition or loop
construct. Finding the largest integer among a set of integers
can use a construct of this kind.
8.16
8-3 ALGORITHM REPRESENTATION8-3 ALGORITHM REPRESENTATION
So far, we have used figures to convey the concept of anSo far, we have used figures to convey the concept of an
algorithm. During the last few decades, tools have beenalgorithm. During the last few decades, tools have been
designed for this purpose. Two of these tools,designed for this purpose. Two of these tools, UMLUML andand
pseudocodepseudocode, are presented here., are presented here.
8.17
UML
Unified Modeling Language (UML) is a pictorial
representation of an algorithm. It hides all the details of an
algorithm in an attempt to give the “big picture” and to show
how the algorithm flows from beginning to end. UML is
covered in detail in Appendix B. Here we show only how the
three constructs are represented using UML (Figure 8.7).
8.18
Figure 8.7 UML for three constructs
8.19
Pseudocode
Pseudocode is an English-language-like representation of an
algorithm. There is no standard for pseudocode—some
people use a lot of detail, others use less. Some use a code
that is close to English, while others use a syntax like the
Pascal programming language.
Pseudocode is covered in detail in Appendix C. Here we
show only how the three constructs can be represented by
pseudocode (Figure 8.8).
8.20
Figure 8.8 Pseudocode for three constructs
8.21
Example 8.1
Write an algorithm in pseudocode that finds the sum of twoWrite an algorithm in pseudocode that finds the sum of two
integers.integers.
8.22
Example 8.2
Write an algorithm to change a numeric grade to a pass/no passWrite an algorithm to change a numeric grade to a pass/no pass
grade.grade.
8.23
Example 8.3
Write an algorithm to change a numeric grade (integer) to a letterWrite an algorithm to change a numeric grade (integer) to a letter
grade.grade.
8.24
Example 8.4
Write an algorithm to find the largest of a set of integers. We doWrite an algorithm to find the largest of a set of integers. We do
not know the number of integers.not know the number of integers.
8.25
Example 8.5
Write an algorithm to find the largest of the first 1000 integers inWrite an algorithm to find the largest of the first 1000 integers in
a set of integers.a set of integers.
8.26
8-4 A MORE FORMAL DEFINITION8-4 A MORE FORMAL DEFINITION
Now that we have discussed the concept of an algorithmNow that we have discussed the concept of an algorithm
and shown its representation, here is a more formaland shown its representation, here is a more formal
definition.definition.
Algorithm:
An ordered set of unambiguous steps that produces a
result and terminates in a finite time.
i
8.27
Ordered set
An algorithm must be a well-defined, ordered set of
instructions.
Unambiguous steps
Each step in an algorithm must be clearly and
unambiguously defined. If one step is to add two integers,
we must define both “integers” as well as the “add”
operation: we cannot for example use the same symbol to
mean addition in one place and multiplication somewhere
else.
8.28
Produce a result
An algorithm must produce a result, otherwise it is useless.
The result can be data returned to the calling algorithm, or
some other effect (for example, printing).
Terminate in a finite time
An algorithm must terminate (halt). If it does not (that is, it
has an infinite loop), we have not created an algorithm. In
Chapter 17 we will discuss solvable and unsolvable
problems, and we will see that a solvable problem has a
solution in the form of an algorithm that terminates.
8.29
8-5 BASIC ALGORITHMS8-5 BASIC ALGORITHMS
Several algorithms are used in computer science soSeveral algorithms are used in computer science so
prevalently that they are considered “basic”. We discussprevalently that they are considered “basic”. We discuss
the most common here. This discussion is very general:the most common here. This discussion is very general:
implementation depends on the language.implementation depends on the language.
8.30
Summation
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 the add operator in a loop (Figure 8.9).
A summation algorithm has three logical parts:
1. Initialization of the sum 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.
8.31
Figure 8.9 Summation algorithm
8.32
Product
Another common algorithm is finding the product of a list of
integers. The solution is simple: use the multiplication
operator in a loop (Figure 8.10).
A product algorithm has three logical parts:
1. Initialization of the product 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.
8.33
Figure 8.10 Product algorithm
8.34
Smallest and largest
We discussed the algorithm for finding the largest among a
list of integers at the beginning of this chapter. The idea was
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.
Finding the smallest integer among a list of integers is
similar, with two minor differences. First, we use a decision
construct to find the smaller of two integers. Second, we
initialize with a very large integer instead of a very small
one.
8.35
Sorting
One of the most common applications in computer science is
sorting, which is the process by which data is arranged
according to its values. 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. These three
sorting algorithms are the foundation of faster sorting
algorithms used in computer science today.
8.36
Selection sorts
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.
Figure 8.11 Selection sort
8.37
Figure 8.12 Example of selection sort
8.38
Figure 8.13 Selection sort algorithm
8.39
Bubble sorts
In the bubble sort method, the list to be sorted is also divided
into two sublists—sorted and unsorted. The smallest element
is bubbled up from the unsorted sublist and moved to the
sorted sublist. After the smallest element has been moved to
the sorted list, the wall moves one element ahead.
Figure 8.14 Bubble sort
8.40
Figure 8.15 Example of bubble sort
8.41
Insertion sorts
The insertion sort algorithm is one of the most common
sorting techniques, and it is often used by card players. Each
card a player picks up is inserted into the proper place in
their hand of cards to maintain a particular sequence.
Figure 8.16 Insertion sort
8.42
Figure 8.17 Example of insertion sort
8.43
Searching
Another common algorithm in computer science is
searching, which is the process of finding the location of a
target among a list of objects. In the case of a list, searching
means that given a value, we want to find the location of the
first element in the list that contains that value. 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.
8.44
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 other cases, the best
approach is to first sort the list and then search it using the
binary search discussed later.
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.
8.45
Figure 8.18 An example of a sequential search
8.46
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.
A binary search starts by testing the data in the
element at the middle of the 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.
8.47
Figure 8.19 Example of a binary search
8.48
8-6 SUBALGORITHMS8-6 SUBALGORITHMS
The three programming constructs described in SectionThe three programming constructs described in Section
8.2 allow us to create an algorithm for any solvable8.2 allow us to create an algorithm for any solvable
problem. The principles of structured programming,problem. The principles of structured programming,
however, require that an algorithm be broken into smallhowever, require that an algorithm be broken into small
units calledunits called subalgorithmssubalgorithms. Each subalgorithm is in. Each subalgorithm is in
turn divided into smaller subalgorithms. A goodturn divided into smaller subalgorithms. A good
example is the algorithm for the selection sort in Figureexample is the algorithm for the selection sort in Figure
8.13.8.13.
8.49 Figure 8.20 Concept of a subalgorithm
8.50
Structure chart
Another tool programmers use is the structure chart. A
structure chart is a high level design tool that shows the
relationship between algorithms and subalgorithms. It is used
mainly at the design level rather than at the programming
level. We briefly discuss the structure chart in Appendix D.
8.51
8-7 RECURSION8-7 RECURSION
In general, there are two approaches to writingIn general, there are two approaches to writing
algorithms for solving a problem. One usesalgorithms for solving a problem. One uses iterationiteration,,
the other usesthe other uses recursionrecursion. Recursion is a process in. Recursion is a process in
which an algorithm calls itself.which an algorithm calls itself.
8.52
Iterative definition
To study a simple example, consider the calculation of a
factorial. The factorial of a integer is the product of the
integral values from 1 to the integer. The definition is
iterative (Figure 8.21). An algorithm is iterative whenever
the definition does not involve the algorithm itself.
Figure 8.21 Iterative definition of factorial
8.53
Recursive definition
An algorithm is defined recursively whenever the algorithm
appears within the definition itself. For example, the factorial
function can be defined recursively as shown in Figure 8.22.
Figure 8.22 Recursive definition of factorial
8.54
Figure 8.23 Tracing the recursive solution to the factorial problem
8.55
Iterative solution
This solution usually involves a loop.
8.56
Recursive solution
The recursive solution does not need a loop, as the recursion
concept itself involves repetition.

Weitere ähnliche Inhalte

Was ist angesagt?

Data Structure
Data StructureData Structure
Data Structure
sheraz1
 

Was ist angesagt? (19)

04 a ch03_programacion
04 a ch03_programacion04 a ch03_programacion
04 a ch03_programacion
 
Numerical analysis using Scilab: Numerical stability and conditioning
Numerical analysis using Scilab: Numerical stability and conditioningNumerical analysis using Scilab: Numerical stability and conditioning
Numerical analysis using Scilab: Numerical stability and conditioning
 
Savitch Ch 07
Savitch Ch 07Savitch Ch 07
Savitch Ch 07
 
Savitch Ch 07
Savitch Ch 07Savitch Ch 07
Savitch Ch 07
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Numerical analysis using Scilab: Solving nonlinear equations
Numerical analysis using Scilab: Solving nonlinear equationsNumerical analysis using Scilab: Solving nonlinear equations
Numerical analysis using Scilab: Solving nonlinear equations
 
Design and analysis of algorithms
Design and analysis of algorithmsDesign and analysis of algorithms
Design and analysis of algorithms
 
Numerical analysis using Scilab: Error analysis and propagation
Numerical analysis using Scilab: Error analysis and propagationNumerical analysis using Scilab: Error analysis and propagation
Numerical analysis using Scilab: Error analysis and propagation
 
Data Structure
Data StructureData Structure
Data Structure
 
Algorithm and pseudocode conventions
Algorithm and pseudocode conventionsAlgorithm and pseudocode conventions
Algorithm and pseudocode conventions
 
Design & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesDesign & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture Notes
 
NACA Regula Falsi Method
 NACA Regula Falsi Method NACA Regula Falsi Method
NACA Regula Falsi Method
 
Savitch ch 07
Savitch ch 07Savitch ch 07
Savitch ch 07
 
Pointers In C
Pointers In CPointers In C
Pointers In C
 
Functional Effects - Part 2
Functional Effects - Part 2Functional Effects - Part 2
Functional Effects - Part 2
 
Unit 1 dsa
Unit 1 dsaUnit 1 dsa
Unit 1 dsa
 
Ch08
Ch08Ch08
Ch08
 
Algorithm Design Presentation
Algorithm Design PresentationAlgorithm Design Presentation
Algorithm Design Presentation
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)
 

Andere mochten auch

Training Sandvik Coromant
Training Sandvik CoromantTraining Sandvik Coromant
Training Sandvik Coromant
ttehnologie
 
Pcy jan06 2011_website_chinese
Pcy jan06 2011_website_chinesePcy jan06 2011_website_chinese
Pcy jan06 2011_website_chinese
Prophecy Corp
 
Presentation Demo Metal 2012 (english)
Presentation Demo Metal 2012 (english)Presentation Demo Metal 2012 (english)
Presentation Demo Metal 2012 (english)
ttehnologie
 
Rolls royce 2010
Rolls royce 2010Rolls royce 2010
Rolls royce 2010
Pac526
 
2007 Q1 interim financial statements
2007 Q1 interim financial statements2007 Q1 interim financial statements
2007 Q1 interim financial statements
Prophecy Corp
 
SNSモテ系女子・男子の特徴
SNSモテ系女子・男子の特徴SNSモテ系女子・男子の特徴
SNSモテ系女子・男子の特徴
masspy-staff
 
Chief Rascal Speaks for 8 mins, 88 seconds
Chief Rascal Speaks for 8 mins, 88 secondsChief Rascal Speaks for 8 mins, 88 seconds
Chief Rascal Speaks for 8 mins, 88 seconds
mortybarnett
 
2007 Q3 interim financial statements
2007 Q3 interim financial statements2007 Q3 interim financial statements
2007 Q3 interim financial statements
Prophecy Corp
 
Q1 md&a & interim financial statements (pre merger)
Q1 md&a & interim financial statements (pre merger)Q1 md&a & interim financial statements (pre merger)
Q1 md&a & interim financial statements (pre merger)
Prophecy Corp
 
2007 Q2 interim financial statements
2007 Q2 interim financial statements2007 Q2 interim financial statements
2007 Q2 interim financial statements
Prophecy Corp
 
Rpt bm tahun 2
Rpt bm tahun 2Rpt bm tahun 2
Rpt bm tahun 2
Shika Nara
 
2009 Q1 interim financial statements
2009 Q1 interim financial statements2009 Q1 interim financial statements
2009 Q1 interim financial statements
Prophecy Corp
 

Andere mochten auch (20)

Training Sandvik Coromant
Training Sandvik CoromantTraining Sandvik Coromant
Training Sandvik Coromant
 
Soalan bm 2 sem 1 2013
Soalan bm 2 sem 1 2013Soalan bm 2 sem 1 2013
Soalan bm 2 sem 1 2013
 
Pcy jan06 2011_website_chinese
Pcy jan06 2011_website_chinesePcy jan06 2011_website_chinese
Pcy jan06 2011_website_chinese
 
Presentation Demo Metal 2012 (english)
Presentation Demo Metal 2012 (english)Presentation Demo Metal 2012 (english)
Presentation Demo Metal 2012 (english)
 
Love quotes
Love quotesLove quotes
Love quotes
 
Rolls royce 2010
Rolls royce 2010Rolls royce 2010
Rolls royce 2010
 
2007 annual md&a
2007 annual md&a2007 annual md&a
2007 annual md&a
 
2007 Q1 interim financial statements
2007 Q1 interim financial statements2007 Q1 interim financial statements
2007 Q1 interim financial statements
 
Presentation Demo Metal 2013
Presentation Demo Metal 2013Presentation Demo Metal 2013
Presentation Demo Metal 2013
 
SNSモテ系女子・男子の特徴
SNSモテ系女子・男子の特徴SNSモテ系女子・男子の特徴
SNSモテ系女子・男子の特徴
 
Chief Rascal Speaks for 8 mins, 88 seconds
Chief Rascal Speaks for 8 mins, 88 secondsChief Rascal Speaks for 8 mins, 88 seconds
Chief Rascal Speaks for 8 mins, 88 seconds
 
2007 Q3 interim financial statements
2007 Q3 interim financial statements2007 Q3 interim financial statements
2007 Q3 interim financial statements
 
Jane Carr on the 'Handmade at Fortnum's' Exhibition she curated, from the Hid...
Jane Carr on the 'Handmade at Fortnum's' Exhibition she curated, from the Hid...Jane Carr on the 'Handmade at Fortnum's' Exhibition she curated, from the Hid...
Jane Carr on the 'Handmade at Fortnum's' Exhibition she curated, from the Hid...
 
Why Make An App? (Retailers)
Why Make An App? (Retailers)Why Make An App? (Retailers)
Why Make An App? (Retailers)
 
Q1 md&a & interim financial statements (pre merger)
Q1 md&a & interim financial statements (pre merger)Q1 md&a & interim financial statements (pre merger)
Q1 md&a & interim financial statements (pre merger)
 
Prueba de ms excel
Prueba de ms excelPrueba de ms excel
Prueba de ms excel
 
Disinvestment
DisinvestmentDisinvestment
Disinvestment
 
2007 Q2 interim financial statements
2007 Q2 interim financial statements2007 Q2 interim financial statements
2007 Q2 interim financial statements
 
Rpt bm tahun 2
Rpt bm tahun 2Rpt bm tahun 2
Rpt bm tahun 2
 
2009 Q1 interim financial statements
2009 Q1 interim financial statements2009 Q1 interim financial statements
2009 Q1 interim financial statements
 

Ähnlich wie Chapitre 08

9 big o-notation
9 big o-notation9 big o-notation
9 big o-notation
irdginfo
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
karymadelaneyrenne19
 

Ähnlich wie Chapitre 08 (20)

Algoritmos
AlgoritmosAlgoritmos
Algoritmos
 
Chap08
Chap08Chap08
Chap08
 
CSI_06.pptx
CSI_06.pptxCSI_06.pptx
CSI_06.pptx
 
DA lecture 3.pptx
DA lecture 3.pptxDA lecture 3.pptx
DA lecture 3.pptx
 
Lect 3-4 Zaheer Abbas
Lect 3-4 Zaheer AbbasLect 3-4 Zaheer Abbas
Lect 3-4 Zaheer Abbas
 
What is algorithm
What is algorithmWhat is algorithm
What is algorithm
 
Unit 1-problem solving with algorithm
Unit 1-problem solving with algorithmUnit 1-problem solving with algorithm
Unit 1-problem solving with algorithm
 
9 big o-notation
9 big o-notation9 big o-notation
9 big o-notation
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptx
 
Discrete structure ch 3 short question's
Discrete structure ch 3 short question'sDiscrete structure ch 3 short question's
Discrete structure ch 3 short question's
 
Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Intro to programing with java-lecture 3
Intro to programing with java-lecture 3
 
Ecs 10 programming assignment 4 loopapalooza
Ecs 10 programming assignment 4   loopapaloozaEcs 10 programming assignment 4   loopapalooza
Ecs 10 programming assignment 4 loopapalooza
 
A Novel Methodology to Implement Optimization Algorithms in Machine Learning
A Novel Methodology to Implement Optimization Algorithms in Machine LearningA Novel Methodology to Implement Optimization Algorithms in Machine Learning
A Novel Methodology to Implement Optimization Algorithms in Machine Learning
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
chapter 1
chapter 1chapter 1
chapter 1
 
Chapter 1 Data structure.pptx
Chapter 1 Data structure.pptxChapter 1 Data structure.pptx
Chapter 1 Data structure.pptx
 
final
finalfinal
final
 
Implementing Merge Sort
Implementing Merge SortImplementing Merge Sort
Implementing Merge Sort
 
Data Structures and Algorithms Unit 01
Data Structures and Algorithms Unit 01Data Structures and Algorithms Unit 01
Data Structures and Algorithms Unit 01
 
GENETIC ALGORITHM FOR FUNCTION APPROXIMATION: AN EXPERIMENTAL INVESTIGATION
GENETIC ALGORITHM FOR FUNCTION APPROXIMATION: AN EXPERIMENTAL INVESTIGATIONGENETIC ALGORITHM FOR FUNCTION APPROXIMATION: AN EXPERIMENTAL INVESTIGATION
GENETIC ALGORITHM FOR FUNCTION APPROXIMATION: AN EXPERIMENTAL INVESTIGATION
 

Kürzlich hochgeladen

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

Chapitre 08

  • 2. 8.2  Define an algorithm and relate it to problem solving.  Define three construct and describe their use in algorithms.  Describe UML diagrams and pseudocode and how they are used in algorithms.  List basic algorithms and their applications.  Describe the concept of sorting and understand the mechanisms behind three primitive sorting algorithms.  Describe the concept of searching and understand the mechanisms behind two common searching algorithms.  Define subalgorithms and their relations to algorithms.  Distinguish between iterative and recursive algorithms ObjectivesObjectives After studying this chapter, the student should be ableAfter studying this chapter, the student should be able to:to:
  • 3. 8.3 8-1 CONCEPT8-1 CONCEPT In this section we informally define anIn this section we informally define an algorithmalgorithm andand elaborate on the concept using an example.elaborate on the concept using an example.
  • 4. 8.4 Informal definition An informal definition of an algorithm is: Algorithm: a step-by-step method for solving a problem or doing a task. i Figure 8.1 Informal definition of an algorithm used in a computer
  • 5. 8.5 Example We want to develop an algorithm for finding the largest integer among a list of positive integers. The algorithm should find the largest integer among a list of any values (for example 5, 1000, 10,000, 1,000,000). The algorithm should be general and not depend on the number of integers. To solve this problem, we need an intuitive approach. First use a small number of integers (for example, five), then extend the solution to any number of integers. Figure 8.2 shows one way to solve this problem. We call the algorithm FindLargest. Each algorithm has a name to distinguish it from other algorithms. The algorithm receives a list of five integers as input and gives the largest integer as output.
  • 6. 8.6 Figure 8.2 Finding the largest integer among five integers
  • 7. 8.7 Defining actions Figure 8.2 does not show what should be done in each step. We can modify the figure to show more details. Figure 8.3 Defining actions in FindLargest algorithm
  • 8. 8.8 Refinement This algorithm needs refinement to be acceptable to the programming community. There are two problems. First, the action in the first step is different than those for the other steps. Second, the wording is not the same in steps 2 to 5. We can easily redefine the algorithm to remove these two inconveniences by changing the wording in steps 2 to 5 to “If the current integer is greater than Largest, set Largest to the current integer.” The reason that the first step is different than the other steps is because Largest is not initialized. If we initialize Largest to −∞ (minus infinity), then the first step can be the same as the other steps, so we add a new step, calling it step 0 to show that it should be done before processing any integers.
  • 9. 8.9 Figure 8.4 FindLargest refined
  • 10. 8.10 Generalization Is it possible to generalize the algorithm? We want to find the largest of n positive integers, where n can be 1000, 1,000,000, or more. Of course, we can follow Figure 8.4 and repeat each step. But if we change the algorithm to a program, then we need to actually type the actions for n steps! There is a better way to do this. We can tell the computer to repeat the steps n times. We now include this feature in our pictorial algorithm (Figure 8.5).
  • 12. 8.12 8-2 THREE CONSTRUCTS8-2 THREE CONSTRUCTS Computer scientists have definedComputer scientists have defined three constructsthree constructs for afor a structured program or algorithm. The idea is that astructured program or algorithm. The idea is that a program must be made of a combination of only theseprogram must be made of a combination of only these three constructs:three constructs: sequencesequence,, decisiondecision (selection) and(selection) and repetitionrepetition (Figure 8.6). It has been proven there is no(Figure 8.6). It has been proven there is no need for any other constructs. Using only theseneed for any other constructs. Using only these constructs makes a program or an algorithm easy toconstructs makes a program or an algorithm easy to understand, debug or change.understand, debug or change.
  • 13. 8.13 Figure 8.6 Three constructs
  • 14. 8.14 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. This is called the decision (selection) construct.
  • 15. 8.15 Repetition In some problems, the same sequence of instructions must be repeated. We handle this with the repetition or loop construct. Finding the largest integer among a set of integers can use a construct of this kind.
  • 16. 8.16 8-3 ALGORITHM REPRESENTATION8-3 ALGORITHM REPRESENTATION So far, we have used figures to convey the concept of anSo far, we have used figures to convey the concept of an algorithm. During the last few decades, tools have beenalgorithm. During the last few decades, tools have been designed for this purpose. Two of these tools,designed for this purpose. Two of these tools, UMLUML andand pseudocodepseudocode, are presented here., are presented here.
  • 17. 8.17 UML Unified Modeling Language (UML) is a pictorial representation of an algorithm. It hides all the details of an algorithm in an attempt to give the “big picture” and to show how the algorithm flows from beginning to end. UML is covered in detail in Appendix B. Here we show only how the three constructs are represented using UML (Figure 8.7).
  • 18. 8.18 Figure 8.7 UML for three constructs
  • 19. 8.19 Pseudocode Pseudocode is an English-language-like representation of an algorithm. There is no standard for pseudocode—some people use a lot of detail, others use less. Some use a code that is close to English, while others use a syntax like the Pascal programming language. Pseudocode is covered in detail in Appendix C. Here we show only how the three constructs can be represented by pseudocode (Figure 8.8).
  • 20. 8.20 Figure 8.8 Pseudocode for three constructs
  • 21. 8.21 Example 8.1 Write an algorithm in pseudocode that finds the sum of twoWrite an algorithm in pseudocode that finds the sum of two integers.integers.
  • 22. 8.22 Example 8.2 Write an algorithm to change a numeric grade to a pass/no passWrite an algorithm to change a numeric grade to a pass/no pass grade.grade.
  • 23. 8.23 Example 8.3 Write an algorithm to change a numeric grade (integer) to a letterWrite an algorithm to change a numeric grade (integer) to a letter grade.grade.
  • 24. 8.24 Example 8.4 Write an algorithm to find the largest of a set of integers. We doWrite an algorithm to find the largest of a set of integers. We do not know the number of integers.not know the number of integers.
  • 25. 8.25 Example 8.5 Write an algorithm to find the largest of the first 1000 integers inWrite an algorithm to find the largest of the first 1000 integers in a set of integers.a set of integers.
  • 26. 8.26 8-4 A MORE FORMAL DEFINITION8-4 A MORE FORMAL DEFINITION Now that we have discussed the concept of an algorithmNow that we have discussed the concept of an algorithm and shown its representation, here is a more formaland shown its representation, here is a more formal definition.definition. Algorithm: An ordered set of unambiguous steps that produces a result and terminates in a finite time. i
  • 27. 8.27 Ordered set An algorithm must be a well-defined, ordered set of instructions. Unambiguous steps Each step in an algorithm must be clearly and unambiguously defined. If one step is to add two integers, we must define both “integers” as well as the “add” operation: we cannot for example use the same symbol to mean addition in one place and multiplication somewhere else.
  • 28. 8.28 Produce a result An algorithm must produce a result, otherwise it is useless. The result can be data returned to the calling algorithm, or some other effect (for example, printing). Terminate in a finite time An algorithm must terminate (halt). If it does not (that is, it has an infinite loop), we have not created an algorithm. In Chapter 17 we will discuss solvable and unsolvable problems, and we will see that a solvable problem has a solution in the form of an algorithm that terminates.
  • 29. 8.29 8-5 BASIC ALGORITHMS8-5 BASIC ALGORITHMS Several algorithms are used in computer science soSeveral algorithms are used in computer science so prevalently that they are considered “basic”. We discussprevalently that they are considered “basic”. We discuss the most common here. This discussion is very general:the most common here. This discussion is very general: implementation depends on the language.implementation depends on the language.
  • 30. 8.30 Summation 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 the add operator in a loop (Figure 8.9). A summation algorithm has three logical parts: 1. Initialization of the sum 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.
  • 32. 8.32 Product Another common algorithm is finding the product of a list of integers. The solution is simple: use the multiplication operator in a loop (Figure 8.10). A product algorithm has three logical parts: 1. Initialization of the product 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.
  • 34. 8.34 Smallest and largest We discussed the algorithm for finding the largest among a list of integers at the beginning of this chapter. The idea was 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. Finding the smallest integer among a list of integers is similar, with two minor differences. First, we use a decision construct to find the smaller of two integers. Second, we initialize with a very large integer instead of a very small one.
  • 35. 8.35 Sorting One of the most common applications in computer science is sorting, which is the process by which data is arranged according to its values. 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. These three sorting algorithms are the foundation of faster sorting algorithms used in computer science today.
  • 36. 8.36 Selection sorts 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. Figure 8.11 Selection sort
  • 37. 8.37 Figure 8.12 Example of selection sort
  • 38. 8.38 Figure 8.13 Selection sort algorithm
  • 39. 8.39 Bubble sorts In the bubble sort method, the list to be sorted is also divided into two sublists—sorted and unsorted. The smallest element is bubbled up from the unsorted sublist and moved to the sorted sublist. After the smallest element has been moved to the sorted list, the wall moves one element ahead. Figure 8.14 Bubble sort
  • 40. 8.40 Figure 8.15 Example of bubble sort
  • 41. 8.41 Insertion sorts The insertion sort algorithm is one of the most common sorting techniques, and it is often used by card players. Each card a player picks up is inserted into the proper place in their hand of cards to maintain a particular sequence. Figure 8.16 Insertion sort
  • 42. 8.42 Figure 8.17 Example of insertion sort
  • 43. 8.43 Searching Another common algorithm in computer science is searching, which is the process of finding the location of a target among a list of objects. In the case of a list, searching means that given a value, we want to find the location of the first element in the list that contains that value. 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.
  • 44. 8.44 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 other cases, the best approach is to first sort the list and then search it using the binary search discussed later. 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.
  • 45. 8.45 Figure 8.18 An example of a sequential search
  • 46. 8.46 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. A binary search starts by testing the data in the element at the middle of the 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.
  • 47. 8.47 Figure 8.19 Example of a binary search
  • 48. 8.48 8-6 SUBALGORITHMS8-6 SUBALGORITHMS The three programming constructs described in SectionThe three programming constructs described in Section 8.2 allow us to create an algorithm for any solvable8.2 allow us to create an algorithm for any solvable problem. The principles of structured programming,problem. The principles of structured programming, however, require that an algorithm be broken into smallhowever, require that an algorithm be broken into small units calledunits called subalgorithmssubalgorithms. Each subalgorithm is in. Each subalgorithm is in turn divided into smaller subalgorithms. A goodturn divided into smaller subalgorithms. A good example is the algorithm for the selection sort in Figureexample is the algorithm for the selection sort in Figure 8.13.8.13.
  • 49. 8.49 Figure 8.20 Concept of a subalgorithm
  • 50. 8.50 Structure chart Another tool programmers use is the structure chart. A structure chart is a high level design tool that shows the relationship between algorithms and subalgorithms. It is used mainly at the design level rather than at the programming level. We briefly discuss the structure chart in Appendix D.
  • 51. 8.51 8-7 RECURSION8-7 RECURSION In general, there are two approaches to writingIn general, there are two approaches to writing algorithms for solving a problem. One usesalgorithms for solving a problem. One uses iterationiteration,, the other usesthe other uses recursionrecursion. Recursion is a process in. Recursion is a process in which an algorithm calls itself.which an algorithm calls itself.
  • 52. 8.52 Iterative definition To study a simple example, consider the calculation of a factorial. The factorial of a integer is the product of the integral values from 1 to the integer. The definition is iterative (Figure 8.21). An algorithm is iterative whenever the definition does not involve the algorithm itself. Figure 8.21 Iterative definition of factorial
  • 53. 8.53 Recursive definition An algorithm is defined recursively whenever the algorithm appears within the definition itself. For example, the factorial function can be defined recursively as shown in Figure 8.22. Figure 8.22 Recursive definition of factorial
  • 54. 8.54 Figure 8.23 Tracing the recursive solution to the factorial problem
  • 55. 8.55 Iterative solution This solution usually involves a loop.
  • 56. 8.56 Recursive solution The recursive solution does not need a loop, as the recursion concept itself involves repetition.