SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
Heaps
Definition:
A heap is a binary tree with the following conditions:
  Shape requirement: it is essentially complete:
                            All its levels are full except possibly
                            the last level, where only some
                            rightmost leaves may be missing.
                      …
  Parental dominance requirement: The key at each
  node is ≥ keys(for max-heap) at its children
Examples

                                                                  1
Heaps and Heapsort
 Not only is the heap structure useful for heapsort,
 but it also makes an efficient priority queue.
 Heapsort
    In place
    O(nlogn)
 A priority queue is the ADT for maintaining a set S of
 elements, each with an associated value called a
 key/priority. It supports the following operations:
    find element with highest priority
    delete element with highest priority
    insert element with assigned priority


                                                       2
Properties of Heaps (1)
  Heap and its array representation.                           9
      Conceptually, we can think of a heap as
      a binary tree.                                   5               3
      But in practice, it is easier and more
      efficient to implement a heap using an
      array.                                      1        4       2
          Store the BFS traversal of the heap’s
          elements in position 1 through n,           1 2 3 4 5 6
          leaving H[0] unused.
  Relationships between indexes of                    9 5 3 1 4 2
  parents and children.
PARENT(i)               LEFT(i)         RIGHT(i)
return ⎣i/2⎦            return 2i       return 2i+1
                                                                           3
Properties of Heaps (2)
Max-heap property and min-heap property
   Max-heap: for every node other than root, A[PARENT(i)] >= A(i)
   Min-heap: for every node other than root, A[PARENT(i)] <= A(i)
The root has the largest key (for a max-heap)
The subtree rooted at any node of a heap is also a heap
Given a heap with n nodes, the height of the heap,
 h = log n .
- Height of a node: the number of edges on the longest simple
downward path from the node to a leaf.
- Height of a tree: the height of its root.
- level of a node: A node’s level + its height = h, the tree’s height.



                                                                         4
Bottom-up Heap construction
   Build an essentially complete binary tree by inserting n
   keys in the given order.

   Heapify a series of trees
     Starting with the last (rightmost) parental node, heapify/fix the
     subtree rooted at it: if the parental dominance condition does
     not hold for the key at this node:
      1.   exchange its key K with the key of its larger child
      2.   Heapify/fix the subtree rooted at it (now in the child’s position)
     Proceed to do the same for the node’s immediate predecessor.
     Stops after this is done for the tree’s root.
Example: 4 1 3 2 16 9 10 14 8 7                16 14 10 8 7 9 3 2 4 1

                                                                                5
Bottom-up heap construction algorithm(A
            Recursive version)
ALGORITHM HeapBottomUp(H[1..n])
//Constructs a heap from the elements                   Given a heap of n nodes, what’s
//of a given array by the bottom-up algorithm           the index of the last parent?
//Input: An array H[1..n] of orderable items
//Output: A heap H[1..n]                                 ⎣n/2⎦
for i   ⎣n/2⎦ downto 1 do
         MaxHeapify(H, i)      ALGORITHM MaxHeapify(H, i)
                               l     LEFT(i)
                               r     RIGHT(i)
                               if l <= n and H[l] > H[i] // if left child exists and > H[i]
                                  then largest   l
                                  else largest    i
                               if r <= n and H[r] > H[largest] // if R child exists and > H[largest]
                                  then largest   r
                               if largest ≠ i
                                  then exchange H[i]      H[largest] // heapify the subtree
                                          MaxHeapify(H, largest)
                                                                                             6
Bottom-up heap construction algorithm(An
           Iterative version)




                          // from the last parent down to 1, heapify the subtree rooted at i
                // k: the root of the subtree to be heapified; v: the key of the root


                                           // if not a heap yet and the left child exists




                                                     // find the larger child, j: its index.
                // if the key of the root > that of the larger child, done.


                                        // exchange the key with the key of the larger child
     // again, k: the root of the subtree to be heapified; v: the key of the root


                                                                                         7
Worst-Case Efficiency
 Worst case:
 a full tree; each key on a certain level will travel to the leaf.
     Fix a subtree rooted at height j: 2j comparisons
     Fix a subtree rooted at level i : 2(h-i) comparisons
        A node’s level + its height = h, the tree’s height.
    Total for heap construction phase:

         h-1

        Σ 2(h-i) 2
        i=0
                     i    = 2 ( n – lg (n + 1)) = Θ(n)

                         # nodes at level i

                                                                     8
Bottom-up vs. Top-down Heap Construction


     Bottom-up: Put everything in the array
     and then heapify/fix the trees in a
     bottom-up way.
     Top-down: Heaps can be constructed
     by successively inserting elements (see
     the next slide) into an (initially) empty
     heap.

                                             9
Insertion of a New Element
The algorithm
   Insert element at the last position in heap.
   Compare with its parent, and exchange them if it violates the parental
   dominance condition.
   Continue comparing the new element with nodes up the tree until the
   parental dominance condition is satisfied.
Example 1: add 10 to a heap: 9 6 8 2 5 7
Efficiency:   h ∈ O(logn)
 Inserting one new element to a heap with n-1 nodes requires no more
    comparisons than the heap’s height
Example 2: Use the top-down method to build a heap for numbers 2 9 7 6 5 8
Questions
   What is the efficiency for a top-down heap construction algorithm for a heap
   of size n?
   Which one is better, a bottom-up or a top-down heap construction?
                                                                            10
Root Deletion
The root of a heap can be deleted and the heap
   fixed up as follows:
1. Exchange the root with the last leaf
2. Decrease the heap’s size by 1
3. Heapify the smaller tree in exactly the same
   way we did it in MaxHeapify().

                        It can’t make key comparison more
Efficiency: 2h ∈Θ(logn) than twice the heap’s height
Example: 9 8 6 2 5 1
                                                       11
Heapsort Algorithm
 The algorithm
   (Heap construction) Build heap for a given
   array (either bottom-up or top-down)
   (Maximum deletion ) Apply the root-
   deletion operation n-1 times to the
   remaining heap until heap contains just
   one node.
 An example: 2 9 7 6 5 8

                                          12
Analysis of Heapsort
    Recall algorithm:
Θ(n)        1.   Bottom-up heap construction
Θ(log n)    2.   Root deletion

            Repeat 2 until heap contains just one node.

   n – 1 times
    Total: Θ(n) + Θ( n log n) = Θ(n log n)

  • Note: this is the worst case. Average case also Θ(n log n).

                                                                  13
Problem Reduction
Problem Reduction
   If you need to solve a problem, reduce it to another problem that you
   know how to solve.
Linear programming
   A problem of optimizing a linear function of several variables subject to
   constraints in the form of linear equations and linear inequalities.
   Formally,
    Maximize(or minimize) c1x1+ …Cnxn
    Subject to ai1x1+…+ ainxn ≤ (or ≥ or =) bi, for i=1…n
                      x1 ≥ 0, …, xn ≥ 0
Reduction to graph problems



                                                                        14
Linear Programming—Example 1:
    Investment Problem
Scenario
  A university endowment needs to invest $100million
  Three types of investment:
     Stocks (expected interest: 10%)
     Bonds (expected interest: 7%)
     Cash (expected interest: 3%)
Constraints
  The investment in stocks is no more than 1/3 of the money
  invested in bonds
  At least 25% of the total amount invested in stocks and
  bonds must be invested in cash
Objective:
  An investment that maximizes the return
                                                              15
Example 1 (cont’)
 Maximize 0.10x + 0.07y + 0.03z
 subject to x + y + z = 100
           x ≤(1/3)y
           z ≥ 0.25(x + y)
           x ≥ 0, y ≥ 0, z ≥ 0



                                  16
Linear Programming—Example 2 :
    Election Problem
                                           Objective:
Scenario:
  A politician that tries to win an          Figure out the minimum
  election.                                 amount of money that you
  Three types of areas of the district:     need to spend in order to
                                            win
     urban (100,000 voters),
     suburban (200,000 voters), and                 50,000 urban votes
     rural(50,000 voters).                          100,000 suburban votes
  Primary issues:                                   25,000 rural votes
     Building more roads                   constraints:
     Gun control
                         Policy             Urban     Suburban     rural
     Farm subsidies
     Gasoline tax        Build roads        -2        5            3

  Advertisement fee       Gun control       8         2            -5
     For every $1,000…    Farm subsidies    0         0            10
                          Gasoline tax      10        0            -2      17
Example 2 (cont’)
x: the number of thousand of dollars spent on advertising on
    building roads
y: the number of thousand of dollars spent on advertising on gun
    control
z: the number of thousand of dollars spent on advertising on farm
    subsidies
w: the number of thousand of dollars spent on advertising on
    gasoline taxes
   Maximize x + y + z + w
   subject to –2x + 8y + 0z + 10w ≥ 50
                5x + 2y + 0z + 0w ≥ 100
                3x – 5y + 10z - 2w ≥ 25
                x, y, z, w ≥ 0
                                                              18
Linear Programming—Example 3: Knapsack
Problem (Continuous/Fraction Version)


Scenario
Given n items:
   weights: w1 w2 … wn
   values: v1 v2 … vn
   a knapsack of capacity W
Constraints
  Any fraction of any item can be put into the knapsack.
  All the items must fit into the knapsack.
Objective:
  Find the most valuable subset of the items


                                                           19
Example 3 (cont’)
 Maximize     n

              ∑v x
              j =1
                     j       j



 subject to   n

              ∑w x
              j =1
                         j       j   ≤W

         0 ≤ xj ≤ 1 for j = 1,…, n.




                                          20
Linear Programming—Example 3: Knapsack
Problem (Discrete Version)


Scenario
Given n items:
   weights: w1 w2 … wn
   values: v1 v2 … vn
   a knapsack of capacity W
Constraints
  an item can either be put into the knapsack in its entirely or
  not be put into the knapsack.
  All the items must fit into the knapsack.
Objective:
  Find the most valuable subset of the items

                                                                   21
Example 3 (cont’)
 Maximize     n

              ∑v x
              j =1
                     j       j



 subject to   n

              ∑w x
              j =1
                         j       j   ≤W

         xj ∈ {0,1} for j = 1,…, n.




                                          22
Algorithms for Linear Programming
Simplex algorithm: exponential time.
Ellipsoid algorithm: polynomial time.
Interior-point methods: polynomial time.

Integer linear programming problem
  no polynomial solution.
  requires the variables to be integers.

                                           23
Reduction to Graph Problems
 River-crossing puzzle
 Star Gazing




                          24

Contenu connexe

Tendances

Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonPriyankaC44
 
Presentation - Bi-directional A-star search
Presentation - Bi-directional A-star searchPresentation - Bi-directional A-star search
Presentation - Bi-directional A-star searchMohammad Saiful Islam
 
Little o and little omega
Little o and little omegaLittle o and little omega
Little o and little omegaRajesh K Shukla
 
Perceptron (neural network)
Perceptron (neural network)Perceptron (neural network)
Perceptron (neural network)EdutechLearners
 
R Programming: Introduction To R Packages
R Programming: Introduction To R PackagesR Programming: Introduction To R Packages
R Programming: Introduction To R PackagesRsquared Academy
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notationsNikhil Sharma
 
Constraint satisfaction problems (csp)
Constraint satisfaction problems (csp)   Constraint satisfaction problems (csp)
Constraint satisfaction problems (csp) Archana432045
 
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.Niraj Bharambe
 
Branch and bound method
Branch and bound methodBranch and bound method
Branch and bound methodVidhyaSenthil
 
TOC 1 | Introduction to Theory of Computation
TOC 1 | Introduction to Theory of ComputationTOC 1 | Introduction to Theory of Computation
TOC 1 | Introduction to Theory of ComputationMohammad Imam Hossain
 
Finite automata(For college Seminars)
Finite automata(For college Seminars)Finite automata(For college Seminars)
Finite automata(For college Seminars)Naman Joshi
 

Tendances (20)

Heaps
HeapsHeaps
Heaps
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
 
Brute force
Brute forceBrute force
Brute force
 
Data Structures & Algorithm design using C
Data Structures & Algorithm design using C Data Structures & Algorithm design using C
Data Structures & Algorithm design using C
 
P versus NP
P versus NPP versus NP
P versus NP
 
Presentation - Bi-directional A-star search
Presentation - Bi-directional A-star searchPresentation - Bi-directional A-star search
Presentation - Bi-directional A-star search
 
Little o and little omega
Little o and little omegaLittle o and little omega
Little o and little omega
 
Approximation Algorithms
Approximation AlgorithmsApproximation Algorithms
Approximation Algorithms
 
TOC 5 | Regular Expressions
TOC 5 | Regular ExpressionsTOC 5 | Regular Expressions
TOC 5 | Regular Expressions
 
Introduction to MPI
Introduction to MPIIntroduction to MPI
Introduction to MPI
 
Linux vs windows
Linux vs windowsLinux vs windows
Linux vs windows
 
Perceptron (neural network)
Perceptron (neural network)Perceptron (neural network)
Perceptron (neural network)
 
R Programming: Introduction To R Packages
R Programming: Introduction To R PackagesR Programming: Introduction To R Packages
R Programming: Introduction To R Packages
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
 
Constraint satisfaction problems (csp)
Constraint satisfaction problems (csp)   Constraint satisfaction problems (csp)
Constraint satisfaction problems (csp)
 
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
 
Branch and bound method
Branch and bound methodBranch and bound method
Branch and bound method
 
TOC 1 | Introduction to Theory of Computation
TOC 1 | Introduction to Theory of ComputationTOC 1 | Introduction to Theory of Computation
TOC 1 | Introduction to Theory of Computation
 
Finite automata(For college Seminars)
Finite automata(For college Seminars)Finite automata(For college Seminars)
Finite automata(For college Seminars)
 

En vedette (14)

Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1
 
Appendix a 2
Appendix a 2Appendix a 2
Appendix a 2
 
Sorting
SortingSorting
Sorting
 
Heapsort
HeapsortHeapsort
Heapsort
 
Heap property
Heap propertyHeap property
Heap property
 
HeapSort
HeapSortHeapSort
HeapSort
 
Heap
HeapHeap
Heap
 
Heapsort
HeapsortHeapsort
Heapsort
 
Heaps
HeapsHeaps
Heaps
 
Heapify
HeapifyHeapify
Heapify
 
chapter - 6.ppt
chapter - 6.pptchapter - 6.ppt
chapter - 6.ppt
 
Heap sort
Heap sort Heap sort
Heap sort
 
Heap sort
Heap sortHeap sort
Heap sort
 
Heap sort
Heap sortHeap sort
Heap sort
 

Similaire à Algorithm chapter 6

05 heap 20161110_jintaeks
05 heap 20161110_jintaeks05 heap 20161110_jintaeks
05 heap 20161110_jintaeksJinTaek Seo
 
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdfCS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdfssuser034ce1
 
358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12sumitbardhan
 
lecture 5
lecture 5lecture 5
lecture 5sajinsc
 
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic ProgammingAlgorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic ProgammingTraian Rebedea
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).pptSudhaPatel11
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).pptAmitShou
 
heap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithmsheap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithmsssuser7319f8
 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heapschidabdu
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Anand Ingle
 

Similaire à Algorithm chapter 6 (20)

05 heap 20161110_jintaeks
05 heap 20161110_jintaeks05 heap 20161110_jintaeks
05 heap 20161110_jintaeks
 
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdfCS-102 BT_24_3_14 Binary Tree Lectures.pdf
CS-102 BT_24_3_14 Binary Tree Lectures.pdf
 
Unit III Heaps.ppt
Unit III Heaps.pptUnit III Heaps.ppt
Unit III Heaps.ppt
 
Heaps
HeapsHeaps
Heaps
 
358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12358 33 powerpoint-slides_12-heaps_chapter-12
358 33 powerpoint-slides_12-heaps_chapter-12
 
chapt11.ppt
chapt11.pptchapt11.ppt
chapt11.ppt
 
Leftlist Heap-1.pdf
Leftlist Heap-1.pdfLeftlist Heap-1.pdf
Leftlist Heap-1.pdf
 
Heap tree
Heap treeHeap tree
Heap tree
 
lecture 5
lecture 5lecture 5
lecture 5
 
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic ProgammingAlgorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
 
Chapter 10 ds
Chapter 10 dsChapter 10 ds
Chapter 10 ds
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).ppt
 
heaps2
heaps2heaps2
heaps2
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).ppt
 
Heap Sort (project).ppt
Heap Sort (project).pptHeap Sort (project).ppt
Heap Sort (project).ppt
 
heap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithmsheap sort in the design anad analysis of algorithms
heap sort in the design anad analysis of algorithms
 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heaps
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure
 
Algorithm Exam Help
Algorithm Exam HelpAlgorithm Exam Help
Algorithm Exam Help
 
Review
ReviewReview
Review
 

Plus de chidabdu

Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffmanchidabdu
 
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 6 bst
Sienna 6 bstSienna 6 bst
Sienna 6 bstchidabdu
 
Sienna 5 decreaseandconquer
Sienna 5 decreaseandconquerSienna 5 decreaseandconquer
Sienna 5 decreaseandconquerchidabdu
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquerchidabdu
 
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 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unitchidabdu
 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organizationchidabdu
 
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 5
Algorithm chapter 5Algorithm chapter 5
Algorithm chapter 5chidabdu
 

Plus de chidabdu (20)

Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffman
 
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 6 bst
Sienna 6 bstSienna 6 bst
Sienna 6 bst
 
Sienna 5 decreaseandconquer
Sienna 5 decreaseandconquerSienna 5 decreaseandconquer
Sienna 5 decreaseandconquer
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
 
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 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unit
 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organization
 
Algorithm chapter 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 5
Algorithm chapter 5Algorithm chapter 5
Algorithm chapter 5
 

Dernier

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingSelcen Ozturkcan
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 

Dernier (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 

Algorithm chapter 6

  • 1. Heaps Definition: A heap is a binary tree with the following conditions: Shape requirement: it is essentially complete: All its levels are full except possibly the last level, where only some rightmost leaves may be missing. … Parental dominance requirement: The key at each node is ≥ keys(for max-heap) at its children Examples 1
  • 2. Heaps and Heapsort Not only is the heap structure useful for heapsort, but it also makes an efficient priority queue. Heapsort In place O(nlogn) A priority queue is the ADT for maintaining a set S of elements, each with an associated value called a key/priority. It supports the following operations: find element with highest priority delete element with highest priority insert element with assigned priority 2
  • 3. Properties of Heaps (1) Heap and its array representation. 9 Conceptually, we can think of a heap as a binary tree. 5 3 But in practice, it is easier and more efficient to implement a heap using an array. 1 4 2 Store the BFS traversal of the heap’s elements in position 1 through n, 1 2 3 4 5 6 leaving H[0] unused. Relationships between indexes of 9 5 3 1 4 2 parents and children. PARENT(i) LEFT(i) RIGHT(i) return ⎣i/2⎦ return 2i return 2i+1 3
  • 4. Properties of Heaps (2) Max-heap property and min-heap property Max-heap: for every node other than root, A[PARENT(i)] >= A(i) Min-heap: for every node other than root, A[PARENT(i)] <= A(i) The root has the largest key (for a max-heap) The subtree rooted at any node of a heap is also a heap Given a heap with n nodes, the height of the heap, h = log n . - Height of a node: the number of edges on the longest simple downward path from the node to a leaf. - Height of a tree: the height of its root. - level of a node: A node’s level + its height = h, the tree’s height. 4
  • 5. Bottom-up Heap construction Build an essentially complete binary tree by inserting n keys in the given order. Heapify a series of trees Starting with the last (rightmost) parental node, heapify/fix the subtree rooted at it: if the parental dominance condition does not hold for the key at this node: 1. exchange its key K with the key of its larger child 2. Heapify/fix the subtree rooted at it (now in the child’s position) Proceed to do the same for the node’s immediate predecessor. Stops after this is done for the tree’s root. Example: 4 1 3 2 16 9 10 14 8 7 16 14 10 8 7 9 3 2 4 1 5
  • 6. Bottom-up heap construction algorithm(A Recursive version) ALGORITHM HeapBottomUp(H[1..n]) //Constructs a heap from the elements Given a heap of n nodes, what’s //of a given array by the bottom-up algorithm the index of the last parent? //Input: An array H[1..n] of orderable items //Output: A heap H[1..n] ⎣n/2⎦ for i ⎣n/2⎦ downto 1 do MaxHeapify(H, i) ALGORITHM MaxHeapify(H, i) l LEFT(i) r RIGHT(i) if l <= n and H[l] > H[i] // if left child exists and > H[i] then largest l else largest i if r <= n and H[r] > H[largest] // if R child exists and > H[largest] then largest r if largest ≠ i then exchange H[i] H[largest] // heapify the subtree MaxHeapify(H, largest) 6
  • 7. Bottom-up heap construction algorithm(An Iterative version) // from the last parent down to 1, heapify the subtree rooted at i // k: the root of the subtree to be heapified; v: the key of the root // if not a heap yet and the left child exists // find the larger child, j: its index. // if the key of the root > that of the larger child, done. // exchange the key with the key of the larger child // again, k: the root of the subtree to be heapified; v: the key of the root 7
  • 8. Worst-Case Efficiency Worst case: a full tree; each key on a certain level will travel to the leaf. Fix a subtree rooted at height j: 2j comparisons Fix a subtree rooted at level i : 2(h-i) comparisons A node’s level + its height = h, the tree’s height. Total for heap construction phase: h-1 Σ 2(h-i) 2 i=0 i = 2 ( n – lg (n + 1)) = Θ(n) # nodes at level i 8
  • 9. Bottom-up vs. Top-down Heap Construction Bottom-up: Put everything in the array and then heapify/fix the trees in a bottom-up way. Top-down: Heaps can be constructed by successively inserting elements (see the next slide) into an (initially) empty heap. 9
  • 10. Insertion of a New Element The algorithm Insert element at the last position in heap. Compare with its parent, and exchange them if it violates the parental dominance condition. Continue comparing the new element with nodes up the tree until the parental dominance condition is satisfied. Example 1: add 10 to a heap: 9 6 8 2 5 7 Efficiency: h ∈ O(logn) Inserting one new element to a heap with n-1 nodes requires no more comparisons than the heap’s height Example 2: Use the top-down method to build a heap for numbers 2 9 7 6 5 8 Questions What is the efficiency for a top-down heap construction algorithm for a heap of size n? Which one is better, a bottom-up or a top-down heap construction? 10
  • 11. Root Deletion The root of a heap can be deleted and the heap fixed up as follows: 1. Exchange the root with the last leaf 2. Decrease the heap’s size by 1 3. Heapify the smaller tree in exactly the same way we did it in MaxHeapify(). It can’t make key comparison more Efficiency: 2h ∈Θ(logn) than twice the heap’s height Example: 9 8 6 2 5 1 11
  • 12. Heapsort Algorithm The algorithm (Heap construction) Build heap for a given array (either bottom-up or top-down) (Maximum deletion ) Apply the root- deletion operation n-1 times to the remaining heap until heap contains just one node. An example: 2 9 7 6 5 8 12
  • 13. Analysis of Heapsort Recall algorithm: Θ(n) 1. Bottom-up heap construction Θ(log n) 2. Root deletion Repeat 2 until heap contains just one node. n – 1 times Total: Θ(n) + Θ( n log n) = Θ(n log n) • Note: this is the worst case. Average case also Θ(n log n). 13
  • 14. Problem Reduction Problem Reduction If you need to solve a problem, reduce it to another problem that you know how to solve. Linear programming A problem of optimizing a linear function of several variables subject to constraints in the form of linear equations and linear inequalities. Formally, Maximize(or minimize) c1x1+ …Cnxn Subject to ai1x1+…+ ainxn ≤ (or ≥ or =) bi, for i=1…n x1 ≥ 0, …, xn ≥ 0 Reduction to graph problems 14
  • 15. Linear Programming—Example 1: Investment Problem Scenario A university endowment needs to invest $100million Three types of investment: Stocks (expected interest: 10%) Bonds (expected interest: 7%) Cash (expected interest: 3%) Constraints The investment in stocks is no more than 1/3 of the money invested in bonds At least 25% of the total amount invested in stocks and bonds must be invested in cash Objective: An investment that maximizes the return 15
  • 16. Example 1 (cont’) Maximize 0.10x + 0.07y + 0.03z subject to x + y + z = 100 x ≤(1/3)y z ≥ 0.25(x + y) x ≥ 0, y ≥ 0, z ≥ 0 16
  • 17. Linear Programming—Example 2 : Election Problem Objective: Scenario: A politician that tries to win an Figure out the minimum election. amount of money that you Three types of areas of the district: need to spend in order to win urban (100,000 voters), suburban (200,000 voters), and 50,000 urban votes rural(50,000 voters). 100,000 suburban votes Primary issues: 25,000 rural votes Building more roads constraints: Gun control Policy Urban Suburban rural Farm subsidies Gasoline tax Build roads -2 5 3 Advertisement fee Gun control 8 2 -5 For every $1,000… Farm subsidies 0 0 10 Gasoline tax 10 0 -2 17
  • 18. Example 2 (cont’) x: the number of thousand of dollars spent on advertising on building roads y: the number of thousand of dollars spent on advertising on gun control z: the number of thousand of dollars spent on advertising on farm subsidies w: the number of thousand of dollars spent on advertising on gasoline taxes Maximize x + y + z + w subject to –2x + 8y + 0z + 10w ≥ 50 5x + 2y + 0z + 0w ≥ 100 3x – 5y + 10z - 2w ≥ 25 x, y, z, w ≥ 0 18
  • 19. Linear Programming—Example 3: Knapsack Problem (Continuous/Fraction Version) Scenario Given n items: weights: w1 w2 … wn values: v1 v2 … vn a knapsack of capacity W Constraints Any fraction of any item can be put into the knapsack. All the items must fit into the knapsack. Objective: Find the most valuable subset of the items 19
  • 20. Example 3 (cont’) Maximize n ∑v x j =1 j j subject to n ∑w x j =1 j j ≤W 0 ≤ xj ≤ 1 for j = 1,…, n. 20
  • 21. Linear Programming—Example 3: Knapsack Problem (Discrete Version) Scenario Given n items: weights: w1 w2 … wn values: v1 v2 … vn a knapsack of capacity W Constraints an item can either be put into the knapsack in its entirely or not be put into the knapsack. All the items must fit into the knapsack. Objective: Find the most valuable subset of the items 21
  • 22. Example 3 (cont’) Maximize n ∑v x j =1 j j subject to n ∑w x j =1 j j ≤W xj ∈ {0,1} for j = 1,…, n. 22
  • 23. Algorithms for Linear Programming Simplex algorithm: exponential time. Ellipsoid algorithm: polynomial time. Interior-point methods: polynomial time. Integer linear programming problem no polynomial solution. requires the variables to be integers. 23
  • 24. Reduction to Graph Problems River-crossing puzzle Star Gazing 24