Binary Heaps and Heapsort
|
|
|
- Anis Pope
- 9 years ago
- Views:
Transcription
1 CPSC 259: Data Structures and Algorithms for Electrical Engineers Binary Heaps and Heapsort Textbook Reference: Thareja first edition: Chapter 12, pages Thareja second edition: Chapter 12, pages Hassan Khosravi CPSC 259 Binary Heaps and Heapsort Page 1
2 Learning Goals Provide examples of appropriate applications for priority queues and heaps. Implement and manipulate a heap using an array as the underlying data structure. Describe and use the Heapify ( Build Heap ) and Heapsort algorithms. Analyze the complexity of operations on a heap. CPSC 259 Binary Heaps and Heapsort Page 2
3 CPSC 259 Administrative Notes MT2 on Friday See course website for details covers all of the course material up to and including what we cover today No Lecture on Wednesday No labs this week. Quiz 3 Marks are released PeerWise grades for second call are posted PeerWise: Third and final call ends Dec 4 th. CPSC 259 Binary Heaps and Heapsort Page 3
4 CPSC 259 Journey Abstract Data Types Priority Queue Tools Pointers Dynamic Memory Alloca2on Stack Queue Dictionary Asymptotic Analysis Recursion Linked list Circular Array Array Heapsort Binary Heap Data Structures Binary Search Tree Algorithms CPSC 259 Binary Trees Page 4
5 Priority Queues Let s say we have the following tasks. 2 - Water plants 5 - Order cleaning supplies 1 - Clean coffee maker 3 - Empty trash 9 - Fix overflowing sink 2 - Shampoo carpets 4 - Replace light bulb 1 - Remove pencil sharpener shavings We are interested in finding the task with the highest priority quickly. CPSC 259 Binary Heaps and Heapsort Page 5
6 Priority Queues A collection organized so as to permit fast access to and removal of the largest/smallest element Prioritization is a weaker condition than ordering. Order of insertion is irrelevant. Element with the highest priority (whatever that means) comes out next. Not really a queue: not a FIFO CPSC 259 Binary Heaps and Heapsort Page 6
7 Priority Queue ADT Priority Queue operations create destroy insert deletemin isempty G(9) insert F(7) E(5) D(100) A(4) B(6) deletemin C(3) Priority Queue property: for two elements in the queue, x and y, if x has a lower priority value than y, x will be deleted before y. CPSC 259 Binary Heaps and Heapsort Page 7
8 Heaps and Priority Queues A priority queue is an abstract data type (ADT) that maintains a bag of items. What is the difference between a set and a bag? A set does not contain duplicates. Two or more distinct items in a priority queue can have the same priority. If all items have the same priority, you might think a priority queue should behave like a queue, but it may not. We ll see why, shortly. A binary heap can implement a priority queue, efficiently. CPSC 259 Binary Heaps and Heapsort Page 8
9 Applications of the Priority Q Hold jobs for a printer in order of length Manage limited resources such as bandwidth on a transmission line from a network router Simulate events (simulation time used as the priority) Sort numbers Anything greedy: an algorithm that makes the locally best choice at each step CPSC 259 Binary Heaps and Heapsort Page 9
10 Naïve Priority Q Data Structures Let s use an unsorted list (could be implemented with either an Array or Linked List) Running time of insert? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 10
11 Naïve Priority Q Data Structures Let s use an unsorted list (could be implemented with either an Array or Linked List) Running time of insert? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 11
12 Naïve Priority Q Data Structures Let s use an unsorted list (could be implemented with either an Array or Linked List) Running time of deletemin? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 12
13 Naïve Priority Q Data Structures Let s use an unsorted list (could be implemented with either an Array or Linked List) Running time of deletemin? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 13
14 Naïve Priority Q Data Structures Let s use a sorted list (could be implemented with either an Array or Linked List) Running time of insert? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 14
15 Naïve Priority Q Data Structures Let s use a sorted list (could be implemented with either an Array or Linked List) Running time of insert? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 15
16 Naïve Priority Q Data Structures Let s use a sorted list (could be implemented with either an Array or Linked List) Running time of deletemin? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 16
17 Naïve Priority Q Data Structures Let s use a sorted list (could be implemented with either an Array or Linked List) Running time of deletemin? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 17
18 Naïve Priority Q Data Structures Let s use a Binary Search Tree (could be implemented with either an Array or Linked List) Worst case running time of insert? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 18
19 Naïve Priority Q Data Structures Let s use a Binary Search Tree (could be implemented with either an Array or Linked List) Worst case running time of insert? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 19
20 Naïve Priority Q Data Structures Let s use a Binary Search Tree (could be implemented with either an Array or Linked List) Worst case running time of deletemin? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 20
21 Naïve Priority Q Data Structures Let s use a Binary Search Tree (could be implemented with either an Array or Linked List) Worst case running time of deletemin? a. O(1) b. O(lg n) c. O(n) d. O(n lg n) e. Something else CPSC 259 Binary Heaps and Heapsort Page 21
22 Naïve Priority Q Data Structures (Summary) Data Structure Insert (worst case) Unsorted lists O(1) O(n) Sorted lists O(n) O(1) Binary Search Trees O(n) O(n) Binary Heaps O(lg n) O(lg n) deletemin (worst case) CPSC 259 Binary Heaps and Heapsort Page 22
23 The heap property A node has the heap property if the priority of the node is as high as or higher than the priority of its children Red node has heap property 8 12 Red node has heap property 8 14 Red node does not have heap property All leaf nodes automatically have the heap property. A binary tree is a heap if all nodes in it have the heap property. CPSC 259 Binary Heaps and Heapsort Page 23
24 Percolate-up Given a node that does not have the heap property, you can give it the heap property by exchanging its value with the value of the child with the higher priority Red node does not have heap property 8 12 Red node has heap property This is sometimes called Percolate-up (sifting up). Notice that the child may have lost the heap property. CPSC 259 Binary Heaps and Heapsort Page 24
25 Binary Heap Priority Q Data Structure Heap-order property parent s key is less than or equal to children s keys result: minimum is always at the top Structure property nearly complete tree CPSC 259 Binary Heaps and Heapsort Page depth is always O(log n); next open loca2on always known WARNING: this has NO SIMILARITY to the heap you hear about when people say objects you create with new go on the heap
26 It is important to realize that two binary heaps can contain the same data but the data may appear in different positions in the heap: Both of the minimum binary heaps above contain the same data: 2, 5, 5, 7, 7, and 8. Even though both heaps satisfy all the properties necessary of a minimum binary heap, the data is stored in different positions in the tree. CPSC 259 Binary Heaps and Heapsort Page 26
27 Min-heap and Max-heap (There s also a maximum binary heap, where parent each child simply changes to parent each child.) Min-heap Max-heap CPSC 259 Binary Heaps and Heapsort Page 27
28 Constructing a heap I (Naïve approach) A tree consisting of a single node is automatically a heap. We construct a heap by adding nodes one at a time: Add the node just to the right of the rightmost node in the deepest level. If the deepest level is full, start a new level with the leftmost position. Examples: Add a new node here Add a new node here CPSC 259 Binary Heaps and Heapsort Page 28
29 Constructing a heap II (Naïve approach) Each time we add a node, we may destroy the heap property of its parent node. To fix this, we percolate-up. But each time we percolate-up, the value of the topmost node in the sift may increase, and this may destroy the heap property of its parent node. We repeat the percolate-up process, moving up in the tree, until either: we reach nodes whose values don t need to be swapped (because the parent is still larger than both children), or we reach the root CPSC 259 Binary Heaps and Heapsort Page 29
30 Constructing a heap III (Naïve approach) CPSC 259 Binary Heaps and Heapsort Page 30
31 Other children are not affected The node containing 8 is not affected because its parent gets larger, not smaller. The node containing 5 is not affected because its parent gets larger, not smaller. The node containing 8 is still not affected because, although its parent got smaller, its parent is still greater than it was originally. CPSC 259 Binary Heaps and Heapsort Page 31
32 A sample heap Here s a sample binary tree after it has been heapified Notice that heapified does not mean sorted. Heapifying does not change the shape of the binary tree; this binary tree is still a nearly complete binary tree. CPSC 259 Binary Heaps and Heapsort Page 32
33 Clicker Question Is the following binary tree a maximum binary heap? A: It is a maximum binary heap B: It is not a maximum binary heap C: I don t know CPSC 259 Binary Heaps and Heapsort Page 33
34 Clicker Question (answer) Is the following binary tree a maximum binary heap? A: It is a maximum binary heap B: It is not a maximum binary heap C: I don t know CPSC 259 Binary Heaps and Heapsort Page 34
35 Clicker question Which of the following statement(s) are true of the tree shown below? a. It is a binary search tree. b. It is a complete tree. c. It is a Max-heap. d. It is a Min-heap. 2 7 e. More than one of the above statements is true. 15 CPSC 259 Binary Heaps and Heapsort Page 35
36 Clicker question Which of the following statement(s) are true of the tree shown below? a. It is a binary search tree. b. It is a complete tree. c. It is a Max-heap. d. It is a Min-heap. 2 7 e. More than one of the above statements is true. 15 CPSC 259 Binary Heaps and Heapsort Page 36
37 In-class exercise Build a binary Max-heap using the following numbers, assuming numbers arrive one at a time, so you don t have the whole list to start with). 2,7,26,25,19,17,1,90,3, See hpp://visualgo.net/heap.html CPSC 259 Binary Heaps and Heapsort Page 37
38 Mapping into an array Because of the heap's shape, node values can be stored in an array. CPSC 259 Binary Heaps and Heapsort Page 38
39 Mapping into an array LeV child = 2*node + 1 right child= 2*node + 2 parent = floor((node-1)/2) nex\ree = length root = 0 CPSC 259 Binary Heaps and Heapsort Page 39
40 Adding an item to a heap If a new item is added to the heap, use ReheapUp (percolate-up ) to maintain a heap. /* This function performs the Reheapup operation on an array, to establish heap properties (for a subtree).!! PARAM: data integer array containing the heap! top position of the root! bottom - position of the added element! */! void ReheapUp( int * data, int top, int bottom ){! if (bottom > top) {! int parent = getparent(bottom);! if (data[parent] < data[bottom]) {! swap( &data[parent], &data[bottom]);! ReheapUp(data, top, parent);! }! }! } CPSC 259 Binary Heaps and Heapsort Page 40
41 In-class exercise For the max-heap below draw the recursion tree of ReheapUp(data, 0, 12), where 25 is stored in data[0]! ReheapUp(data, 0, 12) ReheapUp(data, 0, 5) ReheapUp(data, 0, 2) ReheapUp(data, 0, 0) CPSC 259 Binary Heaps and Heapsort Page 41
42 Example (min-heap) CPSC 259 Binary Heaps and Heapsort Page 42
43 Removing the root (Min-heap example) So we know how to add new elements to our heap. We also know that root is the element with the highest priority. But what should we do once root is removed? Which element should replace root?? CPSC 259 Binary Heaps and Heapsort Page 43
44 ? One possibility 4 4 5? ? CPSC 259 Binary Heaps and Heapsort Page 44
45 Removing the root (max-heap example) So we know how to add new elements to our heap. We also know that root is the element with the highest priority. But what should we do once root is removed? Which element should replace root? CPSC 259 Binary Heaps and Heapsort Page 45
46 Removing the root Suppose we remove the root: How can we fix the binary tree so it is once again a nearly complete tree? Solution: remove the rightmost leaf at the deepest level and use it for the new root CPSC 259 Binary Heaps and Heapsort Page 46
47 The percolate-down method Our tree is now a nearly complete binary tree, but no longer a heap. However, only the root lacks the heap property We can percolate-down the root. After doing this, one and only one of its children may have lost the heap property. 3 9 CPSC 259 Binary Heaps and Heapsort Page 47
48 The percolate-down method Now the left child of the root (still the number 11) lacks the heap property We can percolate-down this node. After doing this, one and only one of its children may have lost the heap property. CPSC 259 Binary Heaps and Heapsort Page 48
49 The percolate-down method Now the right child of the left child of the root (still the number 11) lacks the heap property: We can percolate-down this node. After doing this, one and only one of its children may have lost the heap property. CPSC 259 Binary Heaps and Heapsort Page 49
50 The percolate-down method Our tree is once again a heap, because every node in it has the heap property Once again, the largest (or a largest) value is in the root CPSC 259 Binary Heaps and Heapsort Page 50
51 In-class exercise Build a binary Max-heap using the following numbers 2,7,26,25,19,17,1,90,3, Now remove max and reheap CPSC 259 Binary Heaps and Heapsort Page 51
52 ! Removing an item from a heap Use ReheapDown (percolate-down) to remove an item from a max heap /* This function performs the ReheapDown operation on an array, to establish heap properties (for a subtree).!! PARAM: data integer array containing the heap! top position of the root! bottom position of the final elements in heap! */! void ReheapDown( int * data, int top, int bottom){! if (!isleaf(top, bottom)){ /* top is not a leaf */! int maxchild = getmaxchild(top) /* position of the! child having largest data value */! }! }! if ( data[top] < data[maxchild] ){! swap( &data[top], &data[maxchild])! ReheapDown( data, maxchild, bottom);! }! CPSC 259 Binary Heaps and Heapsort Page 52
53 In-class exercise For the max heap below draw the recursion tree of ReheapDown(data, 0, 10).! ReheapDown(data, 0, 10) ReheapDown(data, 1, 10) ReheapDown(data, 4, 10) ReheapDown(data, 9, 10) CPSC 259 Binary Heaps and Heapsort Page 53
54 When performing either a ReheapUp or ReheapDown operation, the number of operations depends on the depth of the tree. Notice that we traverse only one path or branch of the tree. Recall that a nearly complete binary tree of height h has between 2 h and 2 h+1-1 nodes: F Time Complexity D J F D J H H K L M We can now determine the height of a heap in terms of the number of nodes n in the heap. The height is lg n. The time complexity of the ReheapUp and ReheapDown operations is therefore O(lg n). CPSC 259 Binary Heaps and Heapsort Page 54
55 Building a Heap (Naïve) Adding the elements one add a time with a reheapup See /* This function builds a heap from an array.!! PARAM: data integer array (no order is assumed)! top - position of the root! bottom position of the final elements in heap! */! void Build_heap( int * data, int top, int bottom )! {! int index = 0;! while (index <= bottom){! ReheapUp(data, top, index);! index ++;! }! }! CPSC 259 Binary Heaps and Heapsort Page 55
56 Complexity analysis: we add each of n nodes and each node has to be sifted up, possibly as far as the root Since the binary tree is a nearly complete binary tree, sifting up a single node takes O(lg n) time Since we do this N times, Build_heap takes N*O(lg n) time, that is, O(n lg n) time CPSC 259 Binary Heaps and Heapsort Page 56
57 ! Heapify method See /* This function builds a heap from an array.!! PARAM: data integer array (no order is assumed)! top - position of the root! bottom position of the final elements in heap! */! void Heapify( int * data, int top, int bottom )! {! int index = position of last parent node in entire tree;! while (index => top){! /* go backwards from the last parent */! ReheapDown( data, index, bottom );! index --;! }! } CPSC 259 Binary Heaps and Heapsort Page 57
58 In-class exercise Example: Convert the following array to a min-heap: To do so, picture the array as a nearly complete binary tree: CPSC 259 Binary Heaps and Heapsort Page 58
59 CPSC 259 Binary Heaps and Heapsort Page 59
60 Time complexity of Heapify We can determine the time complexity of the Heapify function by looking at the total number of times the comparison and swap operations occur while building the heap. Let us consider the worst case, which is when the last level in the heap is full, and all of the nodes with high priorities are in the leafs. We will colour all the paths from each node, starting with the lowest parent and working up to the root, each going down to a leaf node. The number of edges on the path from each node to a leaf node represents an upper bound on the number of comparison and swap operations that will occur while applying the ReheapDown operation to that node. By summing the total length of these paths, we will determine the time complexity of the Heapify function. CPSC 259 Binary Heaps and Heapsort Page 60
61 Time complexity of Heapify In the worse possible case how many swaps are going to take place? Relate the number of swaps first to the number of edges and then nodes. CPSC 259 Binary Heaps and Heapsort Page 61
62 Time complexity of Heapify Note that no edge is coloured more than once. Hence the work done by the Heapify function to build the heap can be measured in terms of the number of coloured edges. CPSC 259 Binary Heaps and Heapsort Page 62
63 Time complexity of Heapify Note that no edge is coloured more than once. Hence the work done by the Heapify function to build the heap can be measured in terms of the number of coloured edges. CPSC 259 Binary Heaps and Heapsort Page 63
64 Time complexity of Heapify Note that no edge is coloured more than once. Hence the work done by the Heapify function to build the heap can be measured in terms of the number of coloured edges. CPSC 259 Binary Heaps and Heapsort Page 64
65 Time complexity of Heapify Note that no edge is coloured more than once. Hence the work done by the Heapify function to build the heap can be measured in terms of the number of coloured edges. CPSC 259 Binary Heaps and Heapsort Page 65
66 Time complexity of Heapify (sketch) Suppose H is the height of the tree, N is the number of elements in the tree, and E is the number of edges in the tree. How many edges are there in a nearly complete tree with N elements? N-1 Total number of coloured edges or swaps = E H = N H = N 1 lg N T(n) O (n) Hence, in the worst case, the overall time complexity of the Heapify algorithm is: O(n) CPSC 259 Binary Heaps and Heapsort Page 66
67 The Heapsort Algorithm Motivation: In this section, we examine a sorting algorithm that guarantees worst case O(n lg n) time. We will use a binary heap to sort an array of data The Heapsort algorithm consists of 2 phases: 1. [Heapify] Build a heap using the elements to be sorted. 2. [Sort] Use the heap to sort the data. CPSC 259 Binary Heaps and Heapsort Page 67
68 Having built the heap, we now sort the array: Note: In this section, we represent the data in both binary tree and array formats. It is important to understand that in practice the data is stored only as an array. More about this later when we cover sorting!!! CPSC 259 Binary Heaps and Heapsort Page 68
69 Time Complexity of Heapsort We need to determine the time complexity of the Heapify O(n) operation, and the time complexity of the subsequent sorting operation. The time complexity of the sorting operation once the heap has been built is fairly easy to determine. For each element in the heap, we perform a single swap and a ReheapDown. If there are N elements in the heap, the ReheapDown operation is O( lg n ), and hence the sorting operation is O( n lg n ). Hence, in the worst case, the overall time complexity of the Heapsort algorithm is: O(n) + O(n lg n) = O(n lg n) build heap from unsorted array essentially perform N RemoveMin s CPSC 259 Binary Heaps and Heapsort Page 69
70 Learning Goals revisited Provide examples of appropriate applications for priority queues and heaps. Implement and manipulate a heap using an array as the underlying data structure. Describe and use the Heapify ( Build Heap ) and Heapsort algorithms. Analyze the complexity of operations on a heap. CPSC 259 Binary Heaps and Heapsort Page 70
Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *
Binary Heaps A binary heap is another data structure. It implements a priority queue. Priority Queue has the following operations: isempty add (with priority) remove (highest priority) peek (at highest
6 March 2007 1. Array Implementation of Binary Trees
Heaps CSE 0 Winter 00 March 00 1 Array Implementation of Binary Trees Each node v is stored at index i defined as follows: If v is the root, i = 1 The left child of v is in position i The right child of
Converting a Number from Decimal to Binary
Converting a Number from Decimal to Binary Convert nonnegative integer in decimal format (base 10) into equivalent binary number (base 2) Rightmost bit of x Remainder of x after division by two Recursive
Binary Heaps. CSE 373 Data Structures
Binary Heaps CSE Data Structures Readings Chapter Section. Binary Heaps BST implementation of a Priority Queue Worst case (degenerate tree) FindMin, DeleteMin and Insert (k) are all O(n) Best case (completely
CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team
CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we learned about the ADT Priority Queue. A
Cpt S 223. School of EECS, WSU
Priority Queues (Heaps) 1 Motivation Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important or timely than others (higher priority)
Ordered Lists and Binary Trees
Data Structures and Algorithms Ordered Lists and Binary Trees Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/62 6-0:
1/1 7/4 2/2 12/7 10/30 12/25
Binary Heaps A binary heap is dened to be a binary tree with a key in each node such that: 1. All leaves are on, at most, two adjacent levels. 2. All leaves on the lowest level occur to the left, and all
CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) 3 4 4 7 5 9 6 16 7 8 8 4 9 8 10 4 Total 92.
Name: Email ID: CSE 326, Data Structures Section: Sample Final Exam Instructions: The exam is closed book, closed notes. Unless otherwise stated, N denotes the number of elements in the data structure
Analysis of Algorithms I: Binary Search Trees
Analysis of Algorithms I: Binary Search Trees Xi Chen Columbia University Hash table: A data structure that maintains a subset of keys from a universe set U = {0, 1,..., p 1} and supports all three dictionary
Algorithms and Data Structures
Algorithms and Data Structures CMPSC 465 LECTURES 20-21 Priority Queues and Binary Heaps Adam Smith S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 1 Trees Rooted Tree: collection
Data Structures and Algorithms
Data Structures and Algorithms CS245-2016S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list
Binary Heap Algorithms
CS Data Structures and Algorithms Lecture Slides Wednesday, April 5, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks [email protected] 2005 2009 Glenn G. Chappell
A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property
CmSc 250 Intro to Algorithms Chapter 6. Transform and Conquer Binary Heaps 1. Definition A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called
A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:
Binary Search Trees 1 The general binary tree shown in the previous chapter is not terribly useful in practice. The chief use of binary trees is for providing rapid access to data (indexing, if you will)
From Last Time: Remove (Delete) Operation
CSE 32 Lecture : More on Search Trees Today s Topics: Lazy Operations Run Time Analysis of Binary Search Tree Operations Balanced Search Trees AVL Trees and Rotations Covered in Chapter of the text From
CS711008Z Algorithm Design and Analysis
CS711008Z Algorithm Design and Analysis Lecture 7 Binary heap, binomial heap, and Fibonacci heap 1 Dongbo Bu Institute of Computing Technology Chinese Academy of Sciences, Beijing, China 1 The slides were
Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)
Sorting revisited How did we use a binary search tree to sort an array of elements? Tree Sort Algorithm Given: An array of elements to sort 1. Build a binary search tree out of the elements 2. Traverse
Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R
Binary Search Trees A Generic Tree Nodes in a binary search tree ( B-S-T) are of the form P parent Key A Satellite data L R B C D E F G H I J The B-S-T has a root node which is the only node whose parent
Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child
Binary Search Trees Data in each node Larger than the data in its left child Smaller than the data in its right child FIGURE 11-6 Arbitrary binary tree FIGURE 11-7 Binary search tree Data Structures Using
Class Notes CS 3137. 1 Creating and Using a Huffman Code. Ref: Weiss, page 433
Class Notes CS 3137 1 Creating and Using a Huffman Code. Ref: Weiss, page 433 1. FIXED LENGTH CODES: Codes are used to transmit characters over data links. You are probably aware of the ASCII code, a fixed-length
Questions 1 through 25 are worth 2 points each. Choose one best answer for each.
Questions 1 through 25 are worth 2 points each. Choose one best answer for each. 1. For the singly linked list implementation of the queue, where are the enqueues and dequeues performed? c a. Enqueue in
Binary Search Trees CMPSC 122
Binary Search Trees CMPSC 122 Note: This notes packet has significant overlap with the first set of trees notes I do in CMPSC 360, but goes into much greater depth on turning BSTs into pseudocode than
Data Structure [Question Bank]
Unit I (Analysis of Algorithms) 1. What are algorithms and how they are useful? 2. Describe the factor on best algorithms depends on? 3. Differentiate: Correct & Incorrect Algorithms? 4. Write short note:
root node level: internal node edge leaf node CS@VT Data Structures & Algorithms 2000-2009 McQuain
inary Trees 1 A binary tree is either empty, or it consists of a node called the root together with two binary trees called the left subtree and the right subtree of the root, which are disjoint from each
Outline BST Operations Worst case Average case Balancing AVL Red-black B-trees. Binary Search Trees. Lecturer: Georgy Gimel farb
Binary Search Trees Lecturer: Georgy Gimel farb COMPSCI 220 Algorithms and Data Structures 1 / 27 1 Properties of Binary Search Trees 2 Basic BST operations The worst-case time complexity of BST operations
Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015
Data Structures Jaehyun Park CS 97SI Stanford University June 29, 2015 Typical Quarter at Stanford void quarter() { while(true) { // no break :( task x = GetNextTask(tasks); process(x); // new tasks may
Heaps & Priority Queues in the C++ STL 2-3 Trees
Heaps & Priority Queues in the C++ STL 2-3 Trees CS 3 Data Structures and Algorithms Lecture Slides Friday, April 7, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks
Chapter 14 The Binary Search Tree
Chapter 14 The Binary Search Tree In Chapter 5 we discussed the binary search algorithm, which depends on a sorted vector. Although the binary search, being in O(lg(n)), is very efficient, inserting a
Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s
Quiz 4 Solutions Q1: What value does function mystery return when called with a value of 4? int mystery ( int number ) { if ( number
1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++
Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The
PES Institute of Technology-BSC QUESTION BANK
PES Institute of Technology-BSC Faculty: Mrs. R.Bharathi CS35: Data Structures Using C QUESTION BANK UNIT I -BASIC CONCEPTS 1. What is an ADT? Briefly explain the categories that classify the functions
Exam study sheet for CS2711. List of topics
Exam study sheet for CS2711 Here is the list of topics you need to know for the final exam. For each data structure listed below, make sure you can do the following: 1. Give an example of this data structure
A binary search tree is a binary tree with a special property called the BST-property, which is given as follows:
Chapter 12: Binary Search Trees A binary search tree is a binary tree with a special property called the BST-property, which is given as follows: For all nodes x and y, if y belongs to the left subtree
MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push) -----------------------------------------
=============================================================================================================================== DATA STRUCTURE PSEUDO-CODE EXAMPLES (c) Mubashir N. Mir - www.mubashirnabi.com
The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).
CHAPTER 5 The Tree Data Model There are many situations in which information has a hierarchical or nested structure like that found in family trees or organization charts. The abstraction that models hierarchical
Algorithms Chapter 12 Binary Search Trees
Algorithms Chapter 1 Binary Search Trees Outline Assistant Professor: Ching Chi Lin 林 清 池 助 理 教 授 [email protected] Department of Computer Science and Engineering National Taiwan Ocean University
CSE 326: Data Structures B-Trees and B+ Trees
Announcements (4//08) CSE 26: Data Structures B-Trees and B+ Trees Brian Curless Spring 2008 Midterm on Friday Special office hour: 4:-5: Thursday in Jaech Gallery (6 th floor of CSE building) This is
Big Data and Scripting. Part 4: Memory Hierarchies
1, Big Data and Scripting Part 4: Memory Hierarchies 2, Model and Definitions memory size: M machine words total storage (on disk) of N elements (N is very large) disk size unlimited (for our considerations)
1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.
1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D. base address 2. The memory address of fifth element of an array can be calculated
Algorithms and Data Structures
Algorithms and Data Structures Part 2: Data Structures PD Dr. rer. nat. habil. Ralf-Peter Mundani Computation in Engineering (CiE) Summer Term 2016 Overview general linked lists stacks queues trees 2 2
CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016
CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues Linda Shapiro Registration We have 180 students registered and others who want to get in. If you re thinking of dropping
How To Create A Tree From A Tree In Runtime (For A Tree)
Binary Search Trees < 6 2 > = 1 4 8 9 Binary Search Trees 1 Binary Search Trees A binary search tree is a binary tree storing keyvalue entries at its internal nodes and satisfying the following property:
Binary Search Trees (BST)
Binary Search Trees (BST) 1. Hierarchical data structure with a single reference to node 2. Each node has at most two child nodes (a left and a right child) 3. Nodes are organized by the Binary Search
Lecture Notes on Binary Search Trees
Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning Lecture 17 March 17, 2010 1 Introduction In the previous two lectures we have seen how to exploit the structure
Lecture Notes on Binary Search Trees
Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 17 October 23, 2014 1 Introduction In this lecture, we will continue considering associative
Data Structures and Algorithms Written Examination
Data Structures and Algorithms Written Examination 22 February 2013 FIRST NAME STUDENT NUMBER LAST NAME SIGNATURE Instructions for students: Write First Name, Last Name, Student Number and Signature where
Introduction to Data Structures and Algorithms
Introduction to Data Structures and Algorithms Chapter: Elementary Data Structures(1) Lehrstuhl Informatik 7 (Prof. Dr.-Ing. Reinhard German) Martensstraße 3, 91058 Erlangen Overview on simple data structures
Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C
Tutorial#1 Q 1:- Explain the terms data, elementary item, entity, primary key, domain, attribute and information? Also give examples in support of your answer? Q 2:- What is a Data Type? Differentiate
Binary Trees and Huffman Encoding Binary Search Trees
Binary Trees and Huffman Encoding Binary Search Trees Computer Science E119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Motivation: Maintaining a Sorted Collection of Data A data dictionary
Algorithms and Data Structures Written Exam Proposed SOLUTION
Algorithms and Data Structures Written Exam Proposed SOLUTION 2005-01-07 from 09:00 to 13:00 Allowed tools: A standard calculator. Grading criteria: You can get at most 30 points. For an E, 15 points are
The ADT Binary Search Tree
The ADT Binary Search Tree The Binary Search Tree is a particular type of binary tree that enables easy searching for specific items. Definition The ADT Binary Search Tree is a binary tree which has an
Data Structures and Algorithm Analysis (CSC317) Intro/Review of Data Structures Focus on dynamic sets
Data Structures and Algorithm Analysis (CSC317) Intro/Review of Data Structures Focus on dynamic sets We ve been talking a lot about efficiency in computing and run time. But thus far mostly ignoring data
Full and Complete Binary Trees
Full and Complete Binary Trees Binary Tree Theorems 1 Here are two important types of binary trees. Note that the definitions, while similar, are logically independent. Definition: a binary tree T is full
Analysis of a Search Algorithm
CSE 326 Lecture 4: Lists and Stacks 1. Agfgd 2. Dgsdsfd 3. Hdffdsf 4. Sdfgsfdg 5. Tefsdgass We will review: Analysis: Searching a sorted array (from last time) List ADT: Insert, Delete, Find, First, Kth,
5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.
1. The advantage of.. is that they solve the problem if sequential storage representation. But disadvantage in that is they are sequential lists. [A] Lists [B] Linked Lists [A] Trees [A] Queues 2. The
Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010
Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010 Problem 1. In each of the following question, please specify if the statement
Data Structures and Data Manipulation
Data Structures and Data Manipulation What the Specification Says: Explain how static data structures may be used to implement dynamic data structures; Describe algorithms for the insertion, retrieval
Operations: search;; min;; max;; predecessor;; successor. Time O(h) with h height of the tree (more on later).
Binary search tree Operations: search;; min;; max;; predecessor;; successor. Time O(h) with h height of the tree (more on later). Data strutcure fields usually include for a given node x, the following
Lecture 4: Balanced Binary Search Trees
Lecture 4 alanced inar Search Trees 6.006 Fall 009 Lecture 4: alanced inar Search Trees Lecture Overview The importance of being balanced VL trees Definition alance Insert Other balanced trees Data structures
Lecture 2 February 12, 2003
6.897: Advanced Data Structures Spring 003 Prof. Erik Demaine Lecture February, 003 Scribe: Jeff Lindy Overview In the last lecture we considered the successor problem for a bounded universe of size u.
Why Use Binary Trees?
Binary Search Trees Why Use Binary Trees? Searches are an important application. What other searches have we considered? brute force search (with array or linked list) O(N) binarysearch with a pre-sorted
Data Structures, Practice Homework 3, with Solutions (not to be handed in)
Data Structures, Practice Homework 3, with Solutions (not to be handed in) 1. Carrano, 4th edition, Chapter 9, Exercise 1: What is the order of each of the following tasks in the worst case? (a) Computing
Data Structures Fibonacci Heaps, Amortized Analysis
Chapter 4 Data Structures Fibonacci Heaps, Amortized Analysis Algorithm Theory WS 2012/13 Fabian Kuhn Fibonacci Heaps Lacy merge variant of binomial heaps: Do not merge trees as long as possible Structure:
Lecture 6: Binary Search Trees CSCI 700 - Algorithms I. Andrew Rosenberg
Lecture 6: Binary Search Trees CSCI 700 - Algorithms I Andrew Rosenberg Last Time Linear Time Sorting Counting Sort Radix Sort Bucket Sort Today Binary Search Trees Data Structures Data structure is a
TREE BASIC TERMINOLOGIES
TREE Trees are very flexible, versatile and powerful non-liner data structure that can be used to represent data items possessing hierarchical relationship between the grand father and his children and
Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction
Class Overview CSE 326: Data Structures Introduction Introduction to many of the basic data structures used in computer software Understand the data structures Analyze the algorithms that use them Know
Big O and Limits Abstract Data Types Data Structure Grand Tour. http://gcc.gnu.org/onlinedocs/libstdc++/images/pbds_different_underlying_dss_1.
Big O and Limits Abstract Data Types Data Structure Grand Tour http://gcc.gnu.org/onlinedocs/libstdc++/images/pbds_different_underlying_dss_1.png Consider the limit lim n f ( n) g ( n ) What does it
Tables so far. set() get() delete() BST Average O(lg n) O(lg n) O(lg n) Worst O(n) O(n) O(n) RB Tree Average O(lg n) O(lg n) O(lg n)
Hash Tables Tables so far set() get() delete() BST Average O(lg n) O(lg n) O(lg n) Worst O(n) O(n) O(n) RB Tree Average O(lg n) O(lg n) O(lg n) Worst O(lg n) O(lg n) O(lg n) Table naïve array implementation
Sample Questions Csci 1112 A. Bellaachia
Sample Questions Csci 1112 A. Bellaachia Important Series : o S( N) 1 2 N N i N(1 N) / 2 i 1 o Sum of squares: N 2 N( N 1)(2N 1) N i for large N i 1 6 o Sum of exponents: N k 1 k N i for large N and k
Data Structure with C
Subject: Data Structure with C Topic : Tree Tree A tree is a set of nodes that either:is empty or has a designated node, called the root, from which hierarchically descend zero or more subtrees, which
Data Structures. Level 6 C30151. www.fetac.ie. Module Descriptor
The Further Education and Training Awards Council (FETAC) was set up as a statutory body on 11 June 2001 by the Minister for Education and Science. Under the Qualifications (Education & Training) Act,
Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1
Definition Course: Programming II - Abstract Data Types The ADT Stack The ADT Stack is a linear sequence of an arbitrary number of items, together with access procedures. The access procedures permit insertions
B-Trees. Algorithms and data structures for external memory as opposed to the main memory B-Trees. B -trees
B-Trees Algorithms and data structures for external memory as opposed to the main memory B-Trees Previous Lectures Height balanced binary search trees: AVL trees, red-black trees. Multiway search trees:
22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department http://www.cs.uiowa.edu/~hzhang/c31/
22c:31 Algorithms Ch3: Data Structures Hantao Zhang Computer Science Department http://www.cs.uiowa.edu/~hzhang/c31/ Linear Data Structures Now we can now explore some convenient techniques for organizing
External Sorting. Chapter 13. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1
External Sorting Chapter 13 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1 Why Sort? A classic problem in computer science! Data requested in sorted order e.g., find students in increasing
Lecture 12 Doubly Linked Lists (with Recursion)
Lecture 12 Doubly Linked Lists (with Recursion) In this lecture Introduction to Doubly linked lists What is recursion? Designing a node of a DLL Recursion and Linked Lists o Finding a node in a LL (recursively)
- Easy to insert & delete in O(1) time - Don t need to estimate total memory needed. - Hard to search in less than O(n) time
Skip Lists CMSC 420 Linked Lists Benefits & Drawbacks Benefits: - Easy to insert & delete in O(1) time - Don t need to estimate total memory needed Drawbacks: - Hard to search in less than O(n) time (binary
DATA STRUCTURES USING C
DATA STRUCTURES USING C QUESTION BANK UNIT I 1. Define data. 2. Define Entity. 3. Define information. 4. Define Array. 5. Define data structure. 6. Give any two applications of data structures. 7. Give
ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION 2008-10-23/5:15-6:45 REC-200, EVI-350, RCH-106, HH-139
ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION 2008-10-23/5:15-6:45 REC-200, EVI-350, RCH-106, HH-139 Instructions: No aides. Turn off all electronic media and store them under your desk. If
Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles
B-Trees Algorithms and data structures for external memory as opposed to the main memory B-Trees Previous Lectures Height balanced binary search trees: AVL trees, red-black trees. Multiway search trees:
Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types
EECS 281: Data Structures and Algorithms The Foundation: Data Structures and Abstract Data Types Computer science is the science of abstraction. Abstract Data Type Abstraction of a data structure on that
Sequential Data Structures
Sequential Data Structures In this lecture we introduce the basic data structures for storing sequences of objects. These data structures are based on arrays and linked lists, which you met in first year
Alex. Adam Agnes Allen Arthur
Worksheet 29:Solution: Binary Search Trees In Preparation: Read Chapter 8 to learn more about the Bag data type, and chapter 10 to learn more about the basic features of trees. If you have not done so
Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic
Queues Outline and Required Reading: Queues ( 4. except 4..4) COSC, Fall 3, Section A Instructor: N. Vlajic Queue ADT Queue linear data structure organized according to first-in/first-out (FIFO) principle!
Algorithms. Margaret M. Fleck. 18 October 2010
Algorithms Margaret M. Fleck 18 October 2010 These notes cover how to analyze the running time of algorithms (sections 3.1, 3.3, 4.4, and 7.1 of Rosen). 1 Introduction The main reason for studying big-o
Rotation Operation for Binary Search Trees Idea:
Rotation Operation for Binary Search Trees Idea: Change a few pointers at a particular place in the tree so that one subtree becomes less deep in exchange for another one becoming deeper. A sequence of
Common Data Structures
Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees
recursion, O(n), linked lists 6/14
recursion, O(n), linked lists 6/14 recursion reducing the amount of data to process and processing a smaller amount of data example: process one item in a list, recursively process the rest of the list
The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,
The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge, cheapest first, we had to determine whether its two endpoints
Binary Search Trees. basic implementations randomized BSTs deletion in BSTs
Binary Search Trees basic implementations randomized BSTs deletion in BSTs eferences: Algorithms in Java, Chapter 12 Intro to Programming, Section 4.4 http://www.cs.princeton.edu/introalgsds/43bst 1 Elementary
Symbol Tables. Introduction
Symbol Tables Introduction A compiler needs to collect and use information about the names appearing in the source program. This information is entered into a data structure called a symbol table. The
Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees
Learning Outcomes COMP202 Complexity of Algorithms Binary Search Trees and Other Search Trees [See relevant sections in chapters 2 and 3 in Goodrich and Tamassia.] At the conclusion of this set of lecture
CompSci-61B, Data Structures Final Exam
Your Name: CompSci-61B, Data Structures Final Exam Your 8-digit Student ID: Your CS61B Class Account Login: This is a final test for mastery of the material covered in our labs, lectures, and readings.
B+ Tree Properties B+ Tree Searching B+ Tree Insertion B+ Tree Deletion Static Hashing Extendable Hashing Questions in pass papers
B+ Tree and Hashing B+ Tree Properties B+ Tree Searching B+ Tree Insertion B+ Tree Deletion Static Hashing Extendable Hashing Questions in pass papers B+ Tree Properties Balanced Tree Same height for paths
Binary search algorithm
Binary search algorithm Definition Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than
Keys and records. Binary Search Trees. Data structures for storing data. Example. Motivation. Binary Search Trees
Binary Search Trees Last lecture: Tree terminology Kinds of binary trees Size and depth of trees This time: binary search tree ADT Java implementation Keys and records So far most examples assumed that
Linked Lists, Stacks, Queues, Deques. It s time for a chainge!
Linked Lists, Stacks, Queues, Deques It s time for a chainge! Learning Goals After this unit, you should be able to... Differentiate an abstraction from an implementation. Define and give examples of problems
Persistent Binary Search Trees
Persistent Binary Search Trees Datastructures, UvA. May 30, 2008 0440949, Andreas van Cranenburgh Abstract A persistent binary tree allows access to all previous versions of the tree. This paper presents
