SlideShare a Scribd company logo
1 of 22
Types of Algorithms
CS 206
Aimhee Santos
Algorithm classification
• Algorithms that use a similar problem-solving
approach can be grouped together
• This classification scheme is neither exhaustive
nor disjoint
• The purpose is not to be able to classify an
algorithm as one type or another, but to highlight
the various ways in which a problem can be
attacked
A short list of categories
• Algorithm types we will consider include:
– Simple recursive algorithms
– Backtracking algorithms
– Divide and conquer algorithms
– Dynamic programming algorithms
– Greedy algorithms
– Branch and bound algorithms
– Brute force algorithms
– Randomized algorithms
Simple recursive algorithms I
• A simple recursive algorithm:
– Solves the base cases directly
– Recurs with a simpler subproblem
– Does some extra work to convert the solution to the
simpler subproblem into a solution to the given
problem
• I call these “simple” because several of the other
algorithm types are inherently recursive
Example recursive algorithms
• To count the number of elements in a list:
– If the list is empty, return zero; otherwise,
– Step past the first element, and count the remaining
elements in the list
– Add one to the result
• To test if a value occurs in a list:
– If the list is empty, return false; otherwise,
– If the first thing in the list is the given value, return
true; otherwise
– Step past the first element, and test whether the value
occurs in the remainder of the list
Backtracking algorithms
• Backtracking algorithms are based on a depth-first
recursive search
• A backtracking algorithm:
– Tests to see if a solution has been found, and if so,
returns it; otherwise
– For each choice that can be made at this point,
• Make that choice
• Recur
• If the recursion returns a solution, return it
– If no choices remain, return failure
Example backtracking algorithm
• To color a map with no more than four colors:
– color(Country n)
• If all countries have been colored (n > number of
countries) return success; otherwise,
• For each color c of four colors,
– If country n is not adjacent to a country that has
been colored c
» Color country n with color c
» recursivly color country n+1
» If successful, return success
• Return failure (if loop exits)
Divide and Conquer
• A divide and conquer algorithm consists of two
parts:
– Divide the problem into smaller subproblems of the
same type, and solve these subproblems recursively
– Combine the solutions to the subproblems into a
solution to the original problem
• Traditionally, an algorithm is only called divide
and conquer if it contains two or more recursive
calls
Examples
• Quicksort:
– Partition the array into two parts, and quicksort each
of the parts
– No additional work is required to combine the two
sorted parts
• Mergesort:
– Cut the array in half, and mergesort each half
– Combine the two sorted arrays into a single sorted
array by merging them
Binary tree lookup
• Here’s how to look up something in a sorted
binary tree:
– Compare the key to the value in the root
• If the two values are equal, report success
• If the key is less, search the left subtree
• If the key is greater, search the right subtree
• This is not a divide and conquer algorithm
because, although there are two recursive calls,
only one is used at each level of the recursion
Fibonacci numbers
• To find the nth Fibonacci number:
– If n is zero or one, return one; otherwise,
– Compute fibonacci(n-1) and fibonacci(n-2)
– Return the sum of these two numbers
• This is an expensive algorithm
– It requires O(fibonacci(n)) time
– This is equivalent to exponential time, that is, O(2n)
Dynamic programming algorithms
• A dynamic programming algorithm remembers past results
and uses them to find new results
• Dynamic programming is generally used for optimization
problems
– Multiple solutions exist, need to find the “best” one
– Requires “optimal substructure” and “overlapping subproblems”
• Optimal substructure: Optimal solution contains optimal
solutions to subproblems
• Overlapping subproblems: Solutions to subproblems can be
stored and reused in a bottom-up fashion
• This differs from Divide and Conquer, where subproblems
generally need not overlap
Fibonacci numbers again
• To find the nth Fibonacci number:
– If n is zero or one, return one; otherwise,
– Compute, or look up in a table, fibonacci(n-1) and
fibonacci(n-2)
– Find the sum of these two numbers
– Store the result in a table and return it
• Since finding the nth Fibonacci number involves
finding all smaller Fibonacci numbers, the second
recursive call has little work to do
• The table may be preserved and used again later
Greedy algorithms
• An optimization problem is one in which you want
to find, not just a solution, but the best solution
• A “greedy algorithm” sometimes works well for
optimization problems
• A greedy algorithm works in phases: At each
phase:
– You take the best you can get right now, without regard
for future consequences
– You hope that by choosing a local optimum at each
step, you will end up at a global optimum
Example: Counting money
• Suppose you want to count out a certain amount of money,
using the fewest possible bills and coins
• A greedy algorithm would do this would be:
At each step, take the largest possible bill or coin that does
not overshoot
– Example: To make $6.39, you can choose:
• a $5 bill
• a $1 bill, to make $6
• a 25¢ coin, to make $6.25
• A 10¢ coin, to make $6.35
• four 1¢ coins, to make $6.39
• For US money, the greedy algorithm always gives the
optimum solution
A failure of the greedy algorithm
• In some (fictional) monetary system, “krons” come
in 1 kron, 7 kron, and 10 kron coins
• Using a greedy algorithm to count out 15 krons,
you would get
– A 10 kron piece
– Five 1 kron pieces, for a total of 15 krons
– This requires six coins
• A better solution would be to use two 7 kron pieces
and one 1 kron piece
– This only requires three coins
• The greedy algorithm results in a solution, but not
in an optimal solution
Branch and bound algorithms
• Branch and bound algorithms are generally used for
optimization problems
– As the algorithm progresses, a tree of subproblems is formed
– The original problem is considered the “root problem”
– A method is used to construct an upper and lower bound for a
given problem
– At each node, apply the bounding methods
• If the bounds match, it is deemed a feasible solution to that
particular subproblem
• If bounds do not match, partition the problem represented by
that node, and make the two subproblems into children nodes
– Continue, using the best known feasible solution to trim sections of
the tree, until all nodes have been solved or trimmed
Example branch and bound algorithm
• Travelling salesman problem: A salesman has to
visit each of n cities (at least) once each, and
wants to minimize total distance travelled
– Consider the root problem to be the problem of finding
the shortest route through a set of cities visiting each
city once
– Split the node into two child problems:
• Shortest route visiting city A first
• Shortest route not visiting city A first
– Continue subdividing similarly as the tree grows
Brute force algorithm
• A brute force algorithm simply tries all
possibilities until a satisfactory solution is found
– Such an algorithm can be:
• Optimizing: Find the best solution. This may require
finding all solutions, or if a value for the best
solution is known, it may stop when any best
solution is found
– Example: Finding the best path for a travelling salesman
• Satisficing: Stop as soon as a solution is found that
is good enough
– Example: Finding a travelling salesman path that is within
10% of optimal
Improving brute force algorithms
• Often, brute force algorithms require exponential
time
• Various heuristics and optimizations can be used
– Heuristic: A “rule of thumb” that helps you decide
which possibilities to look at first
– Optimization: In this case, a way to eliminate certain
possibilites without fully exploring them
Randomized algorithms
• A randomized algorithm uses a random number at
least once during the computation to make a
decision
– Example: In Quicksort, using a random number to
choose a pivot
– Example: Trying to factor a large prime by choosing
random numbers as possible divisors
Learn
ALGORITHMS

More Related Content

What's hot

Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsMohamed Loey
 
What is an algorithm?
What is an algorithm?What is an algorithm?
What is an algorithm?Angela DeHart
 
Artificial Intelligence Searching Techniques
Artificial Intelligence Searching TechniquesArtificial Intelligence Searching Techniques
Artificial Intelligence Searching TechniquesDr. C.V. Suresh Babu
 
Uninformed search /Blind search in AI
Uninformed search /Blind search in AIUninformed search /Blind search in AI
Uninformed search /Blind search in AIKirti Verma
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysissumitbardhan
 
Algorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms IAlgorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms IMohamed Loey
 
Data Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxData Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxEllenGrace9
 
Heuristic Search Techniques {Artificial Intelligence}
Heuristic Search Techniques {Artificial Intelligence}Heuristic Search Techniques {Artificial Intelligence}
Heuristic Search Techniques {Artificial Intelligence}FellowBuddy.com
 
Our presentation on algorithm design
Our presentation on algorithm designOur presentation on algorithm design
Our presentation on algorithm designNahid Hasan
 
The n Queen Problem
The n Queen ProblemThe n Queen Problem
The n Queen ProblemSukrit Gupta
 
Finite automata-for-lexical-analysis
Finite automata-for-lexical-analysisFinite automata-for-lexical-analysis
Finite automata-for-lexical-analysisDattatray Gandhmal
 

What's hot (20)

Algorithm
AlgorithmAlgorithm
Algorithm
 
Sorting
SortingSorting
Sorting
 
Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to Algorithms
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
What is an algorithm?
What is an algorithm?What is an algorithm?
What is an algorithm?
 
Artificial Intelligence Searching Techniques
Artificial Intelligence Searching TechniquesArtificial Intelligence Searching Techniques
Artificial Intelligence Searching Techniques
 
Uninformed search /Blind search in AI
Uninformed search /Blind search in AIUninformed search /Blind search in AI
Uninformed search /Blind search in AI
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
COMPILER DESIGN
COMPILER DESIGNCOMPILER DESIGN
COMPILER DESIGN
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Algorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms IAlgorithms Lecture 2: Analysis of Algorithms I
Algorithms Lecture 2: Analysis of Algorithms I
 
Data Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxData Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptx
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Heuristic Search Techniques {Artificial Intelligence}
Heuristic Search Techniques {Artificial Intelligence}Heuristic Search Techniques {Artificial Intelligence}
Heuristic Search Techniques {Artificial Intelligence}
 
Procedural programming
Procedural programmingProcedural programming
Procedural programming
 
Our presentation on algorithm design
Our presentation on algorithm designOur presentation on algorithm design
Our presentation on algorithm design
 
Input-Buffering
Input-BufferingInput-Buffering
Input-Buffering
 
The n Queen Problem
The n Queen ProblemThe n Queen Problem
The n Queen Problem
 
Finite automata-for-lexical-analysis
Finite automata-for-lexical-analysisFinite automata-for-lexical-analysis
Finite automata-for-lexical-analysis
 

Viewers also liked

R. villano - Birds (cd rom-vol. 2 parte 1)
R. villano - Birds (cd rom-vol. 2 parte 1)R. villano - Birds (cd rom-vol. 2 parte 1)
R. villano - Birds (cd rom-vol. 2 parte 1)Raimondo Villano
 
Whitebox Handheld Software Radio Kit
Whitebox Handheld Software Radio KitWhitebox Handheld Software Radio Kit
Whitebox Handheld Software Radio KitChris Testa
 
White Bubble
White BubbleWhite Bubble
White Bubbleflasorne
 
160607 14 sw교육_강의안
160607 14 sw교육_강의안160607 14 sw교육_강의안
160607 14 sw교육_강의안Choi Man Dream
 
Madhumita Project Coordinator/Business Analyst
Madhumita Project Coordinator/Business AnalystMadhumita Project Coordinator/Business Analyst
Madhumita Project Coordinator/Business AnalystMadhumita Bairagi
 
Ref Letter Kelly
Ref Letter KellyRef Letter Kelly
Ref Letter KellyKelly Bill
 
Rainbow Hope
Rainbow HopeRainbow Hope
Rainbow Hopeflasorne
 
Day in a life in Moshi, Tanzania
Day in a life in Moshi, TanzaniaDay in a life in Moshi, Tanzania
Day in a life in Moshi, Tanzanialvincentvaughan
 
Madhumita Project Coordinator/Business Analyst
Madhumita Project Coordinator/Business AnalystMadhumita Project Coordinator/Business Analyst
Madhumita Project Coordinator/Business AnalystMadhumita Bairagi
 
문제는 한글이 잘 구현되는가?
문제는 한글이 잘 구현되는가?문제는 한글이 잘 구현되는가?
문제는 한글이 잘 구현되는가?Choi Man Dream
 
햄스터로봇 한줄로산책하기
햄스터로봇 한줄로산책하기햄스터로봇 한줄로산책하기
햄스터로봇 한줄로산책하기Changsuk Hyoun
 
Blind date
Blind dateBlind date
Blind datejenb123
 
R. Villano - integrazione mezzi informatici per la storia - progetto minerva
R. Villano - integrazione mezzi informatici per la storia - progetto minervaR. Villano - integrazione mezzi informatici per la storia - progetto minerva
R. Villano - integrazione mezzi informatici per la storia - progetto minervaRaimondo Villano
 
AIR 를 이용한 One 소스 Multi 디바이스 개발
AIR 를 이용한 One 소스 Multi 디바이스 개발AIR 를 이용한 One 소스 Multi 디바이스 개발
AIR 를 이용한 One 소스 Multi 디바이스 개발Flower Park
 

Viewers also liked (19)

R. villano - Birds (cd rom-vol. 2 parte 1)
R. villano - Birds (cd rom-vol. 2 parte 1)R. villano - Birds (cd rom-vol. 2 parte 1)
R. villano - Birds (cd rom-vol. 2 parte 1)
 
Whitebox Handheld Software Radio Kit
Whitebox Handheld Software Radio KitWhitebox Handheld Software Radio Kit
Whitebox Handheld Software Radio Kit
 
White Bubble
White BubbleWhite Bubble
White Bubble
 
De gatos y escritores
De gatos y escritoresDe gatos y escritores
De gatos y escritores
 
[Untitled] (1)
[Untitled] (1)[Untitled] (1)
[Untitled] (1)
 
160607 14 sw교육_강의안
160607 14 sw교육_강의안160607 14 sw교육_강의안
160607 14 sw교육_강의안
 
Cosmo
CosmoCosmo
Cosmo
 
Madhumita Project Coordinator/Business Analyst
Madhumita Project Coordinator/Business AnalystMadhumita Project Coordinator/Business Analyst
Madhumita Project Coordinator/Business Analyst
 
Ref Letter Kelly
Ref Letter KellyRef Letter Kelly
Ref Letter Kelly
 
Rainbow Hope
Rainbow HopeRainbow Hope
Rainbow Hope
 
Day in a life in Moshi, Tanzania
Day in a life in Moshi, TanzaniaDay in a life in Moshi, Tanzania
Day in a life in Moshi, Tanzania
 
Madhumita Project Coordinator/Business Analyst
Madhumita Project Coordinator/Business AnalystMadhumita Project Coordinator/Business Analyst
Madhumita Project Coordinator/Business Analyst
 
문제는 한글이 잘 구현되는가?
문제는 한글이 잘 구현되는가?문제는 한글이 잘 구현되는가?
문제는 한글이 잘 구현되는가?
 
햄스터로봇 한줄로산책하기
햄스터로봇 한줄로산책하기햄스터로봇 한줄로산책하기
햄스터로봇 한줄로산책하기
 
Stanton
StantonStanton
Stanton
 
T. Où
T. OùT. Où
T. Où
 
Blind date
Blind dateBlind date
Blind date
 
R. Villano - integrazione mezzi informatici per la storia - progetto minerva
R. Villano - integrazione mezzi informatici per la storia - progetto minervaR. Villano - integrazione mezzi informatici per la storia - progetto minerva
R. Villano - integrazione mezzi informatici per la storia - progetto minerva
 
AIR 를 이용한 One 소스 Multi 디바이스 개발
AIR 를 이용한 One 소스 Multi 디바이스 개발AIR 를 이용한 One 소스 Multi 디바이스 개발
AIR 를 이용한 One 소스 Multi 디바이스 개발
 

Similar to Types of algorithms

Lec07-Greedy Algorithms.pdf Lec07-Greedy Algorithms.pdf
Lec07-Greedy Algorithms.pdf Lec07-Greedy Algorithms.pdfLec07-Greedy Algorithms.pdf Lec07-Greedy Algorithms.pdf
Lec07-Greedy Algorithms.pdf Lec07-Greedy Algorithms.pdfMAJDABDALLAH3
 
Algo_Lecture01.pptx
Algo_Lecture01.pptxAlgo_Lecture01.pptx
Algo_Lecture01.pptxShaistaRiaz4
 
Greedy algorithm for design and analysis
Greedy algorithm for design and analysisGreedy algorithm for design and analysis
Greedy algorithm for design and analysisJavedKhan524377
 
Data Analysis and Algorithms Lecture 1: Introduction
 Data Analysis and Algorithms Lecture 1: Introduction Data Analysis and Algorithms Lecture 1: Introduction
Data Analysis and Algorithms Lecture 1: IntroductionTayyabSattar5
 
DynamicProgramming.pptx
DynamicProgramming.pptxDynamicProgramming.pptx
DynamicProgramming.pptxSaimaShaheen14
 
Types of Algorithms.ppt
Types of Algorithms.pptTypes of Algorithms.ppt
Types of Algorithms.pptALIZAIB KHAN
 
CH-1.1 Introduction (1).pptx
CH-1.1 Introduction (1).pptxCH-1.1 Introduction (1).pptx
CH-1.1 Introduction (1).pptxsatvikkushwaha1
 
Greedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.pptGreedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.pptSeethaDinesh
 
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptxbcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptxB.T.L.I.T
 
Undecidable Problems and Approximation Algorithms
Undecidable Problems and Approximation AlgorithmsUndecidable Problems and Approximation Algorithms
Undecidable Problems and Approximation AlgorithmsMuthu Vinayagam
 

Similar to Types of algorithms (20)

35-algorithm-types.ppt
35-algorithm-types.ppt35-algorithm-types.ppt
35-algorithm-types.ppt
 
algorithm-types.ppt
algorithm-types.pptalgorithm-types.ppt
algorithm-types.ppt
 
35 algorithm-types
35 algorithm-types35 algorithm-types
35 algorithm-types
 
35 algorithm-types
35 algorithm-types35 algorithm-types
35 algorithm-types
 
Algorithm types
Algorithm typesAlgorithm types
Algorithm types
 
35 algorithm-types
35 algorithm-types35 algorithm-types
35 algorithm-types
 
32 algorithm-types
32 algorithm-types32 algorithm-types
32 algorithm-types
 
Lec07-Greedy Algorithms.pdf Lec07-Greedy Algorithms.pdf
Lec07-Greedy Algorithms.pdf Lec07-Greedy Algorithms.pdfLec07-Greedy Algorithms.pdf Lec07-Greedy Algorithms.pdf
Lec07-Greedy Algorithms.pdf Lec07-Greedy Algorithms.pdf
 
Algo_Lecture01.pptx
Algo_Lecture01.pptxAlgo_Lecture01.pptx
Algo_Lecture01.pptx
 
Greedy algorithm for design and analysis
Greedy algorithm for design and analysisGreedy algorithm for design and analysis
Greedy algorithm for design and analysis
 
Backtacking
BacktackingBacktacking
Backtacking
 
Data Analysis and Algorithms Lecture 1: Introduction
 Data Analysis and Algorithms Lecture 1: Introduction Data Analysis and Algorithms Lecture 1: Introduction
Data Analysis and Algorithms Lecture 1: Introduction
 
DynamicProgramming.pptx
DynamicProgramming.pptxDynamicProgramming.pptx
DynamicProgramming.pptx
 
Types of Algorithms.ppt
Types of Algorithms.pptTypes of Algorithms.ppt
Types of Algorithms.ppt
 
CH-1.1 Introduction (1).pptx
CH-1.1 Introduction (1).pptxCH-1.1 Introduction (1).pptx
CH-1.1 Introduction (1).pptx
 
algo classification.pptx
algo classification.pptxalgo classification.pptx
algo classification.pptx
 
Greedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.pptGreedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.ppt
 
Algorithm.pptx
Algorithm.pptxAlgorithm.pptx
Algorithm.pptx
 
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptxbcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
bcfbedbf-6679-4d5d-b8a5-7d4c9c48dba4.pptx
 
Undecidable Problems and Approximation Algorithms
Undecidable Problems and Approximation AlgorithmsUndecidable Problems and Approximation Algorithms
Undecidable Problems and Approximation Algorithms
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Types of algorithms

  • 1. Types of Algorithms CS 206 Aimhee Santos
  • 2. Algorithm classification • Algorithms that use a similar problem-solving approach can be grouped together • This classification scheme is neither exhaustive nor disjoint • The purpose is not to be able to classify an algorithm as one type or another, but to highlight the various ways in which a problem can be attacked
  • 3. A short list of categories • Algorithm types we will consider include: – Simple recursive algorithms – Backtracking algorithms – Divide and conquer algorithms – Dynamic programming algorithms – Greedy algorithms – Branch and bound algorithms – Brute force algorithms – Randomized algorithms
  • 4. Simple recursive algorithms I • A simple recursive algorithm: – Solves the base cases directly – Recurs with a simpler subproblem – Does some extra work to convert the solution to the simpler subproblem into a solution to the given problem • I call these “simple” because several of the other algorithm types are inherently recursive
  • 5. Example recursive algorithms • To count the number of elements in a list: – If the list is empty, return zero; otherwise, – Step past the first element, and count the remaining elements in the list – Add one to the result • To test if a value occurs in a list: – If the list is empty, return false; otherwise, – If the first thing in the list is the given value, return true; otherwise – Step past the first element, and test whether the value occurs in the remainder of the list
  • 6. Backtracking algorithms • Backtracking algorithms are based on a depth-first recursive search • A backtracking algorithm: – Tests to see if a solution has been found, and if so, returns it; otherwise – For each choice that can be made at this point, • Make that choice • Recur • If the recursion returns a solution, return it – If no choices remain, return failure
  • 7. Example backtracking algorithm • To color a map with no more than four colors: – color(Country n) • If all countries have been colored (n > number of countries) return success; otherwise, • For each color c of four colors, – If country n is not adjacent to a country that has been colored c » Color country n with color c » recursivly color country n+1 » If successful, return success • Return failure (if loop exits)
  • 8. Divide and Conquer • A divide and conquer algorithm consists of two parts: – Divide the problem into smaller subproblems of the same type, and solve these subproblems recursively – Combine the solutions to the subproblems into a solution to the original problem • Traditionally, an algorithm is only called divide and conquer if it contains two or more recursive calls
  • 9. Examples • Quicksort: – Partition the array into two parts, and quicksort each of the parts – No additional work is required to combine the two sorted parts • Mergesort: – Cut the array in half, and mergesort each half – Combine the two sorted arrays into a single sorted array by merging them
  • 10. Binary tree lookup • Here’s how to look up something in a sorted binary tree: – Compare the key to the value in the root • If the two values are equal, report success • If the key is less, search the left subtree • If the key is greater, search the right subtree • This is not a divide and conquer algorithm because, although there are two recursive calls, only one is used at each level of the recursion
  • 11. Fibonacci numbers • To find the nth Fibonacci number: – If n is zero or one, return one; otherwise, – Compute fibonacci(n-1) and fibonacci(n-2) – Return the sum of these two numbers • This is an expensive algorithm – It requires O(fibonacci(n)) time – This is equivalent to exponential time, that is, O(2n)
  • 12. Dynamic programming algorithms • A dynamic programming algorithm remembers past results and uses them to find new results • Dynamic programming is generally used for optimization problems – Multiple solutions exist, need to find the “best” one – Requires “optimal substructure” and “overlapping subproblems” • Optimal substructure: Optimal solution contains optimal solutions to subproblems • Overlapping subproblems: Solutions to subproblems can be stored and reused in a bottom-up fashion • This differs from Divide and Conquer, where subproblems generally need not overlap
  • 13. Fibonacci numbers again • To find the nth Fibonacci number: – If n is zero or one, return one; otherwise, – Compute, or look up in a table, fibonacci(n-1) and fibonacci(n-2) – Find the sum of these two numbers – Store the result in a table and return it • Since finding the nth Fibonacci number involves finding all smaller Fibonacci numbers, the second recursive call has little work to do • The table may be preserved and used again later
  • 14. Greedy algorithms • An optimization problem is one in which you want to find, not just a solution, but the best solution • A “greedy algorithm” sometimes works well for optimization problems • A greedy algorithm works in phases: At each phase: – You take the best you can get right now, without regard for future consequences – You hope that by choosing a local optimum at each step, you will end up at a global optimum
  • 15. Example: Counting money • Suppose you want to count out a certain amount of money, using the fewest possible bills and coins • A greedy algorithm would do this would be: At each step, take the largest possible bill or coin that does not overshoot – Example: To make $6.39, you can choose: • a $5 bill • a $1 bill, to make $6 • a 25¢ coin, to make $6.25 • A 10¢ coin, to make $6.35 • four 1¢ coins, to make $6.39 • For US money, the greedy algorithm always gives the optimum solution
  • 16. A failure of the greedy algorithm • In some (fictional) monetary system, “krons” come in 1 kron, 7 kron, and 10 kron coins • Using a greedy algorithm to count out 15 krons, you would get – A 10 kron piece – Five 1 kron pieces, for a total of 15 krons – This requires six coins • A better solution would be to use two 7 kron pieces and one 1 kron piece – This only requires three coins • The greedy algorithm results in a solution, but not in an optimal solution
  • 17. Branch and bound algorithms • Branch and bound algorithms are generally used for optimization problems – As the algorithm progresses, a tree of subproblems is formed – The original problem is considered the “root problem” – A method is used to construct an upper and lower bound for a given problem – At each node, apply the bounding methods • If the bounds match, it is deemed a feasible solution to that particular subproblem • If bounds do not match, partition the problem represented by that node, and make the two subproblems into children nodes – Continue, using the best known feasible solution to trim sections of the tree, until all nodes have been solved or trimmed
  • 18. Example branch and bound algorithm • Travelling salesman problem: A salesman has to visit each of n cities (at least) once each, and wants to minimize total distance travelled – Consider the root problem to be the problem of finding the shortest route through a set of cities visiting each city once – Split the node into two child problems: • Shortest route visiting city A first • Shortest route not visiting city A first – Continue subdividing similarly as the tree grows
  • 19. Brute force algorithm • A brute force algorithm simply tries all possibilities until a satisfactory solution is found – Such an algorithm can be: • Optimizing: Find the best solution. This may require finding all solutions, or if a value for the best solution is known, it may stop when any best solution is found – Example: Finding the best path for a travelling salesman • Satisficing: Stop as soon as a solution is found that is good enough – Example: Finding a travelling salesman path that is within 10% of optimal
  • 20. Improving brute force algorithms • Often, brute force algorithms require exponential time • Various heuristics and optimizations can be used – Heuristic: A “rule of thumb” that helps you decide which possibilities to look at first – Optimization: In this case, a way to eliminate certain possibilites without fully exploring them
  • 21. Randomized algorithms • A randomized algorithm uses a random number at least once during the computation to make a decision – Example: In Quicksort, using a random number to choose a pivot – Example: Trying to factor a large prime by choosing random numbers as possible divisors