SlideShare a Scribd company logo
1 of 3
Download to read offline
Computer Science 385
                                     Analysis of Algorithms
                                     Siena College
                                     Spring 2011


                  Topic Notes: Decrease and Conquer
Our next class of algorithms are the decrease-and-conquer group.
The idea here:

   1. Reduce the problem to a smaller instance

   2. Solve the smaller instance

   3. Modify the smaller instance solution to be a solution to the original

The main variations:

   • Decrease by a constant (often by 1)

   • Decrease by a constant factor (often by half)

   • Variable size decrease

For example, consider variations on how to compute the value an .
The brute-force approach would involve applying the definition and multiplying a by itself, n
times.
A decrease-by-one approach would reduce the problem to computing the result for the problem of
size n − 1 (computing an−1 ) then modifying that to be a solution to the original (by multiplying
that result by a).
                                                                                    n
A decrease-by-constant-factor (2, in this case) approach would involve computing a 2 and multi-
plying that result by itself to compute the answer. The only complication here is that we have to
treat odd exponents specially, leading to a rule:

                                    (a 2 )2
                                       n
                                   
                                                    if n is even
                               n               2
                              a =  (a   n−1
                                          2    ) · a if n > 1 and odd
                                    a                if n = 1
                                  
                                  


This approach will lead to O(log n) multiplications.


Insertion Sort
CS 385                                    Analysis of Algorithms                       Spring 2011



Our decrease-by-one approach to sorting is the insertion sort.
The insertion sort sorts an array of n elements by first sorting the first n−1 elements, then inserting
the last element into its correct position in the array.

insertion_sort(A[0..n-1]) {
  for (i=0 to n-1) {
    v = A[i]
    j = i-1
    while (j >= 0 and A[j] > v) {
      A[j+1] = A[j]
      j--
    }
    A[j+1] = v

This is an in-place sort and is stable.
Our basic operation for this algorithm is the comparison of keys in the while loop.
We do have differences in worst, average, and best case behavior. In the worst case, the while loop
always executes as many times as possible. This occurs when each element needs to go all the way
at the start of the sorted portion of the array – exactly when the starting array is in reverse sorted
order.
The worst case number of comparisons:

                                       n−1 i−1         n−1
                                                                  n(n − 1)
                        Cworst (n) =             1=          i=            ∈ Θ(n2 )
                                       i=1 j=0         i=1           2

In the best case, the inner loop needs to do just one comparison, determining that the element is
already in its correct position. This happens when the algorithm is presented with already-sorted
input. Here, the number of comparisons:

                                                 n−1
                                  Cbest (n) =          1 = n − 1 ∈ Θ(n)
                                                 i=1


This behavior is unusual – after all, how often do we attempt to sort an already-sorted array?
However, we come close in some very important cases. If we have nearly-sorted data, we have
nearly this same performance.
A careful analysis of the average case would result in:

                                                        n2
                                          Cavg (n) ≈       ∈ Θ(n2 )
                                                        4

Of the simple sorting algorithms (bubble, selection, insertion), insertion sort is considered the best
option in general.

                                                       2
CS 385                               Analysis of Algorithms                          Spring 2011




Graph Traversals
We return to graph structures for our next group of decrease-and-conquer algorithms. In particular,
we consider the problem of visiting all vertices in a graph.
The two main approaches are the depth-first search (DFS) and the breadth-first search (BFS).
See the text for details...


Topological Sort
Again, see the text for details...




                                                3

More Related Content

What's hot

Weatherwax cormen solutions
Weatherwax cormen solutionsWeatherwax cormen solutions
Weatherwax cormen solutions
kirankoushik
 
Generalization of Tensor Factorization and Applications
Generalization of Tensor Factorization and ApplicationsGeneralization of Tensor Factorization and Applications
Generalization of Tensor Factorization and Applications
Kohei Hayashi
 
Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3
Traian Rebedea
 
Digital Signal Processing Tutorial:Chapt 2 z transform
Digital Signal Processing Tutorial:Chapt 2 z transformDigital Signal Processing Tutorial:Chapt 2 z transform
Digital Signal Processing Tutorial:Chapt 2 z transform
Chandrashekhar Padole
 
Mathematics notes and formula for class 12 chapter 7. integrals
Mathematics notes and formula for class 12 chapter 7. integrals Mathematics notes and formula for class 12 chapter 7. integrals
Mathematics notes and formula for class 12 chapter 7. integrals
sakhi pathak
 
Introduction to FEM
Introduction to FEMIntroduction to FEM
Introduction to FEM
mezkurra
 

What's hot (20)

Weatherwax cormen solutions
Weatherwax cormen solutionsWeatherwax cormen solutions
Weatherwax cormen solutions
 
Recursion
RecursionRecursion
Recursion
 
Generalization of Tensor Factorization and Applications
Generalization of Tensor Factorization and ApplicationsGeneralization of Tensor Factorization and Applications
Generalization of Tensor Factorization and Applications
 
Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3Algorithm Design and Complexity - Course 3
Algorithm Design and Complexity - Course 3
 
Limits of functions
Limits of functionsLimits of functions
Limits of functions
 
Phases of fuzzy field theories
Phases of fuzzy field theoriesPhases of fuzzy field theories
Phases of fuzzy field theories
 
Machine Learning 1
Machine Learning 1Machine Learning 1
Machine Learning 1
 
Lecture cochran
Lecture cochranLecture cochran
Lecture cochran
 
Digital Signal Processing Tutorial:Chapt 2 z transform
Digital Signal Processing Tutorial:Chapt 2 z transformDigital Signal Processing Tutorial:Chapt 2 z transform
Digital Signal Processing Tutorial:Chapt 2 z transform
 
Random Matrix Theory and Machine Learning - Part 4
Random Matrix Theory and Machine Learning - Part 4Random Matrix Theory and Machine Learning - Part 4
Random Matrix Theory and Machine Learning - Part 4
 
SVM (Support Vector Machine & Kernel)
SVM (Support Vector Machine & Kernel)SVM (Support Vector Machine & Kernel)
SVM (Support Vector Machine & Kernel)
 
Mathematics notes and formula for class 12 chapter 7. integrals
Mathematics notes and formula for class 12 chapter 7. integrals Mathematics notes and formula for class 12 chapter 7. integrals
Mathematics notes and formula for class 12 chapter 7. integrals
 
Random Matrix Theory and Machine Learning - Part 2
Random Matrix Theory and Machine Learning - Part 2Random Matrix Theory and Machine Learning - Part 2
Random Matrix Theory and Machine Learning - Part 2
 
Random Matrix Theory and Machine Learning - Part 3
Random Matrix Theory and Machine Learning - Part 3Random Matrix Theory and Machine Learning - Part 3
Random Matrix Theory and Machine Learning - Part 3
 
11.generalized and subset integrated autoregressive moving average bilinear t...
11.generalized and subset integrated autoregressive moving average bilinear t...11.generalized and subset integrated autoregressive moving average bilinear t...
11.generalized and subset integrated autoregressive moving average bilinear t...
 
Introduction to FEM
Introduction to FEMIntroduction to FEM
Introduction to FEM
 
Lecture 1 computational intelligence
Lecture 1  computational intelligenceLecture 1  computational intelligence
Lecture 1 computational intelligence
 
Recursive Formulation of Gradient in a Dense Feed-Forward Deep Neural Network
Recursive Formulation of Gradient in a Dense Feed-Forward Deep Neural NetworkRecursive Formulation of Gradient in a Dense Feed-Forward Deep Neural Network
Recursive Formulation of Gradient in a Dense Feed-Forward Deep Neural Network
 
Lec10
Lec10Lec10
Lec10
 
Lecture 2 fuzzy inference system
Lecture 2  fuzzy inference systemLecture 2  fuzzy inference system
Lecture 2 fuzzy inference system
 

Viewers also liked

Sienna 9 hashing
Sienna 9 hashingSienna 9 hashing
Sienna 9 hashing
chidabdu
 
Sienna 8 countingsorts
Sienna 8 countingsortsSienna 8 countingsorts
Sienna 8 countingsorts
chidabdu
 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heaps
chidabdu
 
Sienna 6 bst
Sienna 6 bstSienna 6 bst
Sienna 6 bst
chidabdu
 
Sienna 10 dynamic
Sienna 10 dynamicSienna 10 dynamic
Sienna 10 dynamic
chidabdu
 
Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffman
chidabdu
 
Sienna 11 graphs
Sienna 11 graphsSienna 11 graphs
Sienna 11 graphs
chidabdu
 
Algorithm chapter 7
Algorithm chapter 7Algorithm chapter 7
Algorithm chapter 7
chidabdu
 

Viewers also liked (8)

Sienna 9 hashing
Sienna 9 hashingSienna 9 hashing
Sienna 9 hashing
 
Sienna 8 countingsorts
Sienna 8 countingsortsSienna 8 countingsorts
Sienna 8 countingsorts
 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heaps
 
Sienna 6 bst
Sienna 6 bstSienna 6 bst
Sienna 6 bst
 
Sienna 10 dynamic
Sienna 10 dynamicSienna 10 dynamic
Sienna 10 dynamic
 
Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffman
 
Sienna 11 graphs
Sienna 11 graphsSienna 11 graphs
Sienna 11 graphs
 
Algorithm chapter 7
Algorithm chapter 7Algorithm chapter 7
Algorithm chapter 7
 

Similar to Sienna 5 decreaseandconquer

Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
chidabdu
 
Quicksort analysis
Quicksort analysisQuicksort analysis
Quicksort analysis
Premjeet Roy
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sorting
zukun
 
Skiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortSkiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksort
zukun
 
Algorithm chapter 5
Algorithm chapter 5Algorithm chapter 5
Algorithm chapter 5
chidabdu
 
lecture 8
lecture 8lecture 8
lecture 8
sajinsc
 

Similar to Sienna 5 decreaseandconquer (20)

Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
 
Analysis and design of algorithms part2
Analysis and design of algorithms part2Analysis and design of algorithms part2
Analysis and design of algorithms part2
 
Introduction
IntroductionIntroduction
Introduction
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Merge sort and quick sort
Merge sort and quick sortMerge sort and quick sort
Merge sort and quick sort
 
Daa chapter5
Daa chapter5Daa chapter5
Daa chapter5
 
Quicksort analysis
Quicksort analysisQuicksort analysis
Quicksort analysis
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sorting
 
Skiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortSkiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksort
 
Algorithm chapter 5
Algorithm chapter 5Algorithm chapter 5
Algorithm chapter 5
 
Cs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyCs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer key
 
lecture 8
lecture 8lecture 8
lecture 8
 
Algorithm Design and Analysis
Algorithm Design and AnalysisAlgorithm Design and Analysis
Algorithm Design and Analysis
 
Linear sorting
Linear sortingLinear sorting
Linear sorting
 
Daa notes 2
Daa notes 2Daa notes 2
Daa notes 2
 
03 dc
03 dc03 dc
03 dc
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
 
Best,worst,average case .17581556 045
Best,worst,average case .17581556 045Best,worst,average case .17581556 045
Best,worst,average case .17581556 045
 
Analysis and design of algorithms part 4
Analysis and design of algorithms part 4Analysis and design of algorithms part 4
Analysis and design of algorithms part 4
 
S1 Dualsimplex
S1 DualsimplexS1 Dualsimplex
S1 Dualsimplex
 

More from chidabdu

Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysis
chidabdu
 
Sienna 1 intro
Sienna 1 introSienna 1 intro
Sienna 1 intro
chidabdu
 
Sienna 13 limitations
Sienna 13 limitationsSienna 13 limitations
Sienna 13 limitations
chidabdu
 
Unit 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unit
chidabdu
 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organization
chidabdu
 
Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1
chidabdu
 
Algorithm chapter 11
Algorithm chapter 11Algorithm chapter 11
Algorithm chapter 11
chidabdu
 
Algorithm chapter 10
Algorithm chapter 10Algorithm chapter 10
Algorithm chapter 10
chidabdu
 
Algorithm chapter 9
Algorithm chapter 9Algorithm chapter 9
Algorithm chapter 9
chidabdu
 
Algorithm chapter 8
Algorithm chapter 8Algorithm chapter 8
Algorithm chapter 8
chidabdu
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6
chidabdu
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
chidabdu
 
Algorithm review
Algorithm reviewAlgorithm review
Algorithm review
chidabdu
 
Unit 2 arithmetics
Unit 2   arithmeticsUnit 2   arithmetics
Unit 2 arithmetics
chidabdu
 
Unit 1 basic structure of computers
Unit 1   basic structure of computersUnit 1   basic structure of computers
Unit 1 basic structure of computers
chidabdu
 
Unit 4 memory system
Unit 4   memory systemUnit 4   memory system
Unit 4 memory system
chidabdu
 

More from chidabdu (16)

Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysis
 
Sienna 1 intro
Sienna 1 introSienna 1 intro
Sienna 1 intro
 
Sienna 13 limitations
Sienna 13 limitationsSienna 13 limitations
Sienna 13 limitations
 
Unit 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unit
 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organization
 
Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1
 
Algorithm chapter 11
Algorithm chapter 11Algorithm chapter 11
Algorithm chapter 11
 
Algorithm chapter 10
Algorithm chapter 10Algorithm chapter 10
Algorithm chapter 10
 
Algorithm chapter 9
Algorithm chapter 9Algorithm chapter 9
Algorithm chapter 9
 
Algorithm chapter 8
Algorithm chapter 8Algorithm chapter 8
Algorithm chapter 8
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
 
Algorithm review
Algorithm reviewAlgorithm review
Algorithm review
 
Unit 2 arithmetics
Unit 2   arithmeticsUnit 2   arithmetics
Unit 2 arithmetics
 
Unit 1 basic structure of computers
Unit 1   basic structure of computersUnit 1   basic structure of computers
Unit 1 basic structure of computers
 
Unit 4 memory system
Unit 4   memory systemUnit 4   memory system
Unit 4 memory system
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
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
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Sienna 5 decreaseandconquer

  • 1. Computer Science 385 Analysis of Algorithms Siena College Spring 2011 Topic Notes: Decrease and Conquer Our next class of algorithms are the decrease-and-conquer group. The idea here: 1. Reduce the problem to a smaller instance 2. Solve the smaller instance 3. Modify the smaller instance solution to be a solution to the original The main variations: • Decrease by a constant (often by 1) • Decrease by a constant factor (often by half) • Variable size decrease For example, consider variations on how to compute the value an . The brute-force approach would involve applying the definition and multiplying a by itself, n times. A decrease-by-one approach would reduce the problem to computing the result for the problem of size n − 1 (computing an−1 ) then modifying that to be a solution to the original (by multiplying that result by a). n A decrease-by-constant-factor (2, in this case) approach would involve computing a 2 and multi- plying that result by itself to compute the answer. The only complication here is that we have to treat odd exponents specially, leading to a rule:  (a 2 )2  n   if n is even n 2 a =  (a n−1 2 ) · a if n > 1 and odd a if n = 1   This approach will lead to O(log n) multiplications. Insertion Sort
  • 2. CS 385 Analysis of Algorithms Spring 2011 Our decrease-by-one approach to sorting is the insertion sort. The insertion sort sorts an array of n elements by first sorting the first n−1 elements, then inserting the last element into its correct position in the array. insertion_sort(A[0..n-1]) { for (i=0 to n-1) { v = A[i] j = i-1 while (j >= 0 and A[j] > v) { A[j+1] = A[j] j-- } A[j+1] = v This is an in-place sort and is stable. Our basic operation for this algorithm is the comparison of keys in the while loop. We do have differences in worst, average, and best case behavior. In the worst case, the while loop always executes as many times as possible. This occurs when each element needs to go all the way at the start of the sorted portion of the array – exactly when the starting array is in reverse sorted order. The worst case number of comparisons: n−1 i−1 n−1 n(n − 1) Cworst (n) = 1= i= ∈ Θ(n2 ) i=1 j=0 i=1 2 In the best case, the inner loop needs to do just one comparison, determining that the element is already in its correct position. This happens when the algorithm is presented with already-sorted input. Here, the number of comparisons: n−1 Cbest (n) = 1 = n − 1 ∈ Θ(n) i=1 This behavior is unusual – after all, how often do we attempt to sort an already-sorted array? However, we come close in some very important cases. If we have nearly-sorted data, we have nearly this same performance. A careful analysis of the average case would result in: n2 Cavg (n) ≈ ∈ Θ(n2 ) 4 Of the simple sorting algorithms (bubble, selection, insertion), insertion sort is considered the best option in general. 2
  • 3. CS 385 Analysis of Algorithms Spring 2011 Graph Traversals We return to graph structures for our next group of decrease-and-conquer algorithms. In particular, we consider the problem of visiting all vertices in a graph. The two main approaches are the depth-first search (DFS) and the breadth-first search (BFS). See the text for details... Topological Sort Again, see the text for details... 3