INDEX. 1 Write recursive program which computes the nth Fibonacci number,

Size: px
Start display at page:

Download "INDEX. 1 Write recursive program which computes the nth Fibonacci number,"

Transcription

1 INDEX S.No PROGRAMS LIST 1 Write recursive program which computes the nth Fibonacci number, 3 for appropriate values of n. Analyze behavior of the program Obtain the frequency count of the statement for various values of n. 2 Write recursive program for the following a) Write recursive C program for calculation of Factorial of an integer 4 b) Write recursive C program for calculation of GCD (n, m) 5 c) Write recursive C program for Towers of Hanoi : N disks are to be 7 transferred from peg S to peg D with Peg I as the intermediate peg. 3 a) Write C programs that use both recursive and non recursive functions to 11 perform Linear search for a Key value in a given list. b) Write C programs that use both recursive and non recursive functions to 12 perform Binary search for a Key value in a given list. c) Write C programs that use both recursive and non recursive functions to 13 perform Fibonacci search for a Key value in a given list. 4 a) Write C programs that implement Bubble sort, to sort a given list of integers in ascending order 15 b) Write C programs that implement Quick sort, to sort a given list of integers in ascending order c) Write C programs that implement Insertion sort, to sort a given list of integers in ascending order 5 a) Write C programs that implement Heap sort, to sort a given list of integers in ascending order b) Write C programs that implement Radix sort, to sort a given list of integers in ascending order c) Write C programs that implement Merge sort, to sort a given list of 25 integers in ascending order 6 a) Write C programs that implement stack (its operations) using arrays 27 b) Write C programs that implement stack (its operations) using Linked list 30 7 a) Write a C program that uses Stack operations to Convert infix expression 34 into postfix expression b) Write C programs that implement Queue (its operations) using arrays. 36 c) Write C programs that implement Queue (its operations) using linked 39 lists 8 a) Write a C program that uses functions to create a singly linked list 45 b) Write a C program that uses functions to perform insertion operation on a singly linked list c) Write a C program that uses functions to perform deletion operation on 50 P a g e 1 Department of Computer Science & Engineering GEC Page no

2 a singly linked list 9 d) Adding two large integers which are represented in linked list fashion. 53 e) Write a C program to reverse elements of a single linked list. 54 f) Write a C program to store a polynomial expression in memory using linked list g) Write a C program to representation the given Sparse matrix using arrays. 10 a) Write a C program to Create a Binary Tree of integers 59 b) Write a recursive C program, for Traversing a binary tree in preorder, in order and post order. 11 a) Write a C program to Create a BST 63 b) Write a C program to insert a note into a BST. 65 c) Write a C program to delete a note from a BST a) Write a C program to compute the shortest path of a graph using Dijkstra s algorithm 67 b) Write a C program to find the minimum spanning tree using Warshall s 69 Algorithm ADD ON PROGRAMS : 1 Write a C program on Circular Queue operations Write a C program on Evaluation on Postfix Expression Write a C program search the elements using Breadth First Search Algorithm & 108 Depth First Search Algorithm 4 Write a C program to perform various operations i.e., insertions and deletions on AVL trees P a g e 2 Department of Computer Science & Engineering GEC

3 Exercise 1: Write recursive program which computes the n th Fibonacci number, for appropriate values of n. Analyze behavior of the program Obtain the frequency count of the statement for various values of n. DESCRIPTION: C Programming Language: Using Recursion to Print the Fibonacci Series? The Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21,.. Begins with the terms 0 and 1 and has the property that each succeeding term is the sum of the two preceding terms. For this problem, we are asked to write a recursive function fib (n) that calculates the nth Fibonacci number. Recursion MUST be used. In an earlier problem, we where asked to do the exact same thing, except we where to NOT use recursion. For that problem, I used the following code (between the dotted lines): ALGORITHM : 1. Start. 2. Get the number n up to which Fibonacci series is generated. 3.Call to the function fib. P a g e 3 Department of Computer Science & Engineering GEC

4 4.stop Algorithm fib 1.start 2.if n=0 or 1 then return n 3.else return fib(n-1)+fib(n-2) 4. Stop. P a g e 4 Department of Computer Science & Engineering GEC

5 Exercise 2: a). Write recursive C program for calculation of Factorial of an integer Recursion : Procedures which call themselves within the body of their lambda expression are said to be recursive. In general, recursive procedures need a terminating condition (otherwise they will run forever) and a recursive step (describing how the computation should proceed). We will use one of MzScheme's procedures trace to illustrate the behavior of recursive procedures. The procedure trace shows the intermediate steps as the recursion proceeds as well as the intermediate values returned. For example, let us define a procedure for counting the factorial of a number. We know that equals 1 and we will use this as our terminating condition. Apart from that, we know that is the same as, which gives us our recursive step. We are now ready to define the procedure itself: (define fact (lambda (n) (if (= n 0) ; the terminating condition 1 ; returning 1 (* n (fact (- n 1)))))) ; the recursive step Let' see what happens if we try to compute the factorial of 7 by using the procedure trace: > (fact 7) 5040 > (trace fact) (fact) > (fact 7) (fact 7) (fact 6) (fact 5) (fact 4) (fact 3) (fact 2) (fact 1) (fact 0) > (untrace fact) (fact) P a g e 5 Department of Computer Science & Engineering GEC

6 ALGORITHM : 1. Start. 2. Get the number n to which Fcatorial value is to be generated. 3. Call to the function fact. 4.Stop Algorithm fact 1.Start 2.if n=0 or 1 then return 1 3.Else return n*fact(n-1) 4.Stop P a g e 6 Department of Computer Science & Engineering GEC

7 b). Write recursive C program for calculation of GCD (n, m) ALGORITHM : The GCD algorithm: Given m,n find gcd(m,n) We proved in class that the gcd can be found by repeatedly applying the division algorithm: a = bq + r. We start with a=m, b=n. The next pair is (b,r) [the quotient is not needed here]. We continue replacing a by the divisor and b by the remainder until we get a remainder 0. The last non-zero remainder is the gcd. This algorithm can be performed on a spreadsheet: A B C 1 m n a b r #DIV/0! 14 0 #DIV/0! #DIV/0! A B C 1 m n =A2 =B2 =MOD (A4,B4) 5 =B4 =C4 =MOD (A5,B5) 6 =B5 =C5 =MOD (A6,B6) 7 =B6 =C6 =MOD (A7,B7) 8 =B7 =C7 =MOD (A8,B8) 9 =B8 =C8 =MOD (A9,B9) 10 =B9 =C9 =MOD (A10,B10) 11 =B10 =C10 =MOD (A11,B11) 12 =B11 =C11 =MOD (A12,B12) 13 =B12 =C12 =MOD (A13,B13) 14 =B13 =C13 =MOD (A14,B14) Once row 5 is entered, it is copied to all lower rows. The spreadsheet automatically updates the formulas (that is what spreadsheets do!). A new pair of numbers can be entered in A2 and B2. Note that when a zero remainder occurs, the spreadsheet gives an error message on the following line. P a g e 7 Department of Computer Science & Engineering GEC

8 c). Write recursive C program for Towers of Hanoi: N disks are to be transferred from peg S to peg D with Peg I as the intermediate peg. DESCRIPTION: How to solve the Towers of Hanoi puzzle The Classical Towers of Hanoi - an initial position of all disks is on post 'A'. Fig. 1 The solution of the puzzle is to build the tower on post 'C'. Fig. 2 The Arbitrary Towers of Hanoi - at start, disks can be in any position provided that a bigger disk is never on top of the smaller one (see Fig. 3). At the end, disks should be in another arbitrary position. * ) Fig. 3 Solving the Tower of Hanoi P a g e 8 Department of Computer Science & Engineering GEC

9 'Solution' shortest path Recursive Solution: 1. Identify biggest discrepancy (=disk N) 2. If moveable to goal peg Then move Else 3. Subgoal: set-up (N 1)-disk tower on non-goal peg. 4. Go to Solving the Tower of Hanoi - 'regular' to 'perfect' Let's start thinking how to solve it. Let's, for the sake of clarity, assume that our goal is to set a 4 disk-high tower on peg 'C' - just like in the classical Towers of Hanoi (see Fig. 2). Let's assume we 'know' how to move a 'perfect' 3 disk-high tower. Then on the way of solving there is one special setup. Disk 4 is on peg 'A' and the 3 disk-high tower is on peg 'B' and target peg 'C' is empty. Fig. 4 From that position we have to move disk 4 from 'A' to 'C' and move by some magic the 3 disk-high tower from 'B' to 'C'. So think back. Forget the disks bigger than 3. Disk 3 is on peg 'C'. We need disk 3 on peg 'B'. To obtain that, we need disk 3 in place where it is now, free peg 'B' and disks 2 and 1 stacked on peg 'A'. So our goal now is to put disk 2 on P a g e 9 Department of Computer Science & Engineering GEC

10 peg 'A'. Fig. 5 Forget for the moment disk 3 (see Fig. 6). To be able to put disk 2 on peg 'A' we need to empty peg 'A' (above the thin blue line), disks smaller than disk 2 stacked on peg 'B'. So, our goal now is to put disk 1 on peg 'B'. As we can see, this is an easy task because disk 1 has no disk above it and peg 'B' is free. So let's move it. Fig. 6 Fig. 7 The steps above are made by the algorithm implemented in Towers of Hanoi when one clicks the "Help me" button. This button-function makes analysis of the current position and generates only one single move which leads to the solution. It is by design. When the 'Help me' button is clicked again, the algorithm repeats all steps of the analysis starting from the position of the biggest disk - in this example disk 4 - and generates the P a g e 10 Department of Computer Science & Engineering GEC

11 next move - disk 2 from peg 'C' to peg 'A'. Fig. 8 If one needs a recursive or iterative algorithm which generates the series of moves for solving arbitrary Towers of Hanoi then one should use a kind of back track programming, that is to remember previous steps of the analysis and not to repeat the analysis of the Towers from the ground. /*A recu rsiv e c prog ram for towe rs of hano i: N disk s are to be P a g e 11 Department of Computer Science & Engineering GEC

12 Exercise 3: a). Write C programs that use both recursive and non recursive functions to perform Linear search for a Key value in a given list. DESCRIPTION: If the data is sorted, a binary search may be done. Variables Lb and Ub keep track of the lower bound and upper bound of the array, respectively. We begin by examining the middle element of the array. If the key we are searching for is less than the middle element, then it must reside in the top half of the array. Thus, we set Ub to (M 1). This restricts our next iteration through the loop to the top half of the array. In this way, each iteration halves the size of the array to be searched. For example, the first iteration will leave 3 items to test. After the second iteration, there will be one item left to test. Therefore it takes only three iterations to find any number. This is a powerful method. Given an array of 1023 elements, we can narrow the search to 511 elements in one comparison. After another comparison, and we re looking at only 255 elements. In fact, we can search the entire array in only 10 comparisons. In addition to searching, we may wish to insert or delete entries. Unfortunately, an array is not a good arrangement for these operations. For example, to insert the number 18, we would need to shift A[3] A[6] down by one slot. Then we could copy number 18 into A[3]. A similar problem arises when deleting numbers. To improve the efficiency of insert and delete operations, linked lists may be used. ALGORITHM : Linear Search ( ): Description: Here A is an array having N elements. ITEM is the value to be searched. 1. Repeat for J = 1 to N 2. If (ITEM == A [J]) Then 3. Print: ITEM found at location J P a g e 12 Department of Computer Science & Engineering GEC

13 4. Return [End of If] [End of For Loop] 5. If (J > N) Then 6. Print: ITEM doesn t exist [End of If] 7. Exit P a g e 13 Department of Computer Science & Engineering GEC

14 b).write C programs that use both recursive and non recursive functions to perform Binary search for a Key value in a given list. ALGORITHM : Binary Search ( ): Description: Here A is a sorted array having N elements. ITEM is the value to be searched. BEG denotes first element and END denotes last element in the array. MID denotes the middle value. 1. Set BEG = 1 and END = N 2. Set MID = (BEG + END) / 2 3. Repeat While (BEG <= END) and (A[MID]? ITEM) 4. If (ITEM < A[MID]) Then 5. Set END = MID 1 6. Else 7. Set BEG = MID + 1 [End of If] 8. Set MID = (BEG + END) / 2 [End of While Loop] 9. If (A[MID] == ITEM) Then 10. Print: ITEM exists at location MID 11. Else 12. Print: ITEM doesn t exist [End of If] 13. Exit P a g e 14 Department of Computer Science & Engineering GEC

15 c).write C programs that use both recursive and non recursive functions to perform Fibonacci search for a Key value in a given list. ALGORITHM : Let F k represent the k-th Fibonacci number where F k+2 =F k+1 + F k for k>=0 and F 0 = 0, F 1 = 1. To test whether an item is in a list of n = F m ordered numbers, proceed as follows: 1. Set k = m. 2. If k = 0, finish - no match. 3. Test item against entry in position F k If match, finish. 5. If item is less than entry F k-1, discard entries from positions F k to n. Set k = k - 1 and go to If item is greater than entry F k-1, discard entries from positions 1 to F k-1. Renumber remaining entries from 1 to F k-2, set k = k - 2 and go to 2. If n is not a Fibonacci number, then let F m be the smallest such number >n, augment the original array with F m -n numbers larger than the sought item and apply the above algorithm for n'=f m. P a g e 15 Department of Computer Science & Engineering GEC

16 Exercise 4: a).write C programs that implement Bubble sort, to sort a given list of integers in ascending order ALGORITHM: step1: take first two elements of a list and compare them step2: if the first elements grater than second then interchange else keep the values as it step3: repeat the step 2 until last comparison takes place step4: reapeat step 1 to 3 until the list is sorted P a g e 16 Department of Computer Science & Engineering GEC

17 b).write C programs that implement Quick sort, to sort a given list of integers in ascending order ALGORITHM: step1: take first a list of unsorted values step2: take firstelement as 'pivot' step3: keep the firstelement as 'pivot' and correct its position in the list step4: divide the list into two based on first element step5: combine the list P a g e 17 Department of Computer Science & Engineering GEC

18 c).write C programs that implement Insertion sort, to sort a given list of integers in ascending order ALGORITHM: step1: take a list of values step2: compare the first two elements of a list if first element is greaterthan second interchange it else keep the list as it is. step3: now take three elements from the list and sort them as follows Step4::reapeat step 2 to 3 until the list is sorted. P a g e 18 Department of Computer Science & Engineering GEC

19 Exercise 5: a). Write C programs that implement Heap sort, to sort a given list of integers in ascending order Heap Sort Technique: Heap sort algorithm, as the name suggests, is based on the concept of heaps. It begins by constructing a special type of binary tree, called heap, out of the set of data which is to be sorted. Note: A Heap by definition is a special type of binary tree in which each node is greater than any of its descendants. It is a complete binary tree. A semi-heap is a binary tree in which all the nodes except the root possess the heap property. If N be the number of a node, then its left child is 2*N and the right child 2*N+1. The root node of a Heap, by definition, is the maximum of all the elements in the set of data, constituting the binary tree. Hence the sorting process basically consists of extracting the root node and reheaping the remaining set of elements to obtain the next largest element till there are no more elements left to heap. Elementary implementations usually employ two arrays, one for the heap and the other to store the sorted data. But it is possible to use the same array to heap the unordered list and compile the sorted list. This is usually done by swapping the root of the heap with the end of the array and then excluding that element from any subsequent reheaping. Significance of a semi-heap - A Semi-Heap as mentioned above is a Heap except that the root does not possess the property of a heap node. This type of a heap is significant in the discussion of Heap Sorting, since after each "Heaping" of the set of data, the root is extracted and replaced by an element from the list. This leaves us with a Semi-Heap. Reheaping a Semi-Heap is particularily easy since all other nodes have already been heaped and only the root node has to be shifted downwards to its right position. The following C function takes care of reheaping a set of data or a part of it. P a g e 19 Department of Computer Science & Engineering GEC

20 void downheap(int a[], int root, int bottom) { int maxchild, temp, child; while (root*2 < bottom) { child = root * 2 + 1; if (child == bottom) { maxchild = child; } else { if (a[child] > a[child + 1]) maxchild = child; else maxchild = child + 1; } if (a[root] < a[maxchild]) { temp = a[root]; a[root] = a[maxchild]; a[maxchild] = temp; } else return; } } root = maxchild; In the above function, both root and bottom are indices into the array. Note that, theoritically speaking, we generally express the indices of the nodes starting from 1 through size of the array. But in C, we know that array indexing begins at 0; and so the left child is child = root * /* so, for eg., if root = 0, child = 1 (not 0) */ In the function, what basically happens is that, starting from root each loop performs a check for the heap property of root and does whatever necessary to make it conform to it. If it does already conform to it, the loop breaks and the function returns to caller. Note that the function assumes that the tree constituted by the root and all its descendants is a Semi-Heap. Now that we have a downheaper, what we need is the actual sorting routine. void heapsort(int a[], int array_size) { int i; for (i = (array_size/2-1); i >= 0; --i) { downheap(a, i, array_size-1); P a g e 20 Department of Computer Science & Engineering GEC

21 } } for (i = array_size-1; i >= 0; --i) { int temp; temp = a[i]; a[i] = a[0]; a[0] = temp; downheap(a, 0, i-1); } Note that, before the actual sorting of data takes place, the list is heaped in the for loop starting from the mid element (which is the parent of the right most leaf of the tree) of the list. for (i = (array_size/2-1); i >= 0; --i) { downheap(a, i, array_size-1); } Following this is the loop which actually performs the extraction of the root and creating the sorted list. Notice the swapping of the ith element with the root followed by a reheaping of the list. for (i = array_size-1; i >= 0; --i) { int temp; temp = a[i]; a[i] = a[0]; a[0] = temp; downheap(a, 0, i-1); } The following are some snapshots of the array during the sorting process. The unodered list After the initial heaping done by the first for loop Second loop which extracts root and reheaps } pass } pass } pass } pass 4 P a g e 21 Department of Computer Science & Engineering GEC

22 b).write C programs that implement Radix sort, to sort a given list of integers in ascending order Radix Sorting : The bin sorting approach can be generalized in a technique that is known as radix sorting. An example Assume that we have n integers in the range (0,n 2 ) to be sorted. (For a bin sort, m = n 2, and we would have an O(n+m) = O(n 2 ) algorithm.) Sort them in two phases: 1. Using n bins, place a i into bin a i mod n, 2. Repeat the process using n bins, placing a i into bin floor(a i /n), being careful to append to the end of each bin. This results in a sorted list. As an example, consider the list of integers: n is 10 and the numbers all lie in (0,99). After the first phase, we will have: Bin Content Note that in this phase, we placed each item in a bin indexed by the least significant decimal digit. Repeating the process, will produce: Bin Content In this second phase, we used the leading decimal digit to allocate items to bins, being careful to add each item to the end of the bin. We can apply this process to numbers of any size expressed to any suitable base or radix. Generalized Radix Sorting: P a g e 22 Department of Computer Science & Engineering GEC

23 We can further observe that it's not necessary to use the same radix in each phase, suppose that the sorting key is a sequence of fields, each with bounded ranges, eg the key is a date using the structure: typedef struct t_date { int day; int month; int year; } date; If the ranges for day and month are limited in the obvious way, and the range for year is suitably constrained, eg 1900 < year <= 2000, then we can apply the same procedure except that we'll employ a different number of bins in each phase. In all cases, we'll sort first using the least significant "digit" (where "digit" here means a field with a limited range), then using the next significant "digit", placing each item after all the items already in the bin, and so on. Assume that the key of the item to be sorted has k fields, f i i=0..k-1, and that each f i has s i discrete values, then a generalised radix sort procedure can be written: radixsort( A, n ) { for(i=0;i<k;i++) { for(j=0;j<s i ;j++) bin[j] = EMPTY; } for(j=0;j<n;j++) { move A i to the end of bin[a i ->f i ] } for(j=0;j<s i ;j++) concatenate bin[j] onto the end of A; } O(s i ) O(n) O(s i ) Total P a g e 23 Department of Computer Science & Engineering GEC

24 Now if, for example, the keys are integers in (0,b k -1), for some constant k, then the keys can be viewed as k-digit base-b integers. Thus, s i = b for all i and the time complexity becomes O(n+kb) or O(n). This result depends on k being constant. If k is allowed to increase with n, then we have a different picture. For example, it takes log 2 n binary digits to represent an integer <n. If the key length were allowed to increase with n, so that k = logn, then we would have:. Another way of looking at this is to note that if the range of the key is restricted to (0,b k -1), then we will be able to use the radix sort approach effectively if we allow duplicate keys when n>b k. However, if we need to have unique keys, then k must increase to at least log b n. Thus, as n increases, we need to have logn phases, each taking O(n) time, and the radix sort is the same as quick sort! P a g e 24 Department of Computer Science & Engineering GEC

25 c).write C programs that implement Merge sort, to sort a given list of integers in ascending order Algorithm to Sort an Array using MERGE SORT Merge Sort ( A, BEG, END ): Description: Here A is an unsorted array. BEG is the lower bound and END is the upper bound. 1. If (BEG < END) Then 2. Set MID = (BEG + END) / 2 3. Call Merge Sort (A, BEG, MID) 4. Call Merge Sort (A, MID + 1, END) 5. Call Merge Array (A, BEG, MID, END) [End of If] 6. Exit Merge Array ( A, BEG, MID, END ) Description: Here A is an unsorted array. BEG is the lower bound, END is the upper bound and MID is the middle value of array. B is an empty array. 1. Repeat For I = BEG to END 2. Set B[I] = A[I] [Assign array A to B] [End of For Loop] 3. Set I = BEG, J = MID + 1, K = BEG 4. Repeat While (I <= MID) and (J <= END) 5. If (B[I] <= B[J]) Then [Assign smaller value to A] 6. Set A[K] = B[I] 7. Set I = I + 1 and K = K Else 9. Set A[K] = B[J] 10. Set J = J + 1 and K = K + 1 [End of If] [End of While Loop] P a g e 25 Department of Computer Science & Engineering GEC

26 11. If (I <= MID) Then [Check whether first half 12. Repeat While (I <= MID) has exhausted or not] 13. Set A[K] = B[I] 14. Set I = I + 1 and K = K + 1 [End of While Loop] 15. Else 16. Repeat While (J <= END) 17. Set A[K] = B[J] 18. Set J = J + 1 and K = K + 1 [End of While Loop] [End of If] 19. Exit P a g e 26 Department of Computer Science & Engineering GEC

27 Exercise 6: a) Write C programs that implement stack (its operations) using arrays Algorithm to Push Item into Stack Push ( ): Description: Here STACK is an array with MAX locations. TOP points to the top most element and ITEM is the value to be inserted. 1. If (TOP == MAX) Then [Check for overflow] 2. Print: Overflow 3. Else 4. Set TOP = TOP + 1 [Increment TOP by 1] 5. Set STACK[TOP] = ITEM [Assign ITEM to top of STACK] 6. Print: ITEM inserted [End of If] 7. Exit Algorithm to Pop Item from Stack Pop ( ): Description: Here STACK is an array with MAX locations. TOP points to the top most element. 1. If (TOP == 0) Then [Check for underflow] 2. Print: Underflow 3. Else 4. Set ITEM = STACK[TOP] [Assign top of STACK to ITEM] 5. Set TOP = TOP - 1 [Decrement TOP by 1] 6. Print: ITEM deleted [End of If] 7. Exit P a g e 27 Department of Computer Science & Engineering GEC

28 b) Write C programs that implement stack (its operations) using Linked list Algorithm: Algorithm to Push Item into Stack Push ( ): Description: Here STACK is an array with MAX locations. TOP points to the top most element and ITEM is the value to be inserted. 1. If (TOP == MAX) Then [Check for overflow] 2. Print: Overflow 3. Else 4. Set TOP = TOP + 1 [Increment TOP by 1] 5. Set STACK[TOP] = ITEM [Assign ITEM to top of STACK] 6. Print: ITEM inserted [End of If] 7. Exit Algorithm to Pop Item from Stack Pop ( ): Description: Here STACK is an array with MAX locations. TOP points to the top most element. 1. If (TOP == 0) Then [Check for underflow] 2. Print: Underflow 3. Else 4. Set ITEM = STACK[TOP] [Assign top of STACK to ITEM] 5. Set TOP = TOP - 1 [Decrement TOP by 1] 6. Print: ITEM deleted [End of If] 7. Exit P a g e 28 Department of Computer Science & Engineering GEC

29 Exercise 7: a) Write a C program that uses Stack operations to Convert infix expression into postfix expression Algorithm to Transform Infix Expression into Postfix Expression using Stack Transform ( ): Description: Here I is an arithmetic expression written in infix notation and P is the equivalent postfix expression generated by this algorithm. Algorithm. 1. Push ( left parenthesis onto stack. 2. Add ) right parenthesis to the end of expression I. 3. Scan I from left to right and repeat step 4 for each element of I a. until the stack becomes empty. 4. If the scanned element is: (i) an operand then add it to P. (ii) a left parenthesis then push it onto stack. (iii) an operator then: (iv) Pop from stack and add to P each operator (v) which has the same or higher precedence then (vi) the scanned operator. (vii) (ii) Add newly scanned operator to stack. (viii) a right parenthesis then: b. Pop from stack and add to P each operator (i) until a left parenthesis is encountered. c. Remove the left parenthesis. 5. Exit. (i) (ii) [End of Step 4 If] [End of step 3 For Loop] P a g e 29 Department of Computer Science & Engineering GEC

30 Algorithm to Evaluate Postfix Expression using Stack Evaluate ( ): Description: Here P is a postfix expression and this algorithm evaluates it. 1) Add a ) right parenthesis at the end of P. 2) Scan P from left to right and repeat steps 3 & 4 for each element i) of P until ) is encountered. 3) If an operand is encountered, push it onto stack. 4) If an operator? is encountered then: i) Pop the top two elements from stack, where A is the ii) top element and B is the next to top element. iii) Evaluate B? A. iv) Place the result of (b) back on stack. v) [End of Step 4 If] vi) [End of step 2 For Loop] 5) Set VALUE equal to the top element on the stack. 6) Exit. P a g e 30 Department of Computer Science & Engineering GEC

31 b). Write C programs that implement Queue (its operations) using arrays. Algorithm to Insert Item into Queue Insert ( ): Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE. ITEM is the value to be inserted. 1. If (REAR == N) Then [Check for overflow] 2. Print: Overflow 3. Else 4. If (FRONT and REAR == 0) Then [Check if QUEUE is empty] 5. Else (a) Set FRONT = 1 (b) Set REAR = 1 6. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If] 7. QUEUE[REAR] = ITEM 8. Print: ITEM inserted 9. Exit [End of Step 1 If] Algorithm to Delete Item from Queue Delete ( ): Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE. 1. If (FRONT == 0) Then [Check for underflow] 2. Print: Underflow 3. Else 4. ITEM = QUEUE[FRONT] 5. If (FRONT == REAR) Then [Check if only one element is left] (a) Set FRONT = 0 (b) Set REAR = 0 P a g e 31 Department of Computer Science & Engineering GEC

32 6. Else 7. Set FRONT = FRONT + 1 [Increment FRONT by 1] [End of Step 5 If] 8. Print: ITEM deleted [End of Step 1 If] 9. Exit P a g e 32 Department of Computer Science & Engineering GEC

33 c).write C programs that implement Queue (its operations) using linked lists /*Queue Using Linked List*/ ALGORITHM: Algorithm to Insert Item into Queue Insert ( ): Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE. ITEM is the value to be inserted. 1. If (REAR == N) Then [Check for overflow] 2. Print: Overflow 3. Else 4. If (FRONT and REAR == 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1 (b) Set REAR = 1 5. Else 6. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If] 7. QUEUE[REAR] = ITEM 8. Print: ITEM inserted [End of Step 1 If] 9. Exit Algorithm to Delete Item from Queue Delete ( ): Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE. 1. If (FRONT == 0) Then [Check for underflow] 2. Print: Underflow 3. Else 4. ITEM = QUEUE[FRONT] 5. If (FRONT == REAR) Then [Check if only one element is left] P a g e 33 Department of Computer Science & Engineering GEC

34 (a) Set FRONT = 0 (b) Set REAR = 0 6. Else 7. Set FRONT = FRONT + 1 [Increment FRONT by 1] [End of Step 5 If] 8. Print: ITEM deleted [End of Step 1 If] 9. Exit Algorithm to Insert Item into Circular Queue Insert Circular ( ): Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear elements of the QUEUE. ITEM is the value to be inserted. 1. If (FRONT == 1 and REAR == N) or (FRONT == REAR + 1) Then 2. Print: Overflow 3. Else 4. If (REAR == 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1 (b) Set REAR = 1 5. Else If (REAR == N) Then [If REAR reaches end if QUEUE] 6. Set REAR = 1 7. Else 8. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If] 9. Set QUEUE[REAR] = ITEM 10. Print: ITEM inserted [End of Step 1 If] 11. Exit P a g e 34 Department of Computer Science & Engineering GEC

35 Exercise 8: a) Write a C program that uses functions to create a Singly linked list ALGORITHM: Description: Here START is a pointer variable which contains the address of first node. PTR will point to the current node and PREV will point to the previous node. REV will maintain the reverse list. 1. Set PTR = START, PREV = NULL 2. Repeat While (PTR!= NULL) 3. REV = PREV 4. PREV = PTR 5. PTR = PTR->LINK 6. PREV->LINK = REV [End of While Loop] 7. START = PREV 8. Exit ALGORITHM TO INSERT ITEM AFTER A SPECIFIC NODE INSERT SPECIFIC ( ): Description: Here START is a pointer variable which contains the address of first node. NEW is a pointer variable which will contain address of new node. N is the value after which new node is to be inserted and ITEM is the value to be inserted. 1. If (START == NULL) Then 2. Print: Linked-List is empty. It must have at least one node 3. Else 4. Set PTR = START, NEW = START 5. Repeat While (PTR!= NULL) P a g e 35 Department of Computer Science & Engineering GEC

36 6. If (PTR->INFO == N) Then 7. NEW = New Node 8. NEW->INFO = ITEM 9. NEW->LINK = PTR->LINK 10. PTR->LINK = NEW 11. Print: ITEM inserted 12. ELSE 13. PTR = PTR->LINK P a g e 36 Department of Computer Science & Engineering GEC

37 b) Write a C program that uses functions to perform insertion operation on a Singly linked list ALGORITHM: INSERTED ( ): Description: Here START is a pointer variable which contains the address of first node. PREV is a pointer variable which contains address of previous node. ITEM is the value to be inserted. 1. If (START == NULL) Then [Check whether list is empty] 2. START = New Node [Create a new node] 3. START->INFO = ITEM [Assign ITEM to INFO field] 4. START->LINK = NULL [Assign NULL to LINK field] 5. Else 6. If (ITEM < START->INFO) Then [Check whether ITEM is less then value in first node] 7. PTR = START 8. START = New Node 9. START->INFO = ITEM 10. START->LINK = PTR 11. Else 12. Set PTR = START, PREV = START 13. Repeat While (PTR!= NULL) 14. If (ITEM < PTR->INFO) Then 15. PREV->LINK = New Node 16. PREV = PREV->LINK 17. PREV->INFO = ITEM 18. PREV->LINK = PTR 19. Return 20. Else If (PTR->LINK == NULL) Then [Check whether PTR reaches last node] 21. PTR->LINK = New Node P a g e 37 Department of Computer Science & Engineering GEC

38 22. PTR = PTR->LINK 23. PTR->INFO = ITEM 24. PTR->LINK = NULL 25. Return 26. Else 27. PREV = PTR 28. PTR = PTR->LINK [End of Step 14 If] [End of While Loop] [End of Step 6 If] [End of Step 1 If] 29. Exit P a g e 38 Department of Computer Science & Engineering GEC

39 c) Write a C program that uses functions to perform deletion operation on a Singly linked list ALGORITHM: DELETE LAST ( ): Description: Here START is a pointer variable which contains the address of first node. PTR is a pointer variable which contains address of node to be deleted. PREV is a pointer variable which points to previous node. ITEM is the value to be deleted. 1. If (START == NULL) Then [Check whether list is empty] 2. Print: Linked-List is empty. 3. Else 4. PTR = START, PREV = START 5. Repeat While (PTR->LINK!= NULL) 6. PREV = PTR [Assign PTR to PREV] 7. PTR = PTR->LINK [Move PTR to next node] [End of While Loop] 8. ITEM = PTR->INFO [Assign INFO of last node to ITEM] 9. If (START->LINK == NULL) Then [If only one node is left] 10. START = NULL [Assign NULL to START] 11. Else 9. PREV->LINK = NULL [Assign NULL to link field of second last node] [End of Step 9 If] 10. Delete PTR 11. Print: ITEM deleted [End of Step 1 If] 12. Exit P a g e 39 Department of Computer Science & Engineering GEC

40 Exercise 9: d) Adding two large integers which are represented in linked list fashion. ALGORITHM: ADD ( ): Description: Here A is a two dimensional array with M rows and N columns and B is a two dimensional array with X rows and Y columns. This algorithm adds these two arrays. 1. If (M? X) or (N? Y) Then 2. Print: Addition is not possible. 3. Exit [End of If] 4. Repeat For I = 1 to M 5. Repeat For J = 1 to N 6. Set C[I][J] = A[I][J] + B[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop] 7. Exit Explanation: First, we have to check whether the rows of array A are equal to the rows of array B or the columns of array A are equal to the columns of array B. if they are not equal, then addition is not possible and the algorithm exits. But if they are equal, then first for loop iterates to the total number of rows i.e. M and the second for loop iterates to the total number of columns i.e. N. In step 6, the element A[I][J] is added to the element B[I][J] and is stored in C[I][J] by the statement: C[I][J] = A[I][J] + B[I][J P a g e 40 Department of Computer Science & Engineering GEC

41 e) Write a C program to reverse elements of a Single linked list. ALGORITHM: Algorithm to Reverse a Linked List Reverse ( ): Description: Here START is a pointer variable which contains the address of first node. PTR will point to the current node and PREV will point to the previous node. REV will maintain the reverse list. 1. Set PTR = START, PREV = NULL 2. Repeat While (PTR!= NULL) 3. REV = PREV 4. PREV = PTR 5. PTR = PTR->LINK 6. PREV->LINK = REV [End of While Loop] 7. START = PREV 8. Exit P a g e 41 Department of Computer Science & Engineering GEC

42 f) Write a C program to representation the given Sparse matrix using arrays. ALGORITHM: Description: Here A is a two dimensional array with M rows and N columns and B is a two dimensional array with X rows and Y columns. This algorithm adds these two arrays. 1. If (M? X) or (N? Y) Then 2. Print: Addition is not possible. 3. Exit [End of If] 4. Repeat For I = 1 to M 5. Repeat For J = 1 to N 6. Set C[I][J] = A[I][J] + B[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop] 7. Exit Explanation: First, we have to check whether the rows of array A are equal to the rows of array B or the columns of array A are equal to the columns of array B. if they are not equal, then addition is not possible and the algorithm exits. But if they are equal, then first for loop iterates to the total number of rows i.e. M and the second for loop iterates to the total number of columns i.e. N. In step 6, the element A[I][J] is added to the element B[I][J] and is stored in C[I][J] by the statement: C[I][J] = A[I][J] + B[I][J P a g e 42 Department of Computer Science & Engineering GEC

43 g) Write a C program to representation the given Sparse matrix using linked list ALGORITHM: Description: Here A is a two dimensional array with M rows and N columns and B is a two dimensional array with X rows and Y columns. This algorithm multiplies these two arrays. 1. If (M? Y) or (N? X) Then 2. Print: Multiplication is not possible. 3. Else 4. Repeat For I = 1 to N 5. Repeat For J = 1 to X 6. Set C[I][J] = 0 7. Repeat For K = 1 to Y 8. Set C[I][J] = C[I][J] + A[I][K] * B[K][J] [End of Step 7 For Loop] [End of Step 5 For Loop] [End of Step 4 For Loop] [End of If] 9. Exit Explanation: First we check whether the rows of A are equal to columns of B or the columns of A are equal to rows of B. If they are not equal, then multiplication is not possible. But, if they are equal, the first for loop iterates to total number of columns of A i.e. N and the second for loop iterates to the total number of rows of B i.e. X. In step 6, all the elements of C are set to zero. Then the third for loop iterates to total number of columns of B i.e. Y. In step 8, the element A[I][K] is multiplied with B[K][J] and added to C[I][J] and the result is assigned to C[I][J] by the statement: C[I][J] = C[I][J] + A[I][K] * B[K][J P a g e 43 Department of Computer Science & Engineering GEC

44 Exercise10: a) Write a C program to Create a Binary Tree of integers ALGORITHM: Binary tree is an important type of structure which occurs very often. It is characterized by the fact that any node can have at most two branches, i.e.,there is no node with degree greater than two. For binary trees we distinguish between the subtree on the left and on the right, whereas for trees the order of the subtree was irrelevant. Also a binary tree may have zero nodes. Thus a binary tree is really a different object than a tree. Definition: A binary tree is a finite set of nodes which is either empty or consists of a root and two disjoint binary trees called the left subtree and the right subtree. We can define the data structure binary tree as follows: structure BTREE declare CREATE( ) --> btree ISMTBT(btree,item,btree) --> boolean MAKEBT(btree,item,btree) --> btree LCHILD(btree) --> btree DATA(btree) --> item RCHILD(btree) --> btree for all p,r in btree, d in item let ISMTBT(CREATE)::=true ISMTBT(MAKEBT(p,d,r))::=false LCHILD(MAKEBT(p,d,r))::=p; LCHILD(CREATE)::=error DATA(MAKEBT(p,d,r))::d; DATA(CREATE)::=error RCHILD(MAKEBT(p,d,r))::=r; RCHILD(CREATE)::=error end end BTREE P a g e 44 Department of Computer Science & Engineering GEC

45 b) Write a recursive C program, for Traversing a binary tree in preorder, inorder and postorder. ALGORITHM: PREORDER The first type of traversal is pre-order whose code looks like the following: sub P(TreeNode) Output(TreeNode.value) If LeftPointer(TreeNode)!= NULL Then P(TreeNode.LeftNode) If RightPointer(TreeNode)!= NULL Then P(TreeNode.RightNode) end sub This can be summed up as Visit the root node (generally output this) Traverse to left subtree Traverse to right subtree And outputs the following: F, B, A, D, C, E, G, I, H IN-ORDER The second(middle) type of traversal is in-order whose code looks like the following: sub P(TreeNode) If LeftPointer(TreeNode)!= NULL Then P(TreeNode.LeftNode) Output(TreeNode.value) If RightPointer(TreeNode)!= NULL Then P(TreeNode.RightNode) end sub P a g e 45 Department of Computer Science & Engineering GEC

46 This can be summed up as Traverse to left subtree Visit root node (generally output this) Traverse to right subtree And outputs the following: A, B, C, D, E, F, G, H, I POST-ORDER The last type of traversal is post-order whose code looks like the following: sub P(TreeNode) If LeftPointer(TreeNode)!= NULL Then P(TreeNode.LeftNode) If RightPointer(TreeNode)!= NULL Then P(TreeNode.RightNode) Output(TreeNode.value) end sub This can be summed up as Traverse to left subtree Traverse to right subtree Visit root node (generally output this) And outputs the following: A, C, E, D, B, H, I, G, F P a g e 46 Department of Computer Science & Engineering GEC

47 Exercise 11: a) Write a C program to Create a BST Algorithm CreateBST (A) Create a binary search tree (BST) from an array A with N elements. root the root of a new binary search tree named T; index 1; while index N do InsertBST (A[index ], root); index index + 1; end while return T Algorithm InOrder (root) Perform an inorder (second-visit) traversal of the BST with root named root. if root is empty then return else InOrder (left child of root); output the value in root; InOrder (right child of root); end if Algorithm TreeSort (A) Sort the elements in array A using a binary search tree (BST). CreateBST (A); {Creates a new BST T containing the elements of A} InOrder (root of T); {Sorts the elements in T using an inorder traversal} b) Write a C program to insert a note into a BST. Binary Search Tree Algorithms Algorithm Insert BST (v, root) Iteratively insert a value v into a binary search tree (BST) with root named root. P a g e 47 Department of Computer Science & Engineering GEC

48 if root is empty then root v; else node root; loop {an infinite loop; we will explicitly exit the loop after v is inserted} if v value stored in node then if the left child of node exists then node left child of node; else insert v as the left child of node; exit the loop; end if else if the right child of node exists then node right child of node; else insert v as the right child of node; exit the loop; end if end if end loop end if Algorithm InsertBST (v, root) Recursively insert a value v into a binary search tree (BST) with root named root. if root is empty then root v; else if v value stored in root then if the left child of root exists then InsertBST (v, left child of root); else insert v as the left child of root; P a g e 48 Department of Computer Science & Engineering GEC

49 end if else if the right child of root exists then InsertBST (v, right child of root); else insert v as the right child of root; end if end if end if c) Write a C program to delete a note from a BST. DELETION ALGORITHM 1) Check for the cases that the delete operation fails: a. IF <root> == NULL (tree is empty) b. Search the BST for the element to be deleted; IF <element> is not found (there is no such element in the tree). // In both cases a&b the delete operation fails. 2) IF <element> is found, then the delete operation has four cases: case 1: The <node> to be deleted has no <left> and <right> subtrees; that is, the <node> to be deleted is a leaf. // the easiest case case 2: The <node> to be deleted has no <left> subtree; that is, the <left> subtree is empty. but it has nonempty <right> subtree. case 3: The <node> to be deleted has no <right> subtree; that is, the <right> subtree is empty. but it has nonempty <left> subtree. case 4: The <node> to be deleted has nonempty <left> and <right> subtrees; that is, the <node> to be deleted has <left> and <right> subtrees. // the hardest case P a g e 49 Department of Computer Science & Engineering GEC

50 Exercise 12: a) Write a C program to compute the shortest path of a graph using Dijkstra s algorithm To implement Dijkstra s Algorithm DESCRIPTION: Shortest path from a specified vertex S to another specified vertex T can be stated as follows: A simple weighted Graph G of n vertices is described by a n*n matrix D = [d ij ] Where d ij =length (or distance or weight) of the directed edge from vertex i to vertex j, d ij >=0 D ij =0 D ij=, if there is no edge from I to j (In the problem is replaced with some large number 99999) The distance of a directed path p is defined to be the S denotes the Starting vertex T denotes the Terminal vertex Disjkstra s Alogrithm is the most efficient shortest path Alogrithm P a g e 50 Department of Computer Science & Engineering GEC

51 EXAMPLE: Finding the shortest path from vertex B to G: Starting vertex B is labeled 0. All successor of B get labeled. Smallest label become permanent Successor of C gets labeled. A B C D E F G Destination vertex gets permanently labeled. P a g e 51 Department of Computer Science & Engineering GEC

52 b) Write a C program to find the minimum spanning tree using Warshall s Algorithm ALGORITHM: Warshall algorithm is a dynamic programming formulation, to solve the all-pairs shortest path problem on directed graphs. It finds shortest path between all nodes in a graph. If finds only the lengths not the path. The algorithm considers the intermediate vertices of a simple path are any vertex present in that path other than the first and last vertex of that path. Algorithm: Input Format: Graph is directed and weighted. First two integers must be number of vertices and edges which must be followed by pairs of vertices which has an edge between them. maxvertices represents maximum number of vertices that can be present in the graph. vertices represent number of vertices and edges represent number of edges in thegraph. graph[i][j] represent the weight of edge joining i and j. size[maxvertices] is initialed to{0}, represents the size of every vertex i.e. the number of edges corresponding to the vertex. visited[maxvertices]={0} represents the vertex that have been visited. distance[maxvertices][maxvertices] represents the weight of the edge between the two vertices or distance between two vertices. Initialize the distance between two vertices using init() function. init() function- It takes the distance matrix as an argument. For iter=0 to maxvertices 1 For jter=0 to maxvertices 1 if(iter == jter) distance[iter][jter] = 0 //Distance between two same vertices is 0 else distance[iter][jter] = INF//Distance between different vertices is INF jter + 1 P a g e 52 Department of Computer Science & Engineering GEC

53 iter + 1 Where, INF is a very large integer value. Initialize and input the graph. Call Floyd Warshall function. It takes the distance matrix (distance[maxvertices][maxvertices]) and number of vertices as argument (vertices). Initialize integer type from, to, via For from=0 to vertices-1 For to=0 to vertices-1 For via=0 to vertices-1 distance[from][to] = min(distance[from][to],distance[from] [via]+distance[via][to]) via + 1 to + 1 from + 1 This finds the minimum distance from from vertex to to vertex using the min function. It checks it there are intermediate vertices between the from and to vertex that form the shortest path between them min function returns the minimum of the two integers it takes as argument. Output the distance between every two vertices. P a g e 53 Department of Computer Science & Engineering GEC

54 ADD ON PROGRAMS : 1. Write a C program on Circular Queue operations Circular Queue A circular queue is a Queue but a particular implementation of a queue. It is very efficient. It is also quite useful in low level code, because insertion and deletion are totally independant, which means that you don't have to worry about an interrupt handler trying to do an insertion at the same time as your main code is doing a deletion. Algorithm for Insertion:- Step-1: If "rear" of the queue is pointing to the last position then go to step-2 or else step-3 Step-2: make the "rear" value as 0 Step-3: increment the "rear" value by one Step-4: 1. if the "front" points where "rear" is pointing and the queue holds a not NULL value for it, then its a "queue overflow" state, so quit; else go to step insert the new value for the queue position pointed by the "rear" Algorithm for deletion:- Step-1: If the queue is empty then say "empty queue" and quit; else continue Step-2: Delete the "front" element Step-3: If the "front" is pointing to the last position of the queue then step-4 else step-5 Step-4: Make the "front" point to the first position in the queue and quit Step-5: Increment the "front" position by one P a g e 54 Department of Computer Science & Engineering GEC

55 2. Write a C program on Evaluation on Postfix Expression Postfix Evaluation Infix Expression : Any expression in the standard form like "2*3-4/5" is an Infix(Inorder) expression. Postfix Expression : The Postfix(Postorder) form of the above expression is "23*45/-". Postfix Evaluation : In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+. The algorithm for the conversion is as follows : Scan the Postfix string from left to right. Initialise an empty stack. If the scannned character is an operand, add it to the stack. If the scanned character is an operator, there will be atleast two operands in the stack. If the scanned character is an Operator, then we store the top most element of the stack(topstack) in a variable temp. Pop the stack. Now evaluate topstack(operator)temp. Let the result of this operation be retval. Pop the stack and Push retval into the stack. Repeat this step till all the characters are scanned. After all characters are scanned, we will have only one element in the stack. Return topstack. Example : Let us see how the above algorithm will be imlemented using an example. Postfix String : 123*+4- Initially the Stack is empty. Now, the first three characters scanned are 1,2 and 3, which are operands. Thus they will be pushed into the stack in that order. Expression Stack Next character scanned is "*", which is an operator. Thus, we pop the top two elements from the stack and perform the "*" operation with the two operands. The second operand will be the first element that is popped. P a g e 55 Department of Computer Science & Engineering GEC

56 Expression Stack The value of the expression(2*3) that has been evaluated(6) is pushed into the stack. Expression Stack Next character scanned is "+", which is an operator. Thus, we pop the top two elements from the stack and perform the "+" operation with the two operands. The second operand will be the first element that is popped. Expression Stack The value of the expression(1+6) that has been evaluated(7) is pushed into the stack. Expression Stack Next character scanned is "4", which is added to the stack. Expression Stack Next character scanned is "-", which is an operator. Thus, we pop the top two elements from the stack and perform the "-" operation with the two operands. The second operand will be the first element that is popped. P a g e 56 Department of Computer Science & Engineering GEC

57 Expression Stack The value of the expression(7-4) that has been evaluated(3) is pushed into the stack. Expression Stack Now, since all the characters are scanned, the remaining element in the stack (there will be only one element in the stack) will be returned. End result : Postfix String : 123*+4- Result : 3 P a g e 57 Department of Computer Science & Engineering GEC

58 3. Write a C program search the elements using Breadth First Search Algorithm & Depth First Search Algorithm DESCRIPTION: 1. A graph can be thought of a collection of vertices (V) and edges (E), so we write, G = (V, E) 2. Graphs can be directed, or undirected, weighted or unweighted. 3. A directed graph, or digraph, is a graph where the edge set is an ordered pair. That is, edge 1 being connected to edge 2 does not imply that edge 2 is connected to edge 1. (i.e. it has direction trees are special kinds of directed graphs). 4. An undirected graph is a graph where the edge set in an unordered pair. That is, edge 1 being connected to edge 2 does imply that edge 2 is connected to edge A weighted graph is graph which has a value associated with each edge. This can be a distance, or cost, or some other numeric value associated with the edge. ALGORITHM FOR DEPTH FIRST SEARCH AND TRAVERSAL: A depth first search of a graph differs from a breadth first search in that the exploration of a vertex v is suspended as soon as a new vertex is reached. At this time of exploration of the new vertex u begins. When this new vertex has been explored, the exploration of v continues. The search terminates when all reached vertices have been fully explored. The search process is best described recursively in the following algorithm. Algorithm DFS(v) // Given an undirected(directed) graph G=(V,E) with n vertices and an //array visited [] initially set to zero, this algorithm visits all vertices reachable //from v. G and visited[] are global. { visited[v]:=1; for each vertex w adjacent from v do { if (visited[w]=0) then DFS(w); } P a g e 58 Department of Computer Science & Engineering GEC

59 DESCRIPTION: 1. A graph can be thought of a collection of vertices (V) and edges (E), so we write, G = (V, E) 2. Graphs can be directed, or undirected, weighted or unweighted. 3. A directed graph, or digraph, is a graph where the edge set is an ordered pair. That is, edge 1 being connected to edge 2 does not imply that edge 2 is connected to edge 1. (i.e. it has direction trees are special kinds of directed graphs). 4. An undirected graph is a graph where the edge set in an unordered pair. That is, edge 1 being connected to edge 2 does imply that edge 2 is connected to edge A weighted graph is graph which has a value associated with each edge. This can be a distance, or cost, or some other numeric value associated with the edge. ALGORITHM FOR BREADTH FIRST SEARCH AND TRAVERSAL: In Breadth first search we start at vertex v and mark it as having been reached (visited) the vertex v is at this time said to be unexplored. A vertex is said to have been explored by an algorithm when the algorithm has visited all vertices adjacent from it. All unvisited vertices adjacent from v are visited next. These are new unexplored vertices. Vertex v has now been explored. The newly visited vertices have not been explored and or put on to the end of a list of unexplored list of vertices. The first vertex on this list is the next to be explored. Exploration continues until no unexplored vertex is left. The list of unexplored vertices operates as a queue and can be represented using any of the standard queue representations. Algorithm BFS(v) //A breadth first search of G is carried out beginning at vertex v. For //any node I, visited[i=1 if I has already been visited. The graph G //and array visited are global; visited[] is initialized to zero. { u:=v; //q is a queue of unexplored vertices visited[v]:=1; repeat { for all vertices w adjacent from u do P a g e 59 Department of Computer Science & Engineering GEC

60 { if (visited[w]=0) then { add w to q; //w is unexplored visited[w]:=1; } } if q is empty then return; //no unexplored vertex delete u from q; //get first unexplored vertex }until(false); } Algorithm BFT(G, n) //Breadth first traversal of G { for I:=1 to n do //mark all vertices unvisited visited[i]:=0; for I:=1 to n do if (visited[i]=0) then BFS(i); } P a g e 60 Department of Computer Science & Engineering GEC

61 4. Write a C program to perform various operations i.e., insertions and deletions on AVL trees AVL Trees: Also called as: Height Balanced Binary Search Trees. Search, Insertion, and Deletion can be implemented in worst case O (log n) time. Definition: An AVL tree is a binary search tree in which 1. The heights of the right subtree and left subtree of the root differ by at most 1 2. The left subtree and the right subtree are themselves AVL trees 3. A node is said to be left-high right-high equal if the left subtree has greater height if the right subtree has greater height if the heights of the LST and RST are the same / - Examples: Several examples of AVL trees are shown in Figure1. P a g e 61 Department of Computer Science & Engineering GEC

62 Figure 2: An AVL tree with height h Maximum Height of an AVL Tree: What is the maximum height of an AVL tree having exactly n nodes? To answer this question, we will pose the following question: What is the minimum number of nodes (sparsest possible AVL tree) an AVL tree of height h can have? Let F h be an AVL tree of height h, having the minimum number of nodes. F h can be visualized as in Figure 2. Let F l and F r be AVL trees which are the left subtree and right subtree, respectively, of F h. Then F l or F r must have height h-2. Suppose F l has height h-1 so that F r has height h-2. Note that F r has to be an AVL tree having the minimum number of nodes among all AVL trees with height of h-1. Similarly, F r will have the minimum number of nodes among all AVL trees of height h--2. Thus we have F h = F h F h Where F r denotes the number of nodes in F r. Such trees are called Fibonacci trees. See Figure 3. P a g e 62 Department of Computer Science & Engineering GEC

63 Figure 3: Fibonacci trees Note that F 0 = 1 and F 1 = 2. Adding 1 to both sides, we get F h + 1 = ( F h ) + ( F h ) Thus the numbers F h + 1 are Fibonacci numbers. Using the approximate formula for Fibonacci numbers, we get F h + 1 h 1.44log F n The sparsest possible AVL tree with n nodes has height h 1.44log n The worst case height of an AVL tree with n nodes is 1.44log n Algorithm for Insertions and Deletions into an AVL Trees: While inserting a new node or deleting an existing node, the resulting tree may violate the (stringent) AVL property. To reinstate the AVL property, we use rotations. See Figure 4. P a g e 63 Department of Computer Science & Engineering GEC

64 Figure 4: Rotations in a binary search tree Rotation in a BST: Left rotation and right rotation can be realized by a three-way rotation of pointers. Left Rotation: Temp = p right ; p right = temp left ; temp left = p ; p = temp ; Left rotation and right rotation preserve BST property Inorder ordering of keys Problem Scenarios in AVL Tree Insertions left sub tree of node has degree higher by >= 2 left child of node is left high (A) left child or node is right high (B) right sub tree has degree higher by >= 2 right child of node is left high (C) right child or node is right high (D) The AVL tree property may be violated at any node, not necessarily the root. Fixing the AVL property involves doing a series of single or double rotations. Double rotation involves a left rotation followed or preceded by a right rotation. In an AVL tree of height h, no more than [h/2] rotations are required to fix the AVL property. P a g e 64 Department of Computer Science & Engineering GEC

65 Insertion: Problem Scenario 1: (Scenario D) Scenario A is symmetrical to the above. See Figure 5. Figure 5: Insertion in AVL trees: Scenario D P a g e 65 Department of Computer Science & Engineering GEC

66 Insertion: Problem Scenario 2: (Scenario C) Scenario B is symmetrical to this. See Figure 6. Figure 6: Insertion in AVL trees: Scenario C P a g e 66 Department of Computer Science & Engineering GEC

67 Deletion: Problem Scenario 1: Depending on the original height of T 2, the height of the tree will be either unchanged (height of T 2 = h) or gets reduced (if height of T 2 = h - 1). See Figure 7. Figure 7: Deletion in AVL trees: Scenario 1 There is a scenario symmetric to this. P a g e 67 Department of Computer Science & Engineering GEC

68 Deletion: Problem Scenario 2: See Figure 8. As usual, there is a symmetric scenario. Figure 8: Deletion in AVL trees: Scenario 2 P a g e 68 Department of Computer Science & Engineering GEC

PES Institute of Technology-BSC QUESTION BANK

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

More information

10CS35: Data Structures Using C

10CS35: Data Structures Using C CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling a

More information

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

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

More information

DATA STRUCTURES USING C

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

More information

Module 2 Stacks and Queues: Abstract Data Types

Module 2 Stacks and Queues: Abstract Data Types Module 2 Stacks and Queues: Abstract Data Types A stack is one of the most important and useful non-primitive linear data structure in computer science. It is an ordered collection of items into which

More information

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

More information

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.

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

More information

Data Structure [Question Bank]

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:

More information

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

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

More information

Atmiya Infotech Pvt. Ltd. Data Structure. By Ajay Raiyani. Yogidham, Kalawad Road, Rajkot. Ph : 572365, 576681 1

Atmiya Infotech Pvt. Ltd. Data Structure. By Ajay Raiyani. Yogidham, Kalawad Road, Rajkot. Ph : 572365, 576681 1 Data Structure By Ajay Raiyani Yogidham, Kalawad Road, Rajkot. Ph : 572365, 576681 1 Linked List 4 Singly Linked List...4 Doubly Linked List...7 Explain Doubly Linked list: -...7 Circular Singly Linked

More information

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. 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

More information

Data Structure with C

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

More information

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.

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

More information

Converting a Number from Decimal to Binary

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

More information

Sample Questions Csci 1112 A. Bellaachia

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

More information

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

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

More information

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit Data Structures Page 1 of 24 A.1. Arrays (Vectors) n-element vector start address + ielementsize 0 +1 +2 +3 +4... +n-1 start address continuous memory block static, if size is known at compile time dynamic,

More information

Algorithms and Data Structures

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

More information

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. 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

More information

Exam study sheet for CS2711. List of topics

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

More information

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT. Course Curriculum. DATA STRUCTURES (Code: 3330704)

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT. Course Curriculum. DATA STRUCTURES (Code: 3330704) GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT Course Curriculum DATA STRUCTURES (Code: 3330704) Diploma Programme in which this course is offered Semester in which offered Computer Engineering,

More information

Data Structures UNIT III. Model Question Answer

Data Structures UNIT III. Model Question Answer Data Structures UNIT III Model Question Answer Q.1. Define Stack? What are the different primitive operations on Stack? Ans: Stack: A stack is a linear structure in which items may be added or removed

More information

Unit 1. 5. Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

Unit 1. 5. Write iterative and recursive C functions to find the greatest common divisor of two integers. [6] Unit 1 1. Write the following statements in C : [4] Print the address of a float variable P. Declare and initialize an array to four characters a,b,c,d. 2. Declare a pointer to a function f which accepts

More information

TREE BASIC TERMINOLOGIES

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

More information

Ordered Lists and Binary Trees

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:

More information

Data Structures Fibonacci Heaps, Amortized Analysis

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:

More information

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Why? A central concept in Computer Science. Algorithms are ubiquitous. Analysis of Algorithms: A Brief Introduction Why? A central concept in Computer Science. Algorithms are ubiquitous. Using the Internet (sending email, transferring files, use of search engines, online

More information

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. 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

More information

Analysis of a Search Algorithm

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,

More information

Data Structures and Algorithms

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

More information

Binary Search Trees CMPSC 122

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

More information

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push) -----------------------------------------

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

More information

2) Write in detail the issues in the design of code generator.

2) Write in detail the issues in the design of code generator. COMPUTER SCIENCE AND ENGINEERING VI SEM CSE Principles of Compiler Design Unit-IV Question and answers UNIT IV CODE GENERATION 9 Issues in the design of code generator The target machine Runtime Storage

More information

Binary Trees and Huffman Encoding Binary Search Trees

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

More information

Pseudo code Tutorial and Exercises Teacher s Version

Pseudo code Tutorial and Exercises Teacher s Version Pseudo code Tutorial and Exercises Teacher s Version Pseudo-code is an informal way to express the design of a computer program or an algorithm in 1.45. The aim is to get the idea quickly and also easy

More information

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structures Using C++ 2E. Chapter 5 Linked Lists Data Structures Using C++ 2E Chapter 5 Linked Lists Doubly Linked Lists Traversed in either direction Typical operations Initialize the list Destroy the list Determine if list empty Search list for a given

More information

Binary Heap Algorithms

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

More information

Any two nodes which are connected by an edge in a graph are called adjacent node.

Any two nodes which are connected by an edge in a graph are called adjacent node. . iscuss following. Graph graph G consist of a non empty set V called the set of nodes (points, vertices) of the graph, a set which is the set of edges and a mapping from the set of edges to a set of pairs

More information

Common Data Structures

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

More information

International Journal of Software and Web Sciences (IJSWS) www.iasir.net

International Journal of Software and Web Sciences (IJSWS) www.iasir.net International Association of Scientific Innovation and Research (IASIR) (An Association Unifying the Sciences, Engineering, and Applied Research) ISSN (Print): 2279-0063 ISSN (Online): 2279-0071 International

More information

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, 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

More information

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. 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:

More information

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

From Last Time: Remove (Delete) Operation

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

More information

Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

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:

More information

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

More information

Lecture 3: Finding integer solutions to systems of linear equations

Lecture 3: Finding integer solutions to systems of linear equations Lecture 3: Finding integer solutions to systems of linear equations Algorithmic Number Theory (Fall 2014) Rutgers University Swastik Kopparty Scribe: Abhishek Bhrushundi 1 Overview The goal of this lecture

More information

Algorithms. Margaret M. Fleck. 18 October 2010

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

More information

EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE)

EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE) EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE) UNIT I LINEAR STRUCTURES Abstract Data Types (ADT) List ADT array-based implementation linked list implementation cursor-based linked lists

More information

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:

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)

More information

IE 680 Special Topics in Production Systems: Networks, Routing and Logistics*

IE 680 Special Topics in Production Systems: Networks, Routing and Logistics* IE 680 Special Topics in Production Systems: Networks, Routing and Logistics* Rakesh Nagi Department of Industrial Engineering University at Buffalo (SUNY) *Lecture notes from Network Flows by Ahuja, Magnanti

More information

root node level: internal node edge leaf node CS@VT Data Structures & Algorithms 2000-2009 McQuain

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

More information

Heaps & Priority Queues in the C++ STL 2-3 Trees

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

More information

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)! The Tower of Hanoi Recursion Solution recursion recursion recursion Recursive Thinking: ignore everything but the bottom disk. 1 2 Recursive Function Time Complexity Hanoi (n, src, dest, temp): If (n >

More information

Symbol Tables. Introduction

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

More information

Data Structures and Data Manipulation

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

More information

Data Structures and Algorithms Written Examination

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

More information

Binary Search Trees (BST)

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

More information

2. (a) Explain the strassen s matrix multiplication. (b) Write deletion algorithm, of Binary search tree. [8+8]

2. (a) Explain the strassen s matrix multiplication. (b) Write deletion algorithm, of Binary search tree. [8+8] Code No: R05220502 Set No. 1 1. (a) Describe the performance analysis in detail. (b) Show that f 1 (n)+f 2 (n) = 0(max(g 1 (n), g 2 (n)) where f 1 (n) = 0(g 1 (n)) and f 2 (n) = 0(g 2 (n)). [8+8] 2. (a)

More information

Network (Tree) Topology Inference Based on Prüfer Sequence

Network (Tree) Topology Inference Based on Prüfer Sequence Network (Tree) Topology Inference Based on Prüfer Sequence C. Vanniarajan and Kamala Krithivasan Department of Computer Science and Engineering Indian Institute of Technology Madras Chennai 600036 [email protected],

More information

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

More information

Approximation Algorithms

Approximation Algorithms Approximation Algorithms or: How I Learned to Stop Worrying and Deal with NP-Completeness Ong Jit Sheng, Jonathan (A0073924B) March, 2012 Overview Key Results (I) General techniques: Greedy algorithms

More information

7.1 Our Current Model

7.1 Our Current Model Chapter 7 The Stack In this chapter we examine what is arguably the most important abstract data type in computer science, the stack. We will see that the stack ADT and its implementation are very simple.

More information

Stack & Queue. Darshan Institute of Engineering & Technology. Explain Array in detail. Row major matrix No of Columns = m = u2 b2 + 1

Stack & Queue. Darshan Institute of Engineering & Technology. Explain Array in detail. Row major matrix No of Columns = m = u2 b2 + 1 Stack & Queue Explain Array in detail One Dimensional Array Simplest data structure that makes use of computed address to locate its elements is the onedimensional array or vector; number of memory locations

More information

ALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite

ALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite ALGEBRA Pupils should be taught to: Generate and describe sequences As outcomes, Year 7 pupils should, for example: Use, read and write, spelling correctly: sequence, term, nth term, consecutive, rule,

More information

a 11 x 1 + a 12 x 2 + + a 1n x n = b 1 a 21 x 1 + a 22 x 2 + + a 2n x n = b 2.

a 11 x 1 + a 12 x 2 + + a 1n x n = b 1 a 21 x 1 + a 22 x 2 + + a 2n x n = b 2. Chapter 1 LINEAR EQUATIONS 1.1 Introduction to linear equations A linear equation in n unknowns x 1, x,, x n is an equation of the form a 1 x 1 + a x + + a n x n = b, where a 1, a,..., a n, b are given

More information

Section IV.1: Recursive Algorithms and Recursion Trees

Section IV.1: Recursive Algorithms and Recursion Trees Section IV.1: Recursive Algorithms and Recursion Trees Definition IV.1.1: A recursive algorithm is an algorithm that solves a problem by (1) reducing it to an instance of the same problem with smaller

More information

Data Structures. Level 6 C30151. www.fetac.ie. Module Descriptor

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,

More information

Introduction to Data Structures

Introduction to Data Structures Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate

More information

CS711008Z Algorithm Design and Analysis

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

More information

Continued Fractions and the Euclidean Algorithm

Continued Fractions and the Euclidean Algorithm Continued Fractions and the Euclidean Algorithm Lecture notes prepared for MATH 326, Spring 997 Department of Mathematics and Statistics University at Albany William F Hammond Table of Contents Introduction

More information

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

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

More information

6. Standard Algorithms

6. Standard Algorithms 6. Standard Algorithms The algorithms we will examine perform Searching and Sorting. 6.1 Searching Algorithms Two algorithms will be studied. These are: 6.1.1. inear Search The inear Search The Binary

More information

Analysis of Binary Search algorithm and Selection Sort algorithm

Analysis of Binary Search algorithm and Selection Sort algorithm Analysis of Binary Search algorithm and Selection Sort algorithm In this section we shall take up two representative problems in computer science, work out the algorithms based on the best strategy to

More information

Parallelization: Binary Tree Traversal

Parallelization: Binary Tree Traversal By Aaron Weeden and Patrick Royal Shodor Education Foundation, Inc. August 2012 Introduction: According to Moore s law, the number of transistors on a computer chip doubles roughly every two years. First

More information

CS 2412 Data Structures. Chapter 2 Stacks and recursion

CS 2412 Data Structures. Chapter 2 Stacks and recursion CS 2412 Data Structures Chapter 2 Stacks and recursion 1 2.1 Stacks A stack is a data structure in which all insertions and deletions of entries are made at one end, called top of the stack. Examples:

More information

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

More information

Java Software Structures

Java Software Structures INTERNATIONAL EDITION Java Software Structures Designing and Using Data Structures FOURTH EDITION John Lewis Joseph Chase This page is intentionally left blank. Java Software Structures,International Edition

More information

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013 Exercises Software Development I 11 Recursion, Binary (Search) Trees Towers of Hanoi // Tree Traversal January 16, 2013 Software Development I Winter term 2012/2013 Institute for Pervasive Computing Johannes

More information

Solutions to Homework 6

Solutions to Homework 6 Solutions to Homework 6 Debasish Das EECS Department, Northwestern University [email protected] 1 Problem 5.24 We want to find light spanning trees with certain special properties. Given is one example

More information

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

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

More information

Outline BST Operations Worst case Average case Balancing AVL Red-black B-trees. Binary Search Trees. Lecturer: Georgy Gimel farb

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

More information

Application of Stacks: Postfix Expressions Calculator (cont d.)

Application of Stacks: Postfix Expressions Calculator (cont d.) Application of Stacks: Postfix Expressions Calculator (cont d.) Postfix expression: 6 3 + 2 * = FIGURE 7-15 Evaluating the postfix expression: 6 3 + 2 * = Data Structures Using C++ 2E 1 Application of

More information

Chapter 3: Restricted Structures Page 1

Chapter 3: Restricted Structures Page 1 Chapter 3: Restricted Structures Page 1 1 2 3 4 5 6 7 8 9 10 Restricted Structures Chapter 3 Overview Of Restricted Structures The two most commonly used restricted structures are Stack and Queue Both

More information

COMPUTER SCIENCE. Paper 1 (THEORY)

COMPUTER SCIENCE. Paper 1 (THEORY) COMPUTER SCIENCE Paper 1 (THEORY) (Three hours) Maximum Marks: 70 (Candidates are allowed additional 15 minutes for only reading the paper. They must NOT start writing during this time) -----------------------------------------------------------------------------------------------------------------------

More information

Mathematical Induction. Lecture 10-11

Mathematical Induction. Lecture 10-11 Mathematical Induction Lecture 10-11 Menu Mathematical Induction Strong Induction Recursive Definitions Structural Induction Climbing an Infinite Ladder Suppose we have an infinite ladder: 1. We can reach

More information

Lab Manual. Data Structures (Pr): COT-213 Data Structures (P): IT-215

Lab Manual. Data Structures (Pr): COT-213 Data Structures (P): IT-215 Lab Manual Data Structures (Pr): COT-213 Data Structures (P): IT-215 !" #$%&'() * +, -. 951/6201617535973417*37311 235678976: ;7A

More information

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015 CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis Linda Shapiro Today Registration should be done. Homework 1 due 11:59 pm next Wednesday, January 14 Review math essential

More information

DATABASE DESIGN - 1DL400

DATABASE DESIGN - 1DL400 DATABASE DESIGN - 1DL400 Spring 2015 A course on modern database systems!! http://www.it.uu.se/research/group/udbl/kurser/dbii_vt15/ Kjell Orsborn! Uppsala Database Laboratory! Department of Information

More information

Catalan Numbers. Thomas A. Dowling, Department of Mathematics, Ohio State Uni- versity.

Catalan Numbers. Thomas A. Dowling, Department of Mathematics, Ohio State Uni- versity. 7 Catalan Numbers Thomas A. Dowling, Department of Mathematics, Ohio State Uni- Author: versity. Prerequisites: The prerequisites for this chapter are recursive definitions, basic counting principles,

More information

Lecture Notes on Binary Search Trees

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

More information

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution 16. Recursion COMP 110 Prasun Dewan 1 Loops are one mechanism for making a program execute a statement a variable number of times. Recursion offers an alternative mechanism, considered by many to be more

More information

Stacks. Linear data structures

Stacks. Linear data structures Stacks Linear data structures Collection of components that can be arranged as a straight line Data structure grows or shrinks as we add or remove objects ADTs provide an abstract layer for various operations

More information

GRAPH THEORY LECTURE 4: TREES

GRAPH THEORY LECTURE 4: TREES GRAPH THEORY LECTURE 4: TREES Abstract. 3.1 presents some standard characterizations and properties of trees. 3.2 presents several different types of trees. 3.7 develops a counting method based on a bijection

More information

PROBLEMS (Cap. 4 - Istruzioni macchina)

PROBLEMS (Cap. 4 - Istruzioni macchina) 98 CHAPTER 2 MACHINE INSTRUCTIONS AND PROGRAMS PROBLEMS (Cap. 4 - Istruzioni macchina) 2.1 Represent the decimal values 5, 2, 14, 10, 26, 19, 51, and 43, as signed, 7-bit numbers in the following binary

More information

DATA STRUCTURE - QUEUE

DATA STRUCTURE - QUEUE DATA STRUCTURE - QUEUE http://www.tutorialspoint.com/data_structures_algorithms/dsa_queue.htm Copyright tutorialspoint.com Queue is an abstract data structure, somewhat similar to stack. In contrast to

More information

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012 Binary numbers The reason humans represent numbers using decimal (the ten digits from 0,1,... 9) is that we have ten fingers. There is no other reason than that. There is nothing special otherwise about

More information

Data Structures Using C++

Data Structures Using C++ Data Structures Using C++ 1.1 Introduction Data structure is an implementation of an abstract data type having its own set of data elements along with functions to perform operations on that data. Arrays

More information

Solving Problems Recursively

Solving Problems Recursively Solving Problems Recursively Recursion is an indispensable tool in a programmer s toolkit Allows many complex problems to be solved simply Elegance and understanding in code often leads to better programs:

More information

Lecture Notes on Binary Search Trees

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

More information