SlideShare a Scribd company logo
1 of 30
Download to read offline
Decrease and Conquer
Decrease and Conquer
 Exploring the relationship between a solution
 to a given instance of (e.g., P(n) )a problem
 and a solution to a smaller instance (e.g.,
 P(n/2) or P(n-1) )of the same problem.
 Use top down(recursive) or bottom up
 (iterative) to solve the problem.
 Example, n!
   A top down (recursive) solution
   A bottom up (iterative) solution


                                            2
Examples of Decrease and Conquer
Decrease by a constant:         the size of the problem is reduced by the same constant
on each iteration/recursion of the algorithm.
    Insertion sort
    Graph search algorithms:
        DFS
        BFS
        Topological sorting
    Algorithms for generating permutations, subsets
Decrease by a constant factor:          the size of the problem is reduced by the same
constant factor on each iteration/recursion of the algorithm.
    Binary search
    Fake-coin problems
Variable-size decrease: the size reduction pattern varies from one iteration of an
algorithm to another.
    Euclid’s algorithm


                                                                                   3
A Typical Decrease by One Technique

                     a problem of size n



  subproblem
    of size n-1



 a solution to the
  subproblem




                                            e.g., n!
                         a solution to
                     the original problem              4
A Typical Decrease by a Constant Factor
            (half) Technique

                    a problem of size n



 subproblem
   of size n/2



a solution to the
  subproblem




                                           e.g., Binary search
                        a solution to
                    the original problem                    5
A Typical Divide and Conquer Technique

                   a problem of size n



 subproblem 1                             subproblem 2
   of size n/2                              of size n/2



   a solution to                           a solution to
  subproblem 1                            subproblem 2




                                                  e.g., mergesort
                       a solution to
                   the original problem                             6
What’s the Difference?
Consider the problem of exponentiation: Compute an
  Decrease by one
     Bottom-up: iterative (brute Force) an= a*a*a*a*...*a
     Top-down:recursive                  an= an-1* a      if n > 1
                                                          if n = 1
  Divide and conquer:                      =a

          an= a ⎣ n/2 ⎦ * a ⎡ n/2 ⎤   if n > 1
             =a                       if n = 1

  Decrease by a constant factor:
         an = (an/2 ) 2               if n is even and positive
            = (a(n-1)/2 ) 2 * a       if n is odd and > 1
            =a                        if n = 1
                                                                     7
Insertion Sort
 A decrease by one algorithm
   A bottom-up (iterative) solution
   A top-down (recursive) solution




                                      8
Insertion Sort: an Iterative Solution
ALGORITHM InsertionSortIter(A[0..n-1])
//An iterative implementation of insertion sort
//Input: An array A[0..n-1] of n orderable elements
//Output: Array A[0..n-1] sorted in nondecreasing order

for i    1 to n – 1 do      // i: the index of the first element of the unsorted part.
   key = A[i]
   for j    i – 1 to 0 do   // j: the index of the sorted part of the array
   if (key< A[j])           //compare the key with each element in the sorted part
         A[j+1]      A[j]
   else
         break
   A[j +1]      key         //insert the key to the sorted part of the array


                                                   Efficiency?
                                                                                     9
Insertion Sort: a Recursive Solution
ALGORITHM InsertionSortRecur(A[0..n-1], n-1)
//A recursive implementation of insertion sort
//Input: An array A[0..n-1] of n orderable elements       Index of the last element
//Output: Array A[0..n-1] sorted in nondecreasing order
if n > 1
    InsertionSortRecur(A[0..n-1], n-2)
    Insert(A[0..n-1], n-1) //insert A[n-1] to A[0..n-2]
                                              Index of the element/key to be inserted.
ALGORITHM Insert(A[0..m], m)
//Insert A[m] to the sorted subarray A[0..m-1] of A[0..n-1]
//Input: A subarray A[0..m] of A[0..n-1]
//Output: Array A[0..m] sorted in nondecreasing order
key = A[m]
for j    m – 1 to 0 do
    if (key< A[j])
          A[j+1]    A[j]                     Recurrence       relation?
    else
          break
A[j +1]     key                                                                       10
Exercises
Design a recursive decrease-by-one algorithm for
  finding the position of the largest element in an array
  of n real numbers.
Determine the time efficiency of this algorithm and
  compare it with that of the brute-force algorithm for
  the same problem.




                                                     11
Graph Traversal
 Many problems require processing all graph
 vertices in a systematic fashion

 Graph traversal algorithms:

   Depth-first search

   Breadth-first search

                                          12
Some Terminologies
Vertices and Edges
Undirected and directed graphs
Parents, children, and ancestors.
Connected graphs
  A graph is said to be connected if for every
  pair of its vertices u and v there is a path
  from u to v.


                                                 13
Graph Representation
 Adjacency matrix
    n x n boolean matrix if |V| is n.
    The element on the ith row and jth column is 1 if there’s an
    edge from ith vertex to the jth vertex; otherwise 0.
    The adjacency matrix of an undirected graph is symmetric.
    It takes |V| (comparisons) to figure out all the adjacent
    nodes of a certain node i.
 Adjacency linked lists
    A collection of linked lists, one for each vertex, that contain
    all the vertices adjacent to the list’s vertex.
 An example



                                                                14
Depth-first search
The idea
   traverse “deeper” whenever possible.
   On each iteration, the algorithm proceeds to an unvisited vertex that is
   adjacent to the one it is currently in. If there are more than more
   neighbors, break the tie by the alphabetic order of the vertices.
   When reaching a dead end ( a vertex with no adjacent unvisited vertices),
   the algorithm backs up one edge to the parent and tries to continue visiting
   unvisited vertices from there.
   The algorithm halts after backing up to the starting vertex, with the latter
   being a dead end.
Similar to preorder tree traversals
It’s convenient to use a stack to trace the operation of depth-first
search.
   Push a vertex onto the stack when the vertex is reached for the first time.
   Pop a vertex off the stack when it becomes a dead end.
An example

                                                                             15
Example – undirected graphs
       a        b         c        d



       e        f         g        h



Depth-first traversal:Give the order in
which the vertices were reached.
 abfegcdh
                                          16
Depth-first search (DFS)
Pseudocode for Depth-first-search of graph G=(V,E)
DFS(G) // Use depth-first to visit a graph, which might
       // contain multiple connected components.
count    0 //visiting sequence number
mark each vertex with 0 // (unvisited)
for each vertex v∈ V do
     if v is marked with 0 //w has not been visited yet.
          dfs(v)
                                  dfs(v)
                                  //Use depth-first to visit a connected component starting
                                  //from vertex v.
                                  count     count + 1
                                  mark v with count //visit vertex v
                                  for each vertex w adjacent to v do
                                       if w is marked with 0 //w has not been visited yet.
                                                  dfs(w)
                                                                                          17
Types of edges
 Tree edges: edges comprising forest

 Back edges: edges to ancestor nodes

 Forward edges: edges to descendants
 (digraphs only)

 Cross edges: none of the above

                                       18
Example – directed graph
       a        b         c        d



       e        f         g        h



Depth-first traversal: Give the order in
which the vertices were reached.
 abfghecd
                                           19
Depth-first search: Notes
 DFS can be implemented with graphs
 represented as:
   Adjacency matrices: Θ(|V |2)
   Adjacency linked lists: Θ(|V |+|E| )
 Applications:
   checking connectivity
   finding connected components


                                          20
Breadth-first search (BFS)
The idea
  Traverse “wider” whenever possible.
  Discover all vertices at distance k from s (on level k)
  before discovering any vertices at distance k +1 (at
  level k+1)
Similar to level-by-level tree traversals
Instead of a stack, breadth-first uses a queue.




                                                       21
Example – undirected graph
       a        b          c   d



       e        f          g   h



Breadth-first traversal:
 abefgchd

                                   22
Breadth-first search algorithm
BFS(G)
count      0
mark each vertex with 0   bfs(v)
for each vertex v∈ V do   count        count + 1
  if v is marked with 0   mark v with count         //visit v
               bfs(v)     initialize queue with v //enqueue
                          while queue is not empty do
                             a      front of queue //dequeue
                             for each vertex w adjacent to a do
                                   if w is marked with 0 //w hasn’t been visited.
                                      count     count + 1
                                      mark w with count //visit w
                                      add w to the end of the queue //enqueue
                              remove a from the front of the queue

                                                                           23
Example – directed graph
       a        b          c   d



       e        f          g   h



Breadth-first traversal:
 abefghcd

                                   24
Breadth-first search: Notes
 BFS has same efficiency as DFS and can be
 implemented with graphs represented as:
   Adjacency matrices: Θ(|V |2)
   Adjacency linked lists: Θ(|V |+|E| )
 Applications:
   checking connectivity
   finding connected components
   finding paths between two vertices with the
   smallest number of edges

                                                 25
Topological Sorting
      Problem: Given a Directed Acyclic Graph(DAG) G =
      (V, E), find a linear ordering of all its vertices such
      that if G contains an edge (u, v), then u appears
      before v in the ordering.
      Example: Give an order of the courses so that the
      prerequisites are met.
                        C4

C1           C3
                                  Is the problem solvable if the
                                    digraph contains a cycle?

      C2              C5
                                                             26
The DFS-Based Algorithm
DFS-based algorithm: (2 orderings exist in the DFS)
  DFS traversal noting the order in which vertices are
  popped off stack (the order in which the dead end
  vertices appear)
  Reverse the above order.
Questions
  Can we use the order in which vertices are pushed onto
  the DFS stack (instead of the order they are popped off it)
  to solve the topological sorting problem?
  Does it matter from which node we start?
  Θ(|V |+|E| ) using adjacency linked lists

                                                         27
Example: Scheduling with Task Dependencies

Task        Number   Depends                            Wake up 1
                     on
Wake up     1        --
Dress       2        7,8                                               Make      Make
                                                                      coffee 5   toast 6
Eat         3        5, 6                        Shower 7
                               Choose
breakfast                      clothes 8
Leave       4        2, 3
                                                                  Eat
Make        5        1
                                                               breakfast 3
coffee                                     Dress 2
Make        6        1
toast
Shower      7        1                               Leave 4
Choose      8        1
clothes
                                                                                 28
The Source Removal Algorithms
Source removal algorithm
    Based on a direct implementation of the
    decrease-by-one techniques.
    Repeatedly identify and remove a source
    vertex, ie, a vertex that has no incoming edges,
    and delete it along with all the edges outgoing
    from it.



                                                  29
Exercises
 Problem 1, Exercise 5.2
 Problem 1, Exercise 5.3
 Problem 5, Exercise 5.3




                           30

More Related Content

What's hot

Refresher algebra-calculus
Refresher algebra-calculusRefresher algebra-calculus
Refresher algebra-calculusSteve Nouri
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
 
Algorithm Design and Complexity - Course 11
Algorithm Design and Complexity - Course 11Algorithm Design and Complexity - Course 11
Algorithm Design and Complexity - Course 11Traian Rebedea
 
Average value by integral method
Average value by integral methodAverage value by integral method
Average value by integral methodArun Umrao
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithmMohd Arif
 
Finite automata intro
Finite automata introFinite automata intro
Finite automata introlavishka_anuj
 
01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issuesAndres Mendez-Vazquez
 
Basic mathematics differentiation application
Basic mathematics differentiation applicationBasic mathematics differentiation application
Basic mathematics differentiation applicationMuhammad Luthfan
 
CBSE Class 12 Mathematics formulas
CBSE Class 12 Mathematics formulasCBSE Class 12 Mathematics formulas
CBSE Class 12 Mathematics formulasParth Kshirsagar
 
Database systems-Formal relational query languages
Database systems-Formal relational query languagesDatabase systems-Formal relational query languages
Database systems-Formal relational query languagesjamunaashok
 

What's hot (20)

Refresher algebra-calculus
Refresher algebra-calculusRefresher algebra-calculus
Refresher algebra-calculus
 
21 4 ztransform
21 4 ztransform21 4 ztransform
21 4 ztransform
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
 
Algorithm Design and Complexity - Course 11
Algorithm Design and Complexity - Course 11Algorithm Design and Complexity - Course 11
Algorithm Design and Complexity - Course 11
 
Backtracking
BacktrackingBacktracking
Backtracking
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Average value by integral method
Average value by integral methodAverage value by integral method
Average value by integral method
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
 
01.02 linear equations
01.02 linear equations01.02 linear equations
01.02 linear equations
 
Unit v
Unit vUnit v
Unit v
 
Finite automata intro
Finite automata introFinite automata intro
Finite automata intro
 
01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues01.03 squared matrices_and_other_issues
01.03 squared matrices_and_other_issues
 
Basic mathematics differentiation application
Basic mathematics differentiation applicationBasic mathematics differentiation application
Basic mathematics differentiation application
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
CBSE Class 12 Mathematics formulas
CBSE Class 12 Mathematics formulasCBSE Class 12 Mathematics formulas
CBSE Class 12 Mathematics formulas
 
Differential calculus
Differential calculusDifferential calculus
Differential calculus
 
Chap05alg
Chap05algChap05alg
Chap05alg
 
Database systems-Formal relational query languages
Database systems-Formal relational query languagesDatabase systems-Formal relational query languages
Database systems-Formal relational query languages
 
Differentiation
DifferentiationDifferentiation
Differentiation
 
21 3 ztransform
21 3 ztransform21 3 ztransform
21 3 ztransform
 

Viewers also liked

Chpt9 patternmatching
Chpt9 patternmatchingChpt9 patternmatching
Chpt9 patternmatchingdbhanumahesh
 
Bca ii dfs u-3 tree and graph
Bca  ii dfs u-3 tree and graphBca  ii dfs u-3 tree and graph
Bca ii dfs u-3 tree and graphRai University
 
Depth firstsearchalgorithm
Depth firstsearchalgorithmDepth firstsearchalgorithm
Depth firstsearchalgorithmhansa khan
 
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11sumitbardhan
 
Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffmanchidabdu
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREESiddhi Shrivas
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2chidabdu
 
Unit 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unitchidabdu
 

Viewers also liked (9)

Chpt9 patternmatching
Chpt9 patternmatchingChpt9 patternmatching
Chpt9 patternmatching
 
07 dc3
07 dc307 dc3
07 dc3
 
Bca ii dfs u-3 tree and graph
Bca  ii dfs u-3 tree and graphBca  ii dfs u-3 tree and graph
Bca ii dfs u-3 tree and graph
 
Depth firstsearchalgorithm
Depth firstsearchalgorithmDepth firstsearchalgorithm
Depth firstsearchalgorithm
 
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
 
Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffman
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREE
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
 
Unit 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unit
 

Similar to Algorithm chapter 5

Algorithm review
Algorithm reviewAlgorithm review
Algorithm reviewchidabdu
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 
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 4Deepak John
 
Sienna 5 decreaseandconquer
Sienna 5 decreaseandconquerSienna 5 decreaseandconquer
Sienna 5 decreaseandconquerchidabdu
 
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 keyappasami
 
Module 2 Lesson 2 Notes
Module 2 Lesson 2 NotesModule 2 Lesson 2 Notes
Module 2 Lesson 2 Notestoni dimella
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting classgiridaroori
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquerchidabdu
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103Sure Interview
 
Undecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWER
Undecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWERUndecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWER
Undecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWERmuthukrishnavinayaga
 
Cheat Sheets for Hard Problems
Cheat Sheets for Hard ProblemsCheat Sheets for Hard Problems
Cheat Sheets for Hard ProblemsNeeldhara Misra
 

Similar to Algorithm chapter 5 (20)

Algorithm review
Algorithm reviewAlgorithm review
Algorithm review
 
Review session2
Review session2Review session2
Review session2
 
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
 
Graphs
GraphsGraphs
Graphs
 
Sienna 5 decreaseandconquer
Sienna 5 decreaseandconquerSienna 5 decreaseandconquer
Sienna 5 decreaseandconquer
 
Function Basics Math Wiki
Function Basics   Math WikiFunction Basics   Math Wiki
Function Basics Math Wiki
 
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
 
Brute force
Brute forceBrute force
Brute force
 
Q
QQ
Q
 
Module 2 Lesson 2 Notes
Module 2 Lesson 2 NotesModule 2 Lesson 2 Notes
Module 2 Lesson 2 Notes
 
L04 (1)
L04 (1)L04 (1)
L04 (1)
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
 
New day 5 examples
New day 5 examplesNew day 5 examples
New day 5 examples
 
Approx
ApproxApprox
Approx
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
 
Tower of Hanoi.ppt
Tower of Hanoi.pptTower of Hanoi.ppt
Tower of Hanoi.ppt
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
 
Undecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWER
Undecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWERUndecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWER
Undecidable Problems - COPING WITH THE LIMITATIONS OF ALGORITHM POWER
 
Cheat Sheets for Hard Problems
Cheat Sheets for Hard ProblemsCheat Sheets for Hard Problems
Cheat Sheets for Hard Problems
 
Calc 2.1
Calc 2.1Calc 2.1
Calc 2.1
 

More from chidabdu

Sienna 11 graphs
Sienna 11 graphsSienna 11 graphs
Sienna 11 graphschidabdu
 
Sienna 10 dynamic
Sienna 10 dynamicSienna 10 dynamic
Sienna 10 dynamicchidabdu
 
Sienna 9 hashing
Sienna 9 hashingSienna 9 hashing
Sienna 9 hashingchidabdu
 
Sienna 8 countingsorts
Sienna 8 countingsortsSienna 8 countingsorts
Sienna 8 countingsortschidabdu
 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heapschidabdu
 
Sienna 6 bst
Sienna 6 bstSienna 6 bst
Sienna 6 bstchidabdu
 
Sienna 3 bruteforce
Sienna 3 bruteforceSienna 3 bruteforce
Sienna 3 bruteforcechidabdu
 
Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysischidabdu
 
Sienna 1 intro
Sienna 1 introSienna 1 intro
Sienna 1 introchidabdu
 
Sienna 13 limitations
Sienna 13 limitationsSienna 13 limitations
Sienna 13 limitationschidabdu
 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organizationchidabdu
 
Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1chidabdu
 
Algorithm chapter 11
Algorithm chapter 11Algorithm chapter 11
Algorithm chapter 11chidabdu
 
Algorithm chapter 10
Algorithm chapter 10Algorithm chapter 10
Algorithm chapter 10chidabdu
 
Algorithm chapter 9
Algorithm chapter 9Algorithm chapter 9
Algorithm chapter 9chidabdu
 
Algorithm chapter 8
Algorithm chapter 8Algorithm chapter 8
Algorithm chapter 8chidabdu
 
Algorithm chapter 7
Algorithm chapter 7Algorithm chapter 7
Algorithm chapter 7chidabdu
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6chidabdu
 
Unit 2 arithmetics
Unit 2   arithmeticsUnit 2   arithmetics
Unit 2 arithmeticschidabdu
 
Unit 1 basic structure of computers
Unit 1   basic structure of computersUnit 1   basic structure of computers
Unit 1 basic structure of computerschidabdu
 

More from chidabdu (20)

Sienna 11 graphs
Sienna 11 graphsSienna 11 graphs
Sienna 11 graphs
 
Sienna 10 dynamic
Sienna 10 dynamicSienna 10 dynamic
Sienna 10 dynamic
 
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 3 bruteforce
Sienna 3 bruteforceSienna 3 bruteforce
Sienna 3 bruteforce
 
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 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 7
Algorithm chapter 7Algorithm chapter 7
Algorithm chapter 7
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6
 
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
 

Recently uploaded

Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 

Recently uploaded (20)

Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 

Algorithm chapter 5

  • 2. Decrease and Conquer Exploring the relationship between a solution to a given instance of (e.g., P(n) )a problem and a solution to a smaller instance (e.g., P(n/2) or P(n-1) )of the same problem. Use top down(recursive) or bottom up (iterative) to solve the problem. Example, n! A top down (recursive) solution A bottom up (iterative) solution 2
  • 3. Examples of Decrease and Conquer Decrease by a constant: the size of the problem is reduced by the same constant on each iteration/recursion of the algorithm. Insertion sort Graph search algorithms: DFS BFS Topological sorting Algorithms for generating permutations, subsets Decrease by a constant factor: the size of the problem is reduced by the same constant factor on each iteration/recursion of the algorithm. Binary search Fake-coin problems Variable-size decrease: the size reduction pattern varies from one iteration of an algorithm to another. Euclid’s algorithm 3
  • 4. A Typical Decrease by One Technique a problem of size n subproblem of size n-1 a solution to the subproblem e.g., n! a solution to the original problem 4
  • 5. A Typical Decrease by a Constant Factor (half) Technique a problem of size n subproblem of size n/2 a solution to the subproblem e.g., Binary search a solution to the original problem 5
  • 6. A Typical Divide and Conquer Technique a problem of size n subproblem 1 subproblem 2 of size n/2 of size n/2 a solution to a solution to subproblem 1 subproblem 2 e.g., mergesort a solution to the original problem 6
  • 7. What’s the Difference? Consider the problem of exponentiation: Compute an Decrease by one Bottom-up: iterative (brute Force) an= a*a*a*a*...*a Top-down:recursive an= an-1* a if n > 1 if n = 1 Divide and conquer: =a an= a ⎣ n/2 ⎦ * a ⎡ n/2 ⎤ if n > 1 =a if n = 1 Decrease by a constant factor: an = (an/2 ) 2 if n is even and positive = (a(n-1)/2 ) 2 * a if n is odd and > 1 =a if n = 1 7
  • 8. Insertion Sort A decrease by one algorithm A bottom-up (iterative) solution A top-down (recursive) solution 8
  • 9. Insertion Sort: an Iterative Solution ALGORITHM InsertionSortIter(A[0..n-1]) //An iterative implementation of insertion sort //Input: An array A[0..n-1] of n orderable elements //Output: Array A[0..n-1] sorted in nondecreasing order for i 1 to n – 1 do // i: the index of the first element of the unsorted part. key = A[i] for j i – 1 to 0 do // j: the index of the sorted part of the array if (key< A[j]) //compare the key with each element in the sorted part A[j+1] A[j] else break A[j +1] key //insert the key to the sorted part of the array Efficiency? 9
  • 10. Insertion Sort: a Recursive Solution ALGORITHM InsertionSortRecur(A[0..n-1], n-1) //A recursive implementation of insertion sort //Input: An array A[0..n-1] of n orderable elements Index of the last element //Output: Array A[0..n-1] sorted in nondecreasing order if n > 1 InsertionSortRecur(A[0..n-1], n-2) Insert(A[0..n-1], n-1) //insert A[n-1] to A[0..n-2] Index of the element/key to be inserted. ALGORITHM Insert(A[0..m], m) //Insert A[m] to the sorted subarray A[0..m-1] of A[0..n-1] //Input: A subarray A[0..m] of A[0..n-1] //Output: Array A[0..m] sorted in nondecreasing order key = A[m] for j m – 1 to 0 do if (key< A[j]) A[j+1] A[j] Recurrence relation? else break A[j +1] key 10
  • 11. Exercises Design a recursive decrease-by-one algorithm for finding the position of the largest element in an array of n real numbers. Determine the time efficiency of this algorithm and compare it with that of the brute-force algorithm for the same problem. 11
  • 12. Graph Traversal Many problems require processing all graph vertices in a systematic fashion Graph traversal algorithms: Depth-first search Breadth-first search 12
  • 13. Some Terminologies Vertices and Edges Undirected and directed graphs Parents, children, and ancestors. Connected graphs A graph is said to be connected if for every pair of its vertices u and v there is a path from u to v. 13
  • 14. Graph Representation Adjacency matrix n x n boolean matrix if |V| is n. The element on the ith row and jth column is 1 if there’s an edge from ith vertex to the jth vertex; otherwise 0. The adjacency matrix of an undirected graph is symmetric. It takes |V| (comparisons) to figure out all the adjacent nodes of a certain node i. Adjacency linked lists A collection of linked lists, one for each vertex, that contain all the vertices adjacent to the list’s vertex. An example 14
  • 15. Depth-first search The idea traverse “deeper” whenever possible. On each iteration, the algorithm proceeds to an unvisited vertex that is adjacent to the one it is currently in. If there are more than more neighbors, break the tie by the alphabetic order of the vertices. When reaching a dead end ( a vertex with no adjacent unvisited vertices), the algorithm backs up one edge to the parent and tries to continue visiting unvisited vertices from there. The algorithm halts after backing up to the starting vertex, with the latter being a dead end. Similar to preorder tree traversals It’s convenient to use a stack to trace the operation of depth-first search. Push a vertex onto the stack when the vertex is reached for the first time. Pop a vertex off the stack when it becomes a dead end. An example 15
  • 16. Example – undirected graphs a b c d e f g h Depth-first traversal:Give the order in which the vertices were reached. abfegcdh 16
  • 17. Depth-first search (DFS) Pseudocode for Depth-first-search of graph G=(V,E) DFS(G) // Use depth-first to visit a graph, which might // contain multiple connected components. count 0 //visiting sequence number mark each vertex with 0 // (unvisited) for each vertex v∈ V do if v is marked with 0 //w has not been visited yet. dfs(v) dfs(v) //Use depth-first to visit a connected component starting //from vertex v. count count + 1 mark v with count //visit vertex v for each vertex w adjacent to v do if w is marked with 0 //w has not been visited yet. dfs(w) 17
  • 18. Types of edges Tree edges: edges comprising forest Back edges: edges to ancestor nodes Forward edges: edges to descendants (digraphs only) Cross edges: none of the above 18
  • 19. Example – directed graph a b c d e f g h Depth-first traversal: Give the order in which the vertices were reached. abfghecd 19
  • 20. Depth-first search: Notes DFS can be implemented with graphs represented as: Adjacency matrices: Θ(|V |2) Adjacency linked lists: Θ(|V |+|E| ) Applications: checking connectivity finding connected components 20
  • 21. Breadth-first search (BFS) The idea Traverse “wider” whenever possible. Discover all vertices at distance k from s (on level k) before discovering any vertices at distance k +1 (at level k+1) Similar to level-by-level tree traversals Instead of a stack, breadth-first uses a queue. 21
  • 22. Example – undirected graph a b c d e f g h Breadth-first traversal: abefgchd 22
  • 23. Breadth-first search algorithm BFS(G) count 0 mark each vertex with 0 bfs(v) for each vertex v∈ V do count count + 1 if v is marked with 0 mark v with count //visit v bfs(v) initialize queue with v //enqueue while queue is not empty do a front of queue //dequeue for each vertex w adjacent to a do if w is marked with 0 //w hasn’t been visited. count count + 1 mark w with count //visit w add w to the end of the queue //enqueue remove a from the front of the queue 23
  • 24. Example – directed graph a b c d e f g h Breadth-first traversal: abefghcd 24
  • 25. Breadth-first search: Notes BFS has same efficiency as DFS and can be implemented with graphs represented as: Adjacency matrices: Θ(|V |2) Adjacency linked lists: Θ(|V |+|E| ) Applications: checking connectivity finding connected components finding paths between two vertices with the smallest number of edges 25
  • 26. Topological Sorting Problem: Given a Directed Acyclic Graph(DAG) G = (V, E), find a linear ordering of all its vertices such that if G contains an edge (u, v), then u appears before v in the ordering. Example: Give an order of the courses so that the prerequisites are met. C4 C1 C3 Is the problem solvable if the digraph contains a cycle? C2 C5 26
  • 27. The DFS-Based Algorithm DFS-based algorithm: (2 orderings exist in the DFS) DFS traversal noting the order in which vertices are popped off stack (the order in which the dead end vertices appear) Reverse the above order. Questions Can we use the order in which vertices are pushed onto the DFS stack (instead of the order they are popped off it) to solve the topological sorting problem? Does it matter from which node we start? Θ(|V |+|E| ) using adjacency linked lists 27
  • 28. Example: Scheduling with Task Dependencies Task Number Depends Wake up 1 on Wake up 1 -- Dress 2 7,8 Make Make coffee 5 toast 6 Eat 3 5, 6 Shower 7 Choose breakfast clothes 8 Leave 4 2, 3 Eat Make 5 1 breakfast 3 coffee Dress 2 Make 6 1 toast Shower 7 1 Leave 4 Choose 8 1 clothes 28
  • 29. The Source Removal Algorithms Source removal algorithm Based on a direct implementation of the decrease-by-one techniques. Repeatedly identify and remove a source vertex, ie, a vertex that has no incoming edges, and delete it along with all the edges outgoing from it. 29
  • 30. Exercises Problem 1, Exercise 5.2 Problem 1, Exercise 5.3 Problem 5, Exercise 5.3 30