Data Structures and Algorithms. Dr. Amit Kumar and Dr. Amitabha Bagchi IIT Delhi

Size: px
Start display at page:

Download "Data Structures and Algorithms. Dr. Amit Kumar and Dr. Amitabha Bagchi IIT Delhi"

Transcription

1 Data Structures and Algorithms Dr. Amit Kumar and Dr. Amitabha Bagchi IIT Delhi 1

2 Algorithms & Data structures Algorithm Outline, the essence of a computational procedure, step by step instructions Program an implementation of an algorithm in some programming language Data structure Organization of data needed to solve the problem 2

3 Overall Picture Using a computer to help solve problems Designing programs architecture algorithms Writing programs Verifying (Testing) programs Data Structure and Algorithm Design Goals Efficiency Correctness Implementation Goals Robustness Reusability Adaptability 3

4 Algorithmic problem Specification of input? Specification of output as a function of input Infinite number of input instances satisfying the specification. For example: A sorted, non decreasing sequence of natural numbers. The sequence is of non zero, finite length: 1, 20, 908, 909, ,

5 Algorithmic Solution Input instance, adhering to the specification Algorithm Output related to the input as required Algorithm describes actions on the input instance Infinitely many correct algorithms for the same algorithmic problem 5

6 Data structures Input instance, adhering to the specification Algorithm Output related to the input as required How to organize and manipulate the data Affects the efficiency of the algorithm 6

7 The Goals of this Course The main things that we will try to learn in this course: To be able to think algorithmically, to get the spirit of how algorithms are designed To get to know a toolbox of techniques for designing data structures and algorithms. To learn reason (in a formal way) about the efficiency and the correctness of algorithms 7

8 Example: Sorting OUTPUT INPUT a permutation of the sequence of numbers sequence of numbers a1, a2, a3,.,an Sort Correctness (requirements for the output) For any given input the algorithm halts with the output: b1 < b2 < b3 <. < bn b1, b2, b3,., bn is a permutation of a1, a2, a3,.,an b1,b2,b3,.,bn Running time Depends on number of elements (n) how (partially) sorted they are algorithm 8

9 Insertion Sort A j 5 1 n i Strategy Start empty handed Insert a card in the right position of the already sorted hand Continue until all cards are inserted/sorted 9

10 Insertion Sort

11 Insertion Sort

12 Insertion Sort

13 Insertion Sort

14 Insertion Sort

15 Insertion Sort A j 5 1 n i INPUT: A[1..n] an array of integers OUTPUT: a permutation of A such that A[1] A[2] A [n] for j 2 to n do key A[j] Insert A[j] into the sorted sequence A[1..j 1] i j 1 while i>0 and A[i]>key do A[i+1] A[i] i A[i+1] key 15

16 Issues Efficiency: Running time Space used Efficiency as a function of input size: Number of data elements (numbers, points) A number of bits in an input number How does efficiency depend on the data structure? 16

17 The RAM model Very important to choose the level of detail. The RAM model: Instructions (each taking constant time): Arithmetic (add, subtract, multiply, etc.) Data movement (assign) Control (branch, subroutine call, return) Data types integers and floats 17

18 Analysis of Insertion Sort Time to compute the running time as a function of the input size for j 2 to n do key A[j] Insert A[j] into the sorted sequence A [1..j 1] i j 1 while i>0 and A[i]>key do A[i+1] A[i] i A[i+1]:=key cost c1 c2 0 c3 c4 c5 c6 c7 times n n 1 n 1 n 1 n t (t (t j nj = 2 nj = 2 j j =2 j n 1 1) 1) 18

19 Best/Worst/Average Case Best case: elements already sorted tj=1, running time = f(n), i.e., linear time. Worst case: elements are sorted in inverse order tj=j, running time = f(n2), i.e., quadratic time Average case: tj=j/2, running time = f(n2), i.e., quadratic time 19

20 Best/Worst/Average Case For a specific size of input n, investigate running times for different input instances: 6n 5n 4n 3n 2n 1n 20

21 Best/Worst/Average Case For inputs of all sizes: worst case average case Running time 6n 5n best case 4n 3n 2n 1n Input instance size 21

22 Asymptotic Analysis Goal: to simplify analysis of running time by getting rid of details, which may be affected by specific implementation and hardware like rounding : 1,000,001» 1,000,000 3n2» n2 Capturing the essence: how the running time of an algorithm increases with the size of the input in the limit. Asymptotically more efficient algorithms are best for all but small inputs 22

23 Asymptotic Notation The big Oh O Notation asymptotic upper bound f(n) = O(g(n)), if there exists constants c and n0, s.t. f(n) c g(n) for n n0 f(n) and g(n) are functions over non negative integers Used for worst case analysis c g ( n) f n Running Time n0 Input Size 23

24 Examples f ( n )2 = n 6+ 2n+6 is O(n). c g(n) = 4n g(n) = n n 24

25 Examples Simple Rule: Drop lower order terms and constant factors. 50 n log n is O(n log n) 7n 3 is O(n) 8n2 log n + 5n2 + n is O(n2 log n) Note: Even though (50 n log n) is O(n5), it is expected that such an approximation be of as small an order as possible 25

26 More Examples 26

27 Asymptotic Notation The big Omega Ω Notation asymptotic lower bound f(n) = Ω(g(n)) if g(n) = O(f(n)) Used to describe best case running times or lower bounds of algorithmic problems E.g., lower bound of searching in an unsorted array is Ω(n). Running Time f n c g ( n) n0 Input Size 27

28 Asymptotic Notation The big Theta Θ Notation asymptoticly tight bound f(n) = Θ(g(n)) if f(n) = O(g(n)) and f(n) = Ω (g(n)) O(f(n)) is often misused instead of Θ(f(n)) c 2 g n Running Time f n c 1 g n n0 Input Size 28

29 Asymptotic Notation Analogy with real numbers f(n) = O(g(n)) f g f(n) = Ω(g(n)) f g f(n) = Θ(g(n)) f=g Abuse of notation: f(n) = O(g(n)) actually means f(n) O(g(n)) 29

30 Asymptotic Notation Special classes of algorithms: logarithmic: O(log n) linear: O(n) quadratic: O(n2) polynomial: O(nk), k 1 exponential: O(an), n > 1 30

31 Comparison of Running Times Running Time Maximum problem size (n) 1 second 1 minute 1 hour 400n n log n n n n

32 Sorting Insertion sort takes Θ(n2) time. Are there better strategies? There are many alternate strategies, in fact it is possible to get Θ(n log n) running time. 32

33 Example 2: Searching INPUT sequence of numbers (database) a single number (query) a1, a2, a3,.,an; q OUTPUT an index of the found number or NIL j ; ; 9 NIL 33

34 Searching INPUT: A[1..n] an array of integers, q an integer. OUTPUT: an index j such that A[j] = q. NIL, if q does not appear in A j 1 while j n and A[j] q do j++ if j n then return j else return NIL Worst case running time: Θ(n), average case: Θ(n/2) We can t do better. This is a lower bound for the problem of searching in an arbitrary sequence. 34

35 Searching in a Sorted Array OUTPUT INPUT sorted non descending sequence of a single number (query) a1, a2, a3,.,an; q numbers (database) an index of the found j ; ; 9 NIL number or NIL 35

36 Binary search Idea: Divide and conquer, one of the key design techniques INPUT: A[1..n] a sorted (non decreasing) array of integers, q an integer. OUTPUT: an index j such that A[j] = q. NIL, if q does not appear in A left=1 right=n do j=(left+right)/2 if A[j]=q then return j else if A[j]>q then right=j 1 else left=j+1 while left<=right return NIL 36

37 Binary search example ; 7 37

38 Binary search example ; 7 38

39 Binary search example ;7 39

40 Binary search example ;7 40

41 Binary search example 7 8 ;7 41

42 Binary search example 7 8 ;7 42

43 Insertion Sort : A fresh look A j 5 1 n i While inserting the next element in the partially sorted list, why not use binary search? 43

44 Insertion Sort : A fresh look A j 5 1 n i While inserting the next element in the partially sorted list, why not use binary search? Even though we know where to insert, shifting the array locations will take too much time. Need a better Data structure 44

45 Correctness proofs The algorithm is correct if for any legal input it terminates and produces the desired output. Automatic proof of correctness is not possible But there are practical techniques and rigorous formalisms that help to reason about the correctness of algorithms 45

46 Assertions To prove partial correctness we associate a number of assertions (statements about the state of the execution) with specific checkpoints in the algorithm. E.g., A[1],, A[k] form an increasing sequence Preconditions assertions that must be valid before the execution of an algorithm or a subroutine Postconditions assertions that must be valid after the execution of an algorithm or a subroutine 46

47 Loop Invariants Invariants assertions that are valid any time they are reached (many times during the execution of an algorithm, e.g., in loops) We must show three things about loop invariants: Initialization it is true prior to the first iteration Maintenance if it is true before an iteration, it remains true before the next iteration Termination when loop terminates the invariant gives a useful property to show the correctness of the algorithm 47

48 A Quick Math Review Geometric progression given an integer n0 and a real number 0< a < 1 n +1 1 a i 2 n a = 1 + a + a a = 1 a i= 0 n geometric progressions exhibit exponential growth Arithmetic progression n2 + n i = n = 2 i= 0 n 48

49 A Quick Math Review (2) 49

50 Summations The running time of insertion sort is determined by a nested loop for j 2 to length(a) key A[j] i j 1 while i>0 and A[i]>key A[i+1] A[i] i i 1 A[i+1] key Nested loops correspond to summations 2 ( j 1) = O ( n ) j =2 n 50

51 Proof by Induction We want to show that property P is true for all integers n n0 Basis: prove that P is true for n0 Inductive step: prove that if P is true for all k such that n0 k n 1 then P is also true for n n n( n + 1) Example S ( n) = i = for n 1 i =0 Basis 2 1(1 + 1) S (1) = i = 2 i=

52 Proof by Induction Inductive Step S (k) = k i = i =0 S ( n) = k ( k + 1) for 1 k n 1 2 n n 1 i =0 i =0 i = i + n =S (n 1) + n = ( n 1 +1) ( n 2 n + 2 n) = (n 1) +n= = 2 2 n( n +1) = 2 52

53 Abstract Data Types (ADTs) An Abstract Data Type is an abstraction of a data structure. (No coding is involved.) The ADT specifies: what can be stored in the ADT what operations can be done on/by the ADT For example, if we are going to model a bag of marbles as an ADT, we could specify that: this ADT stores marbles this ADT supports putting in a marble and getting out a marble. 53

54 Abstract Data Types (ADTs) Types of operations: Constructors Access functions Manipulation procedures 54

55 Abstract Data Types Why do we need to talk about ADTs? They serve as specifications of requirements for the building blocks of solutions to algorithmic problems Provides a language to talk on a higher level of abstraction ADTs encapsulate data structures and algorithms that implement them Separate the issues of correctness and efficiency 55

56 Example Dynamic Sets We will deal with ADTs, instances of which are sets of some type of elements. Operations are provided that change the set We call such class of ADTs dynamic sets 56

57 Dynamic Sets An example dynamic set ADT Methods: New():ADT Insert(S:ADT, v:element):adt Delete(S:ADT, v:element):adt IsIn(S:ADT, v:element):boolean Insert and Delete manipulation operations IsIn Access method method 57

58 Other Examples Simple ADTs: Queue Deque Stack 58

59 Stacks A stack is a container of objects that are inserted and removed according to the last in first out (LIFO) principle. Objects can be inserted at any time, but only the last (the most recently inserted) object can be removed. Inserting an item is known as pushing onto the stack. Popping off the stack is synonymous with removing an item. 59

60 Stacks A PEZ dispenser as an analogy: 60

61 Stacks A stack is an ADT that supports three main methods: new():adt Creates a new stack push(s:adt, o:element):adt Inserts object o onto top of stack S pop(s:adt):adt Removes the top object of stack S; if the stack is empty an error occurs top(s:adt):element Returns the top object of the stack, without removing it; if the stack is empty an error occurs 61

62 Stacks The following support methods could also be defined: size(s:adt):integer Returns the number of objects in stack S isempty(s:adt): boolean Indicates if stack S is empty 62

63 An Array Implementation Create a stack using an array by specifying a maximum size N for our stack. The stack consists of an N element array S and an integer variable t, the index of the top element in array S. Array indices start at 0, so we initialize t to 1 63

64 An Array Implementation Pseudo code Algorithm size() return t+1 Algorithm isempty() return (t<0) Algorithm top() if isempty() then return Error return S[t] Algorithm push(o) if size()==n then return Error t=t+1 S[t]=o Algorithm pop() if isempty() then return Error S[t]=null t=t 1 64

65 An Array Implementation The array implementation is simple and efficient (methods performed in O(1)). There is an upper bound, N, on the size of the stack. The arbitrary value N may be too small for a given application, or a waste of memory. 65

66 Applications (1) Matching brackets : a sequence of left and right brackets can every left bracket be matched with a right bracket? ( ) ( ) ( ( ( ) ( ) ) ( ) ) : well formed ((() : not well formed 66

67 Applications (1) When see a ( : push When see a ) : pop Brackets well formed when? Otherwise can get errors 67

68 Applications (2) Procedure calls : 68

69 Applications (3) : time series The span s of a stock s price on a certain day i is the maximum number of consecutive days (up to i the current day) the price of the stock has been less than or equal to its price on day i 69

70 Applications (3) : time series Problem : compute the span of the stock for each day. Naïve algorithm : For each day i, scan back and find the first time price exceeds s i Worst case running time? O(n ) 2 Question : Can this be done in O(n) time? 70

71 Applications (3) : time series We see that si on day i can be easily computed if we know the closest day preceding i, such that the price is greater than on that day than the price on day i. If such a day exists, let s call it h(i), otherwise, we conventionally define h(i) = 1 The span is now computed as si = i h(i) 71

72 Applications (3) : time series Compute h(i) using a stack. On day i, the stack contains i, h(i), h(h(i)), How to update the stack?? 72

73 Applications (3) : time series Compute h(i) using a stack. On day i, the stack contains i, h(i), h(h(i)), How to update the stack?? On day i : x = top of stack while (s > s i) { x pop the stack x = top of stack } push i 73

74 Applications (3) : time series Compute h(i) using a stack. On day i, the stack contains i, h(i), h(h(i)), How to update the stack?? On day i : x = top of stack while (s > s i) { x pop the stack x = top of stack } push i Why is the running time O(n)? 74

75 Teaser Design a data structure which can do push, pop and find min on numbers. All operations in O(1) time! 75

76 Singly Linked List Nodes (data, pointer) connected in a chain by links the head or the tail of the list could serve as the top of the stack 76

77 Singly Linked List Can implement a stack with a linked list. Head = top of stack. Advantage : no limit on size of stack. 77

78 Queues A queue differs from a stack in that its insertion and removal routines follows the first in first out (FIFO) principle. Elements may be inserted at any time, but only the element which has been in the queue the longest may be removed. Elements are inserted at the rear (enqueued) and removed from the front (dequeued) Front Queue Rear 78

79 Queues The queue supports three fundamental methods: New():ADT Creates an empty queue Enqueue(S:ADT, o:element):adt Inserts object o at the rear of the queue Dequeue(S:ADT):ADT Removes the object from the front of the queue; an error occurs if the queue is empty Front(S:ADT):element Returns, but does not remove, the front element; an error occurs if the queue is empty 79

80 Queues These support methods should also be defined: Size(S:ADT):integer IsEmpty(S:ADT):boolean 80

81 An Array Implementation A maximum size N is specified. The queue consists of an N element array Q and two integer variables: f, index of the front element (head for dequeue) r, index of the element after the rear one (tail for enqueue) 81

82 An Array Implementation Enqueue? Dequeue? Empty? Full? Problems?? 82

83 An Array Implementation wrapped around configuration what does f=r mean? 83

84 An Array Implementation (3) Pseudo code Algorithm size() return (N f+r) mod N Algorithm isempty() return (f=r) Algorithm front() if isempty() then return Error return Q[f] Algorithm dequeue() if isempty() then return Error Q[f]=null f=(f+1)modn Algorithm enqueue(o) if size = N 1 then return Error Q[r]=o r=(r +1)modN 84

85 Linked List Implementation Dequeue advance head reference 85

86 Linked List Implementation Enqueue create a new node at the tail chain it and move the tail reference 86

87 Double Ended Queue A double ended queue, or deque, supports insertion and deletion from the front and back The deque supports six fundamental methods InsertFirst(S:ADT, o:element):adt Inserts e at the beginning of deque InsertLast(S:ADT, o:element):adt Inserts e at end of deque RemoveFirst(S:ADT):ADT Removes the first element RemoveLast(S:ADT):ADT Removes the last element First(S:ADT):element and Last(S:ADT):element Returns the first and the last elements 87

88 Stacks with Deques Implementing ADTs using implementations of other ADTs as building blocks Stack Method Deque Implementation size() size() isempty() isempty() top() last() push(o) insertlast(o) pop() removelast() 88

89 Queues with Deques Queue Method Deque Implementation size() size() isempty() isempty() front() first() enqueue(o) insertlast(o) dequeue() removefirst() 89

90 Doubly Linked Lists Deletions at the tail of a singly linked list cannot be done in constant time To implement a deque, we use a doubly linked list A node of a doubly linked list has a next and a prev link Then, all the methods of a deque have a constant (that is, O(1)) running time. 90

91 Doubly Linked Lists When implementing a doubly linked lists, we add two special nodes to the ends of the lists: the header and trailer nodes The header node goes before the first list element. It has a valid next link but a null prev link. The trailer node goes after the last element. It has a valid prev reference but a null next reference. The header and trailer nodes are sentinel or dummy nodes because they do not store elements 91

92

93 Circular Lists No end and no beginning of the list, only one pointer as an entry point Circular doubly linked list with a sentinel is an elegant implementation of a stack or a queue 93

94 Trees a tree represents a hierarchy examples: organization structure of a corporation, tables of contents 94

95 Other examples File system structure 95

96 Trees: Definitions A is the root node. B is the parent of D and E. A is ancestor of D and E. D and E are descendants of A. C is the sibling of B D and E are the children of B. D, E, F, G, I are leaves. 96

97 Trees: Definitions A, B, C, H are internal nodes The depth (level) of E is 2 The height of the tree is 3 The degree of node B is 2 97

98 Binary Tree Binary tree: ordered tree with all internal nodes of degree 2 98

99 Example of Binary Tree Representing arithmetic expressions 99

100 More examples Decision trees 100

101 ADT for trees isempty, number of elements parent, children, siblings is_leaf, is_root Left and right child for binary tree 101

102 Representing BinaryTrees BinaryTree: Root Parent: BinaryTree LeftChild: BinaryTree RightChild: BinaryTree 102

103 The Node Structure Each node in the tree contains key[x] key left[x] pointer to left child right[x] pt. to right child p[x] pt. to parent node 103

104 Example 104

105 How about general trees? Several possibilities : each node stores an array/list of child pointers. Use a binary tree implementation! 105

106 Binary tree implementation Root 106

107 Tree Traversals Visit every node in the tree. How do we do it in an array, list,? 107

108 Pre order traversal preorder(v) visit node v for each child w of v do recursively perform preorder(w) 108

109 Applications Reading a document from beginning to end. 109

110 Post order traversal postorder(v) for each child w of v do recursively perform postorder(w) visit node v 110

111 Applications Disk usage in unix 111

112 Applications Evaluation of arithmetic expressions 112

113 In order traversal InOrder(v) InOrder(left child of v) visit node v Inorder(right child of v) A B D C E F 113

114 Applications Printing an arithmetic expression print ( before traversing left subtree print ) after traversing right subtree 114

115 Applications Printing an arithmetic expression 115

116 Teaser Suppose the in order traversal of a binary tree is H, B, I, A, D, C, F, E, G and its post order traversal is H, I, B, D, F, G, E, C, A Can you recover the actual binary tree? 116

117 Teaser Given a tree, we want to print the nodes in ascending order of their levels, and within each level from left to right. A, B, C, D, E, F, G, H, I 117

118 Dictionary Dictionary ADT a dynamic set with methods: Search(S, k) an access operation that returns a pointer x to an element where x.key = k Insert(S, x) a manipulation operation that adds the element pointed to by x to S Delete(S, x) a manipulation operation that removes the element pointed to by x from S An element has a key part and a satellite data part 118

119 Dictionaries Dictionaries store elements so that they can be located quickly using keys A dictionary may hold bank accounts each account is an object that is identified by an account number each account stores a wealth of additional information including the current balance, the name and address of the account holder, and the history of deposits and withdrawals performed an application wishing to operate on an account would have to provide the account number as a search key 119

120 Dictionaries Supporting order (methods min, max, successor, predecessor ) is not required, thus it is enough that keys are comparable for equality 120

121 Dictionaries Different data structures to realize dictionaries arrays, linked lists (inefficient) Hash table (used in Java...) Binary trees Red/Black trees AVL trees B trees In Java: java.util.dictionary abstract class java.util.map interface 121

122 A List Based Implementation Unordered list searching takes O(n) time inserting takes O(1) time Ordered list searching takes O(n) time inserting takes O(n) time Using array would definitely improve search time. 122

123 Binary Search Narrow down the search range in stages findelement(22) 123

124 Running Time The range of candidate items to be searched is halved after comparing the key with the middle element Binary search runs in O(lg n) time. T(n) <= T(n/2) + 1 <= T(n/4) <=... T(n/2 ) + i i We also have the base case T(1) = 1 which implies that T(n) <= log n 2 124

125 Binary Search The binary search process can be represented by a tree 125

126 Binary Search Trees A binary search tree is a binary tree T such that each internal node stores an item (k,e) of a dictionary keys stored at nodes in the left subtree of v are less than or equal to k keys stored at nodes in the right subtree of v are greater than or equal to k 126

127 Examples How to print the keys in a sorted order? 127

128 Searching a BST To find an element with key k in a tree T compare k with key[root[t]] if k < key[root[t]], search for k in left[root[t]] otherwise, search for k in right[root[t]] 128

129 Pseudocode for BST Search Recursive version Search(T,k) x root[t] if x = NIL then return NIL if k = key[x] then return x if k < key[x] then return Search(left[x],k) else return Search(right[x],k) Iterative version Search(T,k) 01 x root[t] 02 while x NIL and k key[x] do 03 if k < key[x] 04 then x left[x] 05 else x right[x] 06 return x 129

130 Search Examples Search(T, 11) 130

131 Search Examples (2) Search(T, 6) 131

132 Analysis of Search Running time on tree of height h is O(h) After the insertion of n keys, the worst case running time of searching is O(n) 132

133 Analysis of Search How good or bad can the height get? In the bad case : height = n In the good case : height = log n 2 why? 133

134 BST Minimum (Maximum) Find the minimum key in a tree rooted at x (compare to a solution for heaps) TreeMinimum(x) 01 while left[x] NIL 02 do x left[x] 03 return x Running time O(h), i.e., it is proportional to the height of the tree 134

135 Successor Given x, find the node with the smallest key greater than key[x] We can distinguish two cases, depending on the right subtree of x Case 1 right subtree of x is nonempty successor is leftmost node in the right subtree (Why?) this can be done by returning TreeMinimum(right [x]) 135

136 Successor (2) Case 2 the right subtree of x is empty successor is the lowest ancestor of x whose left child is also an ancestor of x (Why?) 136

137 Successor Pseudocode TreeSuccessor(x) if right[x] NIL then return TreeMinimum(right[x]) y p[x] while y NIL and x = right[y] x y y p[y] return y For a tree of height h, the running time is O(h) 137

138 BST Insertion The basic idea is similar to searching take an element z (whose left and right children are NIL) and insert it into T find place in T where z belongs (as if searching for z), and add z there The running on a tree of height h is O(h), i.e., it is proportional to the height of the tree 138

139 BST Insertion Pseudo Code TreeInsert(T,z) y NIL x root[t] while x NIL y x if key[z] < key[x] then x left[x] else x right[x] p[z] y if y = NIL then root[t] z else if key[z] < key[y] then left[y] z else right[y] z 139

140 BST Insertion Example Insert 8 140

141 BST Insertion: Worst Case In what kind of sequence should the insertions be made to produce a BST of height n? 141

142 BST Sorting Use TreeInsert and InorderTreeWalk to sort a list of n elements, A TreeSort(A) 01 root[t] NIL 02 for i 1 to n 03 TreeInsert(T,A[i]) 04 InorderTreeWalk(root[T]) 142

143 BST Sorting (2) Sort the following numbers Build a binary search tree Call InorderTreeWalk

144 Deletion Delete node x from a tree T We can distinguish three cases x has no children x has one child x has two children 144

145 Deletion Case 1 If x has no children just remove x 145

146 Deletion Case 2 If x has exactly one child, then to delete x, simply make p[x] point to that child 146

147 Deletion Case 3 If x has two children, then to delete it we have to find its successor (or predecessor) y remove y (note that y has at most one child why?) replace x with y 147

148 Delete Pseudocode TreeDelete(T,z) 01 if left[z] = NIL or right[z] = NIL 02 then y z 03 else y TreeSuccessor(z) 04 if left[y] NIL 05 then x left[y] 06 else x right[y] 07 if x NIL 08 then p[x] p[y] 09 if p[y] = NIL 10 then root[t] x 11 else if y = left[p[y]] 12 then left[p[y]] x 13 else right[p[y]] x 14 if y z 15 then key[z] key[y] //copy all fileds of y 16 return y 148

149 Problems with BST Running time of Insert and Delete depend upon the height of the BST. But the height of a BST on n nodes can be close to n. 149

150 named after inventors Adel son Vel skii & Landis AVL Trees An AVL Tree is a binary search tree that has the height balance property: for every internal node v of T, the heights of the children of v can differ by at most 1. This assures that the height of an AVL tree storing n keys is O (log n)

151 Insertion in an AVL Tree Insertion is as in a binary search tree Always done by expanding an external node. Example: before insertion after insertion 151

152 Restoring the Height Balance Property Like a heap that requires upheaping to restore heap order property, we may have to fix the AVL tree after insertion if the height balance property is now violated Insertion changes heights of nodes on path from new unbalanced 44 nodes node w to root of tree Idea: find and fix unbalanced nodes with restructuring operation

153 Restoring the Height Balance Property Let z be the first unbalanced ancestor of the new inserted node. y is a child of z and x is a child of y. Restructure(x) 2. Let (a, b, c) be a left to right (inorder) listing of x, y, and z, and let (T0, T1, T2, T3) be an inorder listing of the 4 subtrees of x, y, and not rooted at x, y, or z 2. Replace the subtree rooted at z with a new subtree rooted at b 3. Let a be the left child of b and T0 & T1 be the left and right subtrees of a, respectively 4. Let c be the right child of b and let T2 and T3 be the left and right subtrees of c, respectively 153

154 Insertion Example, continued

155 Restructuring: Notes Restructuring after insertion is guaranteed to restore height balance property to entire tree (i.e., we just have to do it once) It s an O(1) operation But overall insertion is O(log n) because we had to do the binary search tree insertion first Similarly deletion can be done in O(log n) time. 155

Binary Trees. Recursive definition. Is this a binary tree?

Binary Trees. Recursive definition. Is this a binary tree? Binary Search Trees Binary Trees Recursive definition 1. An empty tree is a binary tree 2. A node with two child subtrees is a binary tree 3. Only what you get from 1 by a finite number of applications

More information

Design and Analysis of Algorithms Lecture- 9: Binary Search Trees

Design and Analysis of Algorithms Lecture- 9: Binary Search Trees Design and Analysis of Algorithms Lecture- 9: Binary Search Trees Dr. Chung- Wen Albert Tsao 1 Binary Search Trees Data structures that can support dynamic set operations. Search, Minimum, Maximum, Predecessor,

More information

Data Structures and Algorithms

Data Structures and Algorithms Asymptotic Analysis Data Structures and Algorithms Algorithm: Outline, the essence of a computational procedure, step-by-step instructions Program: an implementation of an algorithm in some programming

More information

Data Structures and Algorithms. Part 2

Data Structures and Algorithms. Part 2 1 Data Structures and Algorithms Part 2 Werner Nutt 2 Acknowledgments The course follows the book Introduction to Algorithms, by Cormen, Leiserson, Rivest and Stein, MIT Press [CLRST]. Many examples displayed

More information

Data Structures Question Bank Multiple Choice

Data Structures Question Bank Multiple Choice Section 1. Fundamentals: Complexity, Algorthm Analysis 1. An algorithm solves A single problem or function Multiple problems or functions Has a single programming language implementation 2. A solution

More information

Binary Search Trees. 1. Inorder tree walk visit the left subtree, the root, and right subtree.

Binary Search Trees. 1. Inorder tree walk visit the left subtree, the root, and right subtree. Binary Search Trees Search trees are data structures that support many dynamic set operations including Search, Minimum, Maximum, Predecessor, Successor, Insert, and Delete. Thus, a search tree can be

More information

Binary search trees :

Binary search trees : Binary search trees Binary search trees : Search trees are data structures that generally offer the following dynamic-set operations : SEARCH MINIMUM MAXIMUM PREDECESSOR SUCCESSOR INSERT DELETE Basic operations

More information

Data Structures and Algorithms Chapter 2

Data Structures and Algorithms Chapter 2 1 Data Structures and Algorithms Chapter 2 Werner Nutt 2 Acknowledgments The course follows the book Introduction to Algorithms, by Cormen, Leiserson, Rivest and Stein, MIT Press [CLRST]. Many examples

More information

Data Structures. Dynamic Sets

Data Structures. Dynamic Sets Data Structures Binary Search Tree Dynamic Sets Elements have a key and satellite data Dynamic sets support queries such as: Search(S, k) Minimum(S) Maximum(S) Successor(S, x) Predecessor(S, x) Insert(S,

More information

Binary Search Trees, etc.

Binary Search Trees, etc. Chapter 12 Binary Search Trees, etc. Binary Search trees are data structures that support a variety of dynamic set operations, e.g., Search, Minimum, Maximum, Predecessors, Successors, Insert, and Delete.

More information

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree 0/2/ Preview Binary Tree Tree Binary Tree Property functions In-order walk Pre-order walk Post-order walk Search Tree Insert an element to the Tree Delete an element form the Tree A binary tree is a tree

More information

Binary Search Trees. Motivation. Binary search tree. Tirgul 7

Binary Search Trees. Motivation. Binary search tree. Tirgul 7 Tirgul 7 Binary Search Trees Motivation We would like to have a dynamic ADT that efficiently supports the following common operations: Insert & Delete Search for an element Minimum & Maximum Predecessor

More information

Basic Data Structures (Version 7) Name:

Basic Data Structures (Version 7) Name: Prerequisite Concepts for Analysis of Algorithms Basic Data Structures (Version 7) Name: Email: Concept: mathematics notation 1. log 2 n is: Code: 21481 (A) o(log 10 n) (B) ω(log 10 n) (C) Θ(log 10 n)

More information

Binary search trees. Support many dynamic-set operations, e.g. Search. Minimum. Maximum. Insert. Delete ...

Binary search trees. Support many dynamic-set operations, e.g. Search. Minimum. Maximum. Insert. Delete ... Binary search trees Support many dynamic-set operations, e.g. Search Minimum Maximum Insert Delete... Can be used as dictionary, priority queue... you name it Running time depends on height of tree: 1

More information

Course Review for. Cpt S 223 Fall Cpt S 223. School of EECS, WSU

Course Review for. Cpt S 223 Fall Cpt S 223. School of EECS, WSU Course Review for Midterm Exam 1 Cpt S 223 Fall 2011 1 Midterm Exam 1 When: Friday (10/14) 1:10-2pm Where: in class Closed book, closed notes Comprehensive Material for preparation: Lecture slides & in-class

More information

Lecture 6: Analysis of Algorithms (CS )

Lecture 6: Analysis of Algorithms (CS ) Lecture 6: Analysis of Algorithms (CS583-002) Amarda Shehu October 08, 2014 1 Outline of Today s Class 2 Traversals Querying Insertion and Deletion Sorting with BSTs 3 Red-black Trees Height of a Red-black

More information

CS301 - Data Structures Glossary By

CS301 - Data Structures Glossary By CS301 - Data Structures Glossary By Abstract Data Type : A set of data values and associated operations that are precisely specified independent of any particular implementation. Also known as ADT Algorithm

More information

Course Review for Finals. Cpt S 223 Fall 2008

Course Review for Finals. Cpt S 223 Fall 2008 Course Review for Finals Cpt S 223 Fall 2008 1 Course Overview Introduction to advanced data structures Algorithmic asymptotic analysis Programming data structures Program design based on performance i.e.,

More information

DATA STRUCTURES AND ALGORITHMS

DATA STRUCTURES AND ALGORITHMS DATA STRUCTURES AND ALGORITHMS UNIT 1 - LINEAR DATASTRUCTURES 1. Write down the definition of data structures? A data structure is a mathematical or logical way of organizing data in the memory that consider

More information

Course Review. Cpt S 223 Fall 2009

Course Review. Cpt S 223 Fall 2009 Course Review Cpt S 223 Fall 2009 1 Final Exam When: Tuesday (12/15) 8-10am Where: in class Closed book, closed notes Comprehensive Material for preparation: Lecture slides & class notes Homeworks & program

More information

DDS Dynamic Search Trees

DDS Dynamic Search Trees DDS Dynamic Search Trees 1 Data structures l A data structure models some abstract object. It implements a number of operations on this object, which usually can be classified into l creation and deletion

More information

Module 1: Asymptotic Time Complexity and Intro to Abstract Data Types

Module 1: Asymptotic Time Complexity and Intro to Abstract Data Types Module 1: Asymptotic Time Complexity and Intro to Abstract Data Types Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu

More information

Trees. CSE 373 Data Structures

Trees. CSE 373 Data Structures Trees CSE 373 Data Structures Readings Reading Chapter 7 Trees 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical relationships File directories

More information

Department of Computer Science and Technology

Department of Computer Science and Technology UNIT : Stack & Queue Short Questions 1 1 1 1 1 1 1 1 20) 2 What is the difference between Data and Information? Define Data, Information, and Data Structure. List the primitive data structure. List the

More information

ECE250: Algorithms and Data Structures Binary Search Trees (Part A)

ECE250: Algorithms and Data Structures Binary Search Trees (Part A) ECE250: Algorithms and Data Structures Binary Search Trees (Part A) Ladan Tahvildari, PEng, SMIEEE Associate Professor Software Technologies Applied Research (STAR) Group Dept. of Elect. & Comp. Eng. University

More information

Lecture: Analysis of Algorithms (CS )

Lecture: Analysis of Algorithms (CS ) Lecture: Analysis of Algorithms (CS583-002) Amarda Shehu Fall 2017 1 Binary Search Trees Traversals, Querying, Insertion, and Deletion Sorting with BSTs 2 Example: Red-black Trees Height of a Red-black

More information

Theory & Algorithms 15/01/04. Red-Black Trees. Nicolas Wack, Sylvain Le Groux

Theory & Algorithms 15/01/04. Red-Black Trees. Nicolas Wack, Sylvain Le Groux Theory & Algorithms Red-Black Trees 15/01/04 Nicolas Wack, Sylvain Le Groux Balanced search trees Balanced search tree: A search-tree data structure for which a height of O(lg n) is guaranteed when implementing

More information

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F))

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F)) DHANALAKSHMI COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES UNIT IV NONLINEAR DATA STRUCTURES Part A 1. Define Tree [N/D 08]

More information

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES CH4.2-4.3. ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER

More information

CS:3330 (22c:31) Algorithms

CS:3330 (22c:31) Algorithms What s an Algorithm? CS:3330 (22c:31) Algorithms Introduction Computer Science is about problem solving using computers. Software is a solution to some problems. Algorithm is a design inside a software.

More information

How much space does this routine use in the worst case for a given n? public static void use_space(int n) { int b; int [] A;

How much space does this routine use in the worst case for a given n? public static void use_space(int n) { int b; int [] A; How much space does this routine use in the worst case for a given n? public static void use_space(int n) { int b; int [] A; } if (n

More information

Cpt S 223 Fall Cpt S 223. School of EECS, WSU

Cpt S 223 Fall Cpt S 223. School of EECS, WSU Course Review Cpt S 223 Fall 2012 1 Final Exam When: Monday (December 10) 8 10 AM Where: in class (Sloan 150) Closed book, closed notes Comprehensive Material for preparation: Lecture slides & class notes

More information

INSTITUTE OF AERONAUTICAL ENGINEERING

INSTITUTE OF AERONAUTICAL ENGINEERING INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad - 500 043 COMPUTER SCIENCE AND ENGINEERING TUTORIAL QUESTION BANK Course Name Course Code Class Branch DATA STRUCTURES ACS002 B. Tech

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms About the course (objectives, outline, recommended reading) Problem solving Notions of Algorithmics (growth of functions, efficiency, programming model, example analysis)

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 10: Search and Heaps MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Search and Heaps 2 Linear Search Binary Search Introduction to trees Priority Queues Heaps Linear Search

More information

CS 216 Exam 1 Fall SOLUTION

CS 216 Exam 1 Fall SOLUTION CS 216 Exam 1 Fall 2004 - SOLUTION Name: Lab Section: Email Address: Student ID # This exam is closed note, closed book. You will have an hour and fifty minutes total to complete the exam. You may NOT

More information

CSE2331/5331. Topic 6: Binary Search Tree. Data structure Operations CSE 2331/5331

CSE2331/5331. Topic 6: Binary Search Tree. Data structure Operations CSE 2331/5331 CSE2331/5331 Topic 6: Binary Search Tree Data structure Operations Set Operations Maximum Extract-Max Insert Increase-key We can use priority queue (implemented by heap) Search Delete Successor Predecessor

More information

DATA STRUCTURES AND ALGORITHMS

DATA STRUCTURES AND ALGORITHMS DATA STRUCTURES AND ALGORITHMS For COMPUTER SCIENCE DATA STRUCTURES &. ALGORITHMS SYLLABUS Programming and Data Structures: Programming in C. Recursion. Arrays, stacks, queues, linked lists, trees, binary

More information

Binary Trees, Binary Search Trees

Binary Trees, Binary Search Trees Binary Trees, Binary Search Trees Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search, insert, delete)

More information

Chapter 2: Basic Data Structures

Chapter 2: Basic Data Structures Chapter 2: Basic Data Structures Basic Data Structures Stacks Queues Vectors, Linked Lists Trees (Including Balanced Trees) Priority Queues and Heaps Dictionaries and Hash Tables Spring 2014 CS 315 2 Two

More information

Binary Search Trees. July 13th, Computer Information Systems. c 2009 Vaidė Narváez

Binary Search Trees. July 13th, Computer Information Systems. c 2009 Vaidė Narváez Binary Search Trees Vaidė Narváez Computer Information Systems July 13th, 2010 Introduction Dynamic set operations: Search, Minimum, Maximum Predecessor, Successor Insert, Delete Time proportional to the

More information

Plotting run-time graphically. Plotting run-time graphically. CS241 Algorithmics - week 1 review. Prefix Averages - Algorithm #1

Plotting run-time graphically. Plotting run-time graphically. CS241 Algorithmics - week 1 review. Prefix Averages - Algorithm #1 CS241 - week 1 review Special classes of algorithms: logarithmic: O(log n) linear: O(n) quadratic: O(n 2 ) polynomial: O(n k ), k 1 exponential: O(a n ), a > 1 Classifying algorithms is generally done

More information

3. Fundamental Data Structures

3. Fundamental Data Structures 3. Fundamental Data Structures CH08-320201: Algorithms and Data Structures 233 Data Structures Definition (recall): A data structure is a way to store and organize data in order to facilitate access and

More information

Trees. (Trees) Data Structures and Programming Spring / 28

Trees. (Trees) Data Structures and Programming Spring / 28 Trees (Trees) Data Structures and Programming Spring 2018 1 / 28 Trees A tree is a collection of nodes, which can be empty (recursive definition) If not empty, a tree consists of a distinguished node r

More information

1. Attempt any three of the following: 15

1. Attempt any three of the following: 15 (Time: 2½ hours) Total Marks: 75 N. B.: (1) All questions are compulsory. (2) Make suitable assumptions wherever necessary and state the assumptions made. (3) Answers to the same question must be written

More information

Elementary Data Structures. Stacks, Queues, & Lists Amortized analysis Trees

Elementary Data Structures. Stacks, Queues, & Lists Amortized analysis Trees Elementary Data Structures Stacks, Queues, & Lists Amortized analysis Trees The Stack ADT ( 2.1.1) The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in first-out scheme Think

More information

Topics on the Midterm

Topics on the Midterm Midterm Review Topics on the Midterm Data Structures & Object-Oriented Design Run-Time Analysis Linear Data Structures The Java Collections Framework Recursion Trees Priority Queues & Heaps Maps, Hash

More information

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305 Q.1 If h is any hashing function and is used to hash n keys in to a table of size m, where n

More information

MLR Institute of Technology

MLR Institute of Technology MLR Institute of Technology Laxma Reddy Avenue, Dundigal, Quthbullapur (M), Hyderabad 500 043 Phone Nos: 08418 204066 / 204088, Fax : 08418 204088 TUTORIAL QUESTION BANK Course Name : DATA STRUCTURES Course

More information

The tree data structure. Trees COL 106. Amit Kumar Shweta Agrawal. Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo

The tree data structure. Trees COL 106. Amit Kumar Shweta Agrawal. Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo The tree data structure 1 Trees COL 106 Amit Kumar Shweta Agrawal Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo 1 Trees The tree data structure 3 A rooted tree data structure stores

More information

21# 33# 90# 91# 34# # 39# # # 31# 98# 0# 1# 2# 3# 4# 5# 6# 7# 8# 9# 10# #

21# 33# 90# 91# 34# # 39# # # 31# 98# 0# 1# 2# 3# 4# 5# 6# 7# 8# 9# 10# # 1. Prove that n log n n is Ω(n). York University EECS 11Z Winter 1 Problem Set 3 Instructor: James Elder Solutions log n n. Thus n log n n n n n log n n Ω(n).. Show that n is Ω (n log n). We seek a c >,

More information

Course Review. Cpt S 223 Fall 2010

Course Review. Cpt S 223 Fall 2010 Course Review Cpt S 223 Fall 2010 1 Final Exam When: Thursday (12/16) 8-10am Where: in class Closed book, closed notes Comprehensive Material for preparation: Lecture slides & class notes Homeworks & program

More information

III Data Structures. Dynamic sets

III Data Structures. Dynamic sets III Data Structures Elementary Data Structures Hash Tables Binary Search Trees Red-Black Trees Dynamic sets Sets are fundamental to computer science Algorithms may require several different types of operations

More information

CSE 332 Winter 2015: Midterm Exam (closed book, closed notes, no calculators)

CSE 332 Winter 2015: Midterm Exam (closed book, closed notes, no calculators) _ UWNetID: Lecture Section: A CSE 332 Winter 2015: Midterm Exam (closed book, closed notes, no calculators) Instructions: Read the directions for each question carefully before answering. We will give

More information

(Refer Slide Time: 1:27)

(Refer Slide Time: 1:27) Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 1 Introduction to Data Structures and Algorithms Welcome to data

More information

Partha Sarathi Mandal

Partha Sarathi Mandal MA 252: Data Structures and Algorithms Lecture 16 http://www.iitg.ernet.in/psm/indexing_ma252/y12/index.html Partha Sarathi Mandal Dept. of Mathematics, IIT Guwahati Deletion in BST Three cases Case 1:

More information

ECE250: Algorithms and Data Structures Midterm Review

ECE250: Algorithms and Data Structures Midterm Review ECE250: Algorithms and Data Structures Midterm Review Ladan Tahvildari, PEng, SMIEEE Associate Professor Software Technologies Applied Research (STAR) Group Dept. of Elect. & Comp. Eng. University of Waterloo

More information

Data Structures and Algorithms Week 4

Data Structures and Algorithms Week 4 Data Structures and Algorithms Week. About sorting algorithms. Heapsort Complete binary trees Heap data structure. Quicksort a popular algorithm very fast on average Previous Week Divide and conquer Merge

More information

CS 303 Design and Analysis of Algorithms

CS 303 Design and Analysis of Algorithms Mid-term CS 303 Design and Analysis of Algorithms Review For Midterm Dong Xu (Based on class note of David Luebke) 12:55-1:55pm, Friday, March 19 Close book Bring your calculator 30% of your final score

More information

Quiz 1 Solutions. (a) f(n) = n g(n) = log n Circle all that apply: f = O(g) f = Θ(g) f = Ω(g)

Quiz 1 Solutions. (a) f(n) = n g(n) = log n Circle all that apply: f = O(g) f = Θ(g) f = Ω(g) Introduction to Algorithms March 11, 2009 Massachusetts Institute of Technology 6.006 Spring 2009 Professors Sivan Toledo and Alan Edelman Quiz 1 Solutions Problem 1. Quiz 1 Solutions Asymptotic orders

More information

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text) Lec 17 April 8 Topics: binary Trees expression trees Binary Search Trees (Chapter 5 of text) Trees Linear access time of linked lists is prohibitive Heap can t support search in O(log N) time. (takes O(N)

More information

CS8391-DATA STRUCTURES QUESTION BANK UNIT I

CS8391-DATA STRUCTURES QUESTION BANK UNIT I CS8391-DATA STRUCTURES QUESTION BANK UNIT I 2MARKS 1.Define data structure. The data structure can be defined as the collection of elements and all the possible operations which are required for those

More information

Sample Exam 1 Questions

Sample Exam 1 Questions CSE 331 Sample Exam 1 Questions Name DO NOT START THE EXAM UNTIL BEING TOLD TO DO SO. If you need more space for some problem, you can link to extra space somewhere else on this exam including right here.

More information

Algorithm Analysis. (Algorithm Analysis ) Data Structures and Programming Spring / 48

Algorithm Analysis. (Algorithm Analysis ) Data Structures and Programming Spring / 48 Algorithm Analysis (Algorithm Analysis ) Data Structures and Programming Spring 2018 1 / 48 What is an Algorithm? An algorithm is a clearly specified set of instructions to be followed to solve a problem

More information

Algorithms. 演算法 Data Structures (focus on Trees)

Algorithms. 演算法 Data Structures (focus on Trees) 演算法 Data Structures (focus on Trees) Professor Chien-Mo James Li 李建模 Graduate Institute of Electronics Engineering National Taiwan University 1 Dynamic Set Dynamic set is a set of elements that can grow

More information

ANALYSIS OF ALGORITHMS

ANALYSIS OF ALGORITHMS ANALYSIS OF ALGORITHMS Running Time Pseudo-Code Asymptotic Notation Asymptotic Analysis Mathematical facts T(n) n = 4 Input Algorithm Output 1 Average Case vs. Worst Case Running Time of an Algorithm An

More information

CS 8391 DATA STRUCTURES

CS 8391 DATA STRUCTURES DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK CS 8391 DATA STRUCTURES UNIT- I PART A 1. Define: data structure. A data structure is a way of storing and organizing data in the memory for

More information

Summer Final Exam Review Session August 5, 2009

Summer Final Exam Review Session August 5, 2009 15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

More information

CSE 3101: Introduction to the Design and Analysis of Algorithms. Office hours: Wed 4-6 pm (CSEB 3043), or by appointment.

CSE 3101: Introduction to the Design and Analysis of Algorithms. Office hours: Wed 4-6 pm (CSEB 3043), or by appointment. CSE 3101: Introduction to the Design and Analysis of Algorithms Instructor: Suprakash Datta (datta[at]cse.yorku.ca) ext 77875 Lectures: Tues, BC 215, 7 10 PM Office hours: Wed 4-6 pm (CSEB 3043), or by

More information

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May www.jwjobs.net R10 SET - 1 II B. Tech I Semester, Supplementary Examinations, May - 2012 (Com. to CSE, IT, ECC ) Time: 3 hours Max Marks: 75 *******-****** 1. a) Which of the given options provides the

More information

CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators)

CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators) Name: Email address: Quiz Section: CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators) Instructions: Read the directions for each question carefully before answering. We will

More information

Comparisons. Θ(n 2 ) Θ(n) Sorting Revisited. So far we talked about two algorithms to sort an array of numbers. What is the advantage of merge sort?

Comparisons. Θ(n 2 ) Θ(n) Sorting Revisited. So far we talked about two algorithms to sort an array of numbers. What is the advantage of merge sort? So far we have studied: Comparisons Insertion Sort Merge Sort Worst case Θ(n 2 ) Θ(nlgn) Best case Θ(n) Θ(nlgn) Sorting Revisited So far we talked about two algorithms to sort an array of numbers What

More information

Algorithms. AVL Tree

Algorithms. AVL Tree Algorithms AVL Tree Balanced binary tree The disadvantage of a binary search tree is that its height can be as large as N-1 This means that the time needed to perform insertion and deletion and many other

More information

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR STUDENT IDENTIFICATION NO MULTIMEDIA COLLEGE JALAN GURNEY KIRI 54100 KUALA LUMPUR FIFTH SEMESTER FINAL EXAMINATION, 2014/2015 SESSION PSD2023 ALGORITHM & DATA STRUCTURE DSEW-E-F-2/13 25 MAY 2015 9.00 AM

More information

Chapter 2: Complexity Analysis

Chapter 2: Complexity Analysis Chapter 2: Complexity Analysis Objectives Looking ahead in this chapter, we ll consider: Computational and Asymptotic Complexity Big-O Notation Properties of the Big-O Notation Ω and Θ Notations Possible

More information

The questions will be short answer, similar to the problems you have done on the homework

The questions will be short answer, similar to the problems you have done on the homework Introduction The following highlights are provided to give you an indication of the topics that you should be knowledgeable about for the midterm. This sheet is not a substitute for the homework and the

More information

Data structures. Organize your data to support various queries using little time and/or space

Data structures. Organize your data to support various queries using little time and/or space Data structures Organize your data to support various queries using little time and/or space Given n elements A[1..n] Support SEARCH(A,x) := is x in A? Trivial solution: scan A. Takes time Θ(n) Best possible

More information

Comparisons. Heaps. Heaps. Heaps. Sorting Revisited. Heaps. So far we talked about two algorithms to sort an array of numbers

Comparisons. Heaps. Heaps. Heaps. Sorting Revisited. Heaps. So far we talked about two algorithms to sort an array of numbers So far we have studied: Comparisons Tree is completely filled on all levels except possibly the lowest, which is filled from the left up to a point Insertion Sort Merge Sort Worst case Θ(n ) Θ(nlgn) Best

More information

CS8391-DATA STRUCTURES

CS8391-DATA STRUCTURES ST.JOSEPH COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERI NG CS8391-DATA STRUCTURES QUESTION BANK UNIT I 2MARKS 1.Explain the term data structure. The data structure can be defined

More information

Module 2: Classical Algorithm Design Techniques

Module 2: Classical Algorithm Design Techniques Module 2: Classical Algorithm Design Techniques Dr. Natarajan Meghanathan Associate Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Module

More information

Fundamentals of Data Structure

Fundamentals of Data Structure Fundamentals of Data Structure Set-1 1. Which if the following is/are the levels of implementation of data structure A) Abstract level B) Application level C) Implementation level D) All of the above 2.

More information

Analysis of Algorithms

Analysis of Algorithms Analysis of Algorithms Trees-I Prof. Muhammad Saeed Tree Representation.. Analysis Of Algorithms 2 .. Tree Representation Analysis Of Algorithms 3 Nomenclature Nodes (13) Size (13) Degree of a node Depth

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

Overview of Data. 1. Array 2. Linked List 3. Stack 4. Queue

Overview of Data. 1. Array 2. Linked List 3. Stack 4. Queue Overview of Data A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. Below

More information

CS61BL. Lecture 3: Asymptotic Analysis Trees & Tree Traversals Stacks and Queues Binary Search Trees (and other trees)

CS61BL. Lecture 3: Asymptotic Analysis Trees & Tree Traversals Stacks and Queues Binary Search Trees (and other trees) CS61BL Lecture 3: Asymptotic Analysis Trees & Tree Traversals Stacks and Queues Binary Search Trees (and other trees) Program Efficiency How much memory a program uses Memory is cheap How much time a

More information

Algorithm Analysis. Applied Algorithmics COMP526. Algorithm Analysis. Algorithm Analysis via experiments

Algorithm Analysis. Applied Algorithmics COMP526. Algorithm Analysis. Algorithm Analysis via experiments Applied Algorithmics COMP526 Lecturer: Leszek Gąsieniec, 321 (Ashton Bldg), L.A.Gasieniec@liverpool.ac.uk Lectures: Mondays 4pm (BROD-107), and Tuesdays 3+4pm (BROD-305a) Office hours: TBA, 321 (Ashton)

More information

Trees and Graphs Shabsi Walfish NYU - Fundamental Algorithms Summer 2006

Trees and Graphs Shabsi Walfish NYU - Fundamental Algorithms Summer 2006 Trees and Graphs Basic Definitions Tree: Any connected, acyclic graph G = (V,E) E = V -1 n-ary Tree: Tree s/t all vertices of degree n+1 A root has degree n Binary Search Tree: A binary tree such that

More information

[ 11.2, 11.3, 11.4] Analysis of Algorithms. Complexity of Algorithms. 400 lecture note # Overview

[ 11.2, 11.3, 11.4] Analysis of Algorithms. Complexity of Algorithms. 400 lecture note # Overview 400 lecture note #0 [.2,.3,.4] Analysis of Algorithms Complexity of Algorithms 0. Overview The complexity of an algorithm refers to the amount of time and/or space it requires to execute. The analysis

More information

External Sorting Methods

External Sorting Methods External Sorting Methods Assumptions: data is too large to be held in main memory; data is read or written in blocks; 1 or more external devices available for sorting Sorting in main memory is cheap or

More information

COMP Analysis of Algorithms & Data Structures

COMP Analysis of Algorithms & Data Structures COMP 3170 - Analysis of Algorithms & Data Structures Shahin Kamali Binary Search Trees CLRS 12.2, 12.3, 13.2, read problem 13-3 University of Manitoba COMP 3170 - Analysis of Algorithms & Data Structures

More information

Data Structures Lecture 8

Data Structures Lecture 8 Fall 2017 Fang Yu Software Security Lab. Dept. Management Information Systems, National Chengchi University Data Structures Lecture 8 Recap What should you have learned? Basic java programming skills Object-oriented

More information

Binary Search Trees. Antonio Carzaniga. Faculty of Informatics University of Lugano. October 22, Antonio Carzaniga 1

Binary Search Trees. Antonio Carzaniga. Faculty of Informatics University of Lugano. October 22, Antonio Carzaniga 1 Binary Search Trees Antonio Carzaniga Faculty of Informatics University of Lugano October 22, 2008 2006 Antonio Carzaniga 1 Binary search trees Outline Randomized binary search trees 2006 Antonio Carzaniga

More information

AP Computer Science 4325

AP Computer Science 4325 4325 Instructional Unit Algorithm Design Techniques -divide-and-conquer The students will be -Decide whether an algorithm -classroom discussion -backtracking able to classify uses divide-and-conquer, -worksheets

More information

Bioinformatics Programming. EE, NCKU Tien-Hao Chang (Darby Chang)

Bioinformatics Programming. EE, NCKU Tien-Hao Chang (Darby Chang) Bioinformatics Programming EE, NCKU Tien-Hao Chang (Darby Chang) 1 Tree 2 A Tree Structure A tree structure means that the data are organized so that items of information are related by branches 3 Definition

More information

CS521 \ Notes for the Final Exam

CS521 \ Notes for the Final Exam CS521 \ Notes for final exam 1 Ariel Stolerman Asymptotic Notations: CS521 \ Notes for the Final Exam Notation Definition Limit Big-O ( ) Small-o ( ) Big- ( ) Small- ( ) Big- ( ) Notes: ( ) ( ) ( ) ( )

More information

Animations. 01/29/04 Lecture

Animations. 01/29/04 Lecture Animations BST: http://babbage.clarku.edu/~achou/cs160/examples/bst_animation/bst-example.html Rotations: http://babbage.clarku.edu/~achou/cs160/examples/bst_animation/index2.html RB-Trees: http://babbage.clarku.edu/~achou/cs160/examples/bst_animation/redblacktree-example.html

More information

PROGRAM EFFICIENCY & COMPLEXITY ANALYSIS

PROGRAM EFFICIENCY & COMPLEXITY ANALYSIS Lecture 03-04 PROGRAM EFFICIENCY & COMPLEXITY ANALYSIS By: Dr. Zahoor Jan 1 ALGORITHM DEFINITION A finite set of statements that guarantees an optimal solution in finite interval of time 2 GOOD ALGORITHMS?

More information

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted, [1] Big-O Analysis AVERAGE(n) 1. sum 0 2. i 0. while i < n 4. number input_number(). sum sum + number 6. i i + 1 7. mean sum / n 8. return mean Revision Statement no. of times executed 1 1 2 1 n+1 4 n

More information

Algorithms in Systems Engineering IE172. Midterm Review. Dr. Ted Ralphs

Algorithms in Systems Engineering IE172. Midterm Review. Dr. Ted Ralphs Algorithms in Systems Engineering IE172 Midterm Review Dr. Ted Ralphs IE172 Midterm Review 1 Textbook Sections Covered on Midterm Chapters 1-5 IE172 Review: Algorithms and Programming 2 Introduction to

More information

Binary search trees. Binary search trees are data structures based on binary trees that support operations on dynamic sets.

Binary search trees. Binary search trees are data structures based on binary trees that support operations on dynamic sets. COMP3600/6466 Algorithms 2018 Lecture 12 1 Binary search trees Reading: Cormen et al, Sections 12.1 to 12.3 Binary search trees are data structures based on binary trees that support operations on dynamic

More information