SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Refresher algebra-calculus
Refresher algebra-calculusRefresher algebra-calculus
Refresher algebra-calculus
Steve Nouri
 
21 4 ztransform
21 4 ztransform21 4 ztransform
21 4 ztransform
Mahyar Alzobaidy
 
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 11
Traian Rebedea
 
Backtracking
BacktrackingBacktracking
Backtracking
Vikas Sharma
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
Melaku Bayih Demessie
 
Average value by integral method
Average value by integral methodAverage value by integral method
Average value by integral method
Arun Umrao
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
Mohd Arif
 
01.02 linear equations
01.02 linear equations01.02 linear equations
01.02 linear equations
Andres Mendez-Vazquez
 
Unit v
Unit vUnit v
Unit v
mrecedu
 
Finite automata intro
Finite automata introFinite automata intro
Finite automata intro
lavishka_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_issues
Andres Mendez-Vazquez
 
Basic mathematics differentiation application
Basic mathematics differentiation applicationBasic mathematics differentiation application
Basic mathematics differentiation application
Muhammad Luthfan
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
ramya marichamy
 
CBSE Class 12 Mathematics formulas
CBSE Class 12 Mathematics formulasCBSE Class 12 Mathematics formulas
CBSE Class 12 Mathematics formulas
Parth Kshirsagar
 
Differential calculus
Differential calculusDifferential calculus
Differential calculus
Muthulakshmilakshmi2
 
Chap05alg
Chap05algChap05alg
Chap05alg
Munkhchimeg
 
Database systems-Formal relational query languages
Database systems-Formal relational query languagesDatabase systems-Formal relational query languages
Database systems-Formal relational query languages
jamunaashok
 
Differentiation
DifferentiationDifferentiation
Differentiation
guest39541b
 
21 3 ztransform
21 3 ztransform21 3 ztransform
21 3 ztransform
Mahyar Alzobaidy
 
Refresher algebra-calculus
Refresher algebra-calculusRefresher algebra-calculus
Refresher algebra-calculus
Steve 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 11
Traian Rebedea
 
Average value by integral method
Average value by integral methodAverage value by integral method
Average value by integral method
Arun Umrao
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
Mohd Arif
 
Finite automata intro
Finite automata introFinite automata intro
Finite automata intro
lavishka_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_issues
Andres Mendez-Vazquez
 
Basic mathematics differentiation application
Basic mathematics differentiation applicationBasic mathematics differentiation application
Basic mathematics differentiation application
Muhammad Luthfan
 
CBSE Class 12 Mathematics formulas
CBSE Class 12 Mathematics formulasCBSE Class 12 Mathematics formulas
CBSE Class 12 Mathematics formulas
Parth Kshirsagar
 
Database systems-Formal relational query languages
Database systems-Formal relational query languagesDatabase systems-Formal relational query languages
Database systems-Formal relational query languages
jamunaashok
 

Viewers also liked (9)

Chpt9 patternmatching
Chpt9 patternmatchingChpt9 patternmatching
Chpt9 patternmatching
dbhanumahesh
 
07 dc3
07 dc307 dc3
07 dc3
Hira Gul
 
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
Rai University
 
Depth firstsearchalgorithm
Depth firstsearchalgorithmDepth firstsearchalgorithm
Depth firstsearchalgorithm
hansa 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-11
sumitbardhan
 
Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffman
chidabdu
 
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
Siddhi Shrivas
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
chidabdu
 
Unit 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unit
chidabdu
 
Chpt9 patternmatching
Chpt9 patternmatchingChpt9 patternmatching
Chpt9 patternmatching
dbhanumahesh
 
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
Rai University
 
Depth firstsearchalgorithm
Depth firstsearchalgorithmDepth firstsearchalgorithm
Depth firstsearchalgorithm
hansa 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-11
sumitbardhan
 
Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffman
chidabdu
 
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
Siddhi Shrivas
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
chidabdu
 
Unit 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unit
chidabdu
 
Ad

Similar to Algorithm chapter 5 (20)

Algorithm review
Algorithm reviewAlgorithm review
Algorithm review
chidabdu
 
Review session2
Review session2Review session2
Review session2
NEEDY12345
 
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
Deepak John
 
Graphs
GraphsGraphs
Graphs
KomalPaliwal3
 
Sienna 5 decreaseandconquer
Sienna 5 decreaseandconquerSienna 5 decreaseandconquer
Sienna 5 decreaseandconquer
chidabdu
 
Function Basics Math Wiki
Function Basics   Math WikiFunction Basics   Math Wiki
Function Basics Math Wiki
Alec Kargodorian
 
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
appasami
 
Brute force
Brute forceBrute force
Brute force
Sadakathullah Appa College
 
Q
QQ
Q
guest9b2176
 
Module 2 Lesson 2 Notes
Module 2 Lesson 2 NotesModule 2 Lesson 2 Notes
Module 2 Lesson 2 Notes
toni dimella
 
L04 (1)
L04 (1)L04 (1)
L04 (1)
Allél Bouzid
 
Brute Force and Divide & Conquer Technique
Brute Force and Divide & Conquer TechniqueBrute Force and Divide & Conquer Technique
Brute Force and Divide & Conquer Technique
ssusered62011
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
giridaroori
 
New day 5 examples
New day 5 examplesNew day 5 examples
New day 5 examples
jchartiersjsd
 
Approx
ApproxApprox
Approx
guest0264d3b
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
chidabdu
 
Tower of Hanoi.ppt
Tower of Hanoi.pptTower of Hanoi.ppt
Tower of Hanoi.ppt
SACHINVERMA255386
 
Data Structures-Non Linear DataStructures-Graphs
Data Structures-Non Linear DataStructures-GraphsData Structures-Non Linear DataStructures-Graphs
Data Structures-Non Linear DataStructures-Graphs
sailaja156145
 
UNIT II - Graph Algorithms techniques.pptx
UNIT II - Graph Algorithms techniques.pptxUNIT II - Graph Algorithms techniques.pptx
UNIT II - Graph Algorithms techniques.pptx
mayakishore55
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
Sure Interview
 
Algorithm review
Algorithm reviewAlgorithm review
Algorithm review
chidabdu
 
Review session2
Review session2Review session2
Review session2
NEEDY12345
 
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
Deepak John
 
Sienna 5 decreaseandconquer
Sienna 5 decreaseandconquerSienna 5 decreaseandconquer
Sienna 5 decreaseandconquer
chidabdu
 
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
appasami
 
Module 2 Lesson 2 Notes
Module 2 Lesson 2 NotesModule 2 Lesson 2 Notes
Module 2 Lesson 2 Notes
toni dimella
 
Brute Force and Divide & Conquer Technique
Brute Force and Divide & Conquer TechniqueBrute Force and Divide & Conquer Technique
Brute Force and Divide & Conquer Technique
ssusered62011
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
giridaroori
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
chidabdu
 
Data Structures-Non Linear DataStructures-Graphs
Data Structures-Non Linear DataStructures-GraphsData Structures-Non Linear DataStructures-Graphs
Data Structures-Non Linear DataStructures-Graphs
sailaja156145
 
UNIT II - Graph Algorithms techniques.pptx
UNIT II - Graph Algorithms techniques.pptxUNIT II - Graph Algorithms techniques.pptx
UNIT II - Graph Algorithms techniques.pptx
mayakishore55
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
Sure Interview
 
Ad

More from chidabdu (20)

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

Recently uploaded (20)

Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 

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