SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Deep Semi-supervised Learning methods
Deep Semi-supervised Learning methodsDeep Semi-supervised Learning methods
Deep Semi-supervised Learning methodsPrincy Joy
 
Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Treekhabbab_h
 
Scikit Learn intro
Scikit Learn introScikit Learn intro
Scikit Learn intro9xdot
 
Recurrent Neural Networks (RNN) | RNN LSTM | Deep Learning Tutorial | Tensorf...
Recurrent Neural Networks (RNN) | RNN LSTM | Deep Learning Tutorial | Tensorf...Recurrent Neural Networks (RNN) | RNN LSTM | Deep Learning Tutorial | Tensorf...
Recurrent Neural Networks (RNN) | RNN LSTM | Deep Learning Tutorial | Tensorf...Edureka!
 
Heap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap AlgorithmHeap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap AlgorithmLearning Courses Online
 
Ingesting streaming data into Graph Database
Ingesting streaming data into Graph DatabaseIngesting streaming data into Graph Database
Ingesting streaming data into Graph DatabaseGuido Schmutz
 
Hashing in datastructure
Hashing in datastructureHashing in datastructure
Hashing in datastructurerajshreemuthiah
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic ProgrammingSahil Kumar
 
Intro to deep learning
Intro to deep learning Intro to deep learning
Intro to deep learning David Voyles
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptSeethaDinesh
 
Deep Learning - Convolutional Neural Networks
Deep Learning - Convolutional Neural NetworksDeep Learning - Convolutional Neural Networks
Deep Learning - Convolutional Neural NetworksChristian Perone
 
R Programming language model test paper
R Programming language model test paperR Programming language model test paper
R Programming language model test paperLuckshay Batra
 
Understanding Feature Space in Machine Learning
Understanding Feature Space in Machine LearningUnderstanding Feature Space in Machine Learning
Understanding Feature Space in Machine LearningAlice Zheng
 
All pair shortest path
All pair shortest pathAll pair shortest path
All pair shortest pathArafat Hossan
 

Was ist angesagt? (20)

Deep Semi-supervised Learning methods
Deep Semi-supervised Learning methodsDeep Semi-supervised Learning methods
Deep Semi-supervised Learning methods
 
lec6
lec6lec6
lec6
 
Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Tree
 
deep learning
deep learningdeep learning
deep learning
 
Scikit Learn intro
Scikit Learn introScikit Learn intro
Scikit Learn intro
 
Recurrent Neural Networks (RNN) | RNN LSTM | Deep Learning Tutorial | Tensorf...
Recurrent Neural Networks (RNN) | RNN LSTM | Deep Learning Tutorial | Tensorf...Recurrent Neural Networks (RNN) | RNN LSTM | Deep Learning Tutorial | Tensorf...
Recurrent Neural Networks (RNN) | RNN LSTM | Deep Learning Tutorial | Tensorf...
 
Heap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap AlgorithmHeap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap Algorithm
 
Data partitioning
Data partitioningData partitioning
Data partitioning
 
Ingesting streaming data into Graph Database
Ingesting streaming data into Graph DatabaseIngesting streaming data into Graph Database
Ingesting streaming data into Graph Database
 
Hashing in datastructure
Hashing in datastructureHashing in datastructure
Hashing in datastructure
 
Dynamic Programming
Dynamic ProgrammingDynamic Programming
Dynamic Programming
 
Intro to deep learning
Intro to deep learning Intro to deep learning
Intro to deep learning
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
 
Big data and Hadoop
Big data and HadoopBig data and Hadoop
Big data and Hadoop
 
Deep Learning - Convolutional Neural Networks
Deep Learning - Convolutional Neural NetworksDeep Learning - Convolutional Neural Networks
Deep Learning - Convolutional Neural Networks
 
R Programming language model test paper
R Programming language model test paperR Programming language model test paper
R Programming language model test paper
 
Understanding Feature Space in Machine Learning
Understanding Feature Space in Machine LearningUnderstanding Feature Space in Machine Learning
Understanding Feature Space in Machine Learning
 
The Evolution of Apache Kylin
The Evolution of Apache KylinThe Evolution of Apache Kylin
The Evolution of Apache Kylin
 
All pair shortest path
All pair shortest pathAll pair shortest path
All pair shortest path
 
RNN-LSTM.pptx
RNN-LSTM.pptxRNN-LSTM.pptx
RNN-LSTM.pptx
 

Andere mochten auch (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
 
Heaps
HeapsHeaps
Heaps
 
Heapsort
HeapsortHeapsort
Heapsort
 
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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Kürzlich hochgeladen (20)

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

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