Вы находитесь на странице: 1из 112
CONCORDIA UNIVERSITY COMP 352 : Data Structures and Algorithms Bi Summer 2002, Term 2 < Section: Cc Be Midterm Examination Name: ( esi Gg AY pV 7 Student io: ENS Question (6 marks) What is the asymptotic time complexity in the average case for the following ‘Operations (@) Remove an element from a linked stack (Pop operation) Cal (0) Remove an element from an array-based stack (pop operation) OC) (6) Find an element in a linked lst OC a) (4) Insert an element into a tinked queue (enqueue operation) CO) ees (€) Insert an element into an aray-based weve (enqueue operation) §—§ (90) () Clear linked list La Question 2 (3 marks) (2) For the folowing code fragment Sive the running time T(n) in the best, average, and worst cases, ‘ere Tin) expresses the numberof aray element comparecre = 7: Cr Tio) inthe best case: fist ewer? = eit 6) @ Tin) inthe average case Middle = Ja [ @cn), Te)inthewerstcase: eo’ chert i Fidg = DN by cry int DoIt (int+ A, int Ry, int k) { for (int i=0; i S; Lqueue Q; For(int k=l; k<=4; ++k) { Vv S.push(k)# Q.enqueue(k); } int x, yi while ( S.pop(x) && Q.dequeuely)) { + u 2 G52) ane aulput = uo 3,2 2, 3 l ce ie Question 6 (5 marks) (a) Draw the BST obtained after inserting the values 10, 70, 20, 60, 30, 50, 40, 45 in the order given. (2 3 (b) Give the preorder, inorder, and postorder fravérsals of the tree in part (a). NER Preorder, 191 10, 791 6D, 3O SOHO, US ¢5)'50, Go CUR moder 12, 19, 39140 11 CO, Gey TPs LAN Postoner ie ig 129% GOTO VP IE Question 7 (2 marks) Show the AVL tree that results from inserting 30 in the following BST. Cay a Ye RL iN 6). wm BS Ow Qo : &) GD Qo Question 8 (6 marks) Given a pointer to linked lst of nodes of type Node (see bellow) and a value Key, write @ recursive function named search that retums true if the value Key appears in the list and false otherwise. Your function should have the following prototype pool search(Node* head, int Key); where class Node { public: char KeyValue; Node* next; de Note: The lst in question is not related to any class and does not use a header node, Moreover, function search isa fre function (ie., not a member of a class), bool Search (Vode * hear? chan F9) if (ees == ot) felon (else [I bote cas< if (keg == heat 2 Rey vets) Fela SAR dla ttm. Goad ((uad eect | key) ‘ \ a Question 9 (10 marks) The following is a partial definition of the linked list class given in the textbook. template class Link ( public: Elem elenei template * head; // Po: to list header LinkcElem>* tail; // Pointer to last Elem in list Link* fence; // Pointer to last element on left side > class LList int leftent; // Size of left partition int rightent; // Size of right partition void init() (fence= tail= head= new Link; leftcat=rightent=0;) void removeall(); // Remove all Elems public: LList (int size = DefaultListSize) (init ();} // Constructor ~List () {removeall ();} // Destructor void clear() {removeall({); init();} // Reinitialize the list bool insert (const Elené); // insert at front of right partition bool appendiconst Elens); // append Elem to end of the list void setstart(); // Place fence at list start void setEnd(); // Place fence at list end void prev(); // Move fence one step left; no change alzeady at start void next (); // Move fence one step right; no change if already at end Ant leftLength() const; // return length of left partition Ant rightLength() const; // return length of right partition bool setPos (int); // set the size of left partition to pos bool remove (Elens) ; // Remove and Return in first parameter the first // elenent of right partition; Return true if // successful, false if the right partition empty. bool getValue(Elemé) const; // Return in first parameter the first // elenent of right partition; Return true if // successful, false if the right partition empty. void print()const; // print the contents of the list a Given a list A=, the trim operation applied to A will remove all odd-indexed elements a1, aa, as, .... from A to produce A = < jae, a2, a4, ....>. For example, i initially A = <20, 23 | 10, 412, 15>, then trim will produce A = <| 20, 10, 45>. Note that list A may intially have zero or more elements, and that the fence may be intially located anywhere within the list. Your task is to add the trim operation to the linked list class as a new member function and implement it in ONE AND ONLY ONE of the following two ways: (1) using ONLY the ciass member functions, OR (2) using NO class member functions and without creating new nodes. 'f more than one implementation are given, only the first will be marked. The trim function should have the following prototype: void trim() ; vod beim) § Link #21, ok coon ben. £2 j head : ‘Gere geo tf Peed ee Ns tisk hash tees t Zesetimen Fen cea) ae A veluin_head takak coon onsen? a element I — é- Aa “can ad Daoxd le | Ce (head, aeetts WEY fox will tootgetal! He eit ig Ceo a quan index awe She cue Li > 3.x = Gand)’ | @ “ \ Couns 4* 1 oe LpenPEeMUceffped o melt et ens: Toad == OULU febura® © a) x \ Ne made, Aad beens ‘howtid eat” Re bak Leo bean deetieged (uty!) = Memory Leak CONCORDIA UNIVERSITY COMP 352 : Data Structures and Algorithms Fall 2000 Section: WW Midterm Examination October 23, 2000 Total Marks: 100 (20% of the final grade) Name: Student ID:__. = Question? (16 marks) tf COTE Give the asymptotic time complexity in the average case for the following operations (a) © Clearalinkedlist__.- (M9 ) x (b) Find an element in a linked list__@(n_) ow ©) Createalinked stack OC) (4) Insert an element into a linked stack (push operation) Oud (e) _ Insert an element into an array-based stack (push operation) _ (» () Createalinkedqueue SO) . (g) Insert an element into a linked queue (enqueue operation) Oty (h) Insert an element into an array-based queue (enqueue operation) _£! Page 1 of 6 : Question2 (20 marks) Give T(r) and @ runing ime equations for the following code fragments. rn Lnitr we ; — - st Tinyeqgnd Gr +Ce The) te (ys ; (b) sum2 = 0; Lo bs : for (jel; icon: i++) ne ee A SY Oe for (j=i7 5>=1; 3-7) 7 : sum2++; ( bon - Tins = c+ DDT) = clea ») + ho i, gy Tim) rseO ln") 4 ()sumi = 0; Co for (k=1; keen; k++) a gor (j=1; j (? Marks) Iterative function: : fajstery Coons it ae f Oly oun 20) na for (ht Pa Ne1j ! aa re) 4 ug CAL ==X ) = Count 44 a iGo sia Page 3 of 6 Question 4 (20 marks) Causes braces, *{* and ‘)", to delimit groups of statements. Treating = C++ program as a string of characters, write a function pool isBalances(char * program_cpp)i that uses acharacter-stack to verify that a given C++ program contains balanced braces. Use the following deslaration for the Stack clas : soi £45340) typedef char Elem; * 1) array-based stack class 7/ Maximum size of stack 7/ Index for Top Elen 17 azxay holding stack Elem’s 7iconstructer: initialize j/Destructor: return array space 77 Remove all Elem’s from stack 7/ Push Elem onto stack 7/ Pop Elem from top of stack 7/ Return value of top Elem 77 Return true if stack is empty nt size; int top: Elem *listarray; public: Stack(int sz = LIST_SIZE); =stack0)i : void clear(); void push(consé Elem item); Elem pop). 3 Elem topValue() const; bool’ isEmpty ()const: (privat pBalence,s ( char * poy oP ) sh pat comnte » Chor Cj ~p SOE . 4 pepe = yim SHA gen oie Ce oh 5 ie ee ete 7 us ycontnee : neptyl) pgule (1S. 38 phy ) ae 4 c= S-pop J ) f peturin fi Page 4 of 6 SLC ened) = 2 Court 2 Question 5 (24 marks) Using the List class given below, write a function void Split(List& L, List & Li, List & L2)7 that takes a linked list 1 of integers, and creates two new linked lists U1 and 12 of imtegers. U1 contains the odd integers that are in L, and L2 contains the even integers that are in b For example, if L= (10,37, 48, 52,13, 78,35), the function call Split (ly U2, 12); will produce the lists L1= (37, 51, 13,35) and L2=(10, 48,78), and the list L will become empty. typedef int Elem; class Node ( J1 Singly-Linked node public: Elem element; // Elem value for node Node ‘next: 77 Pointer to next node Node(const Elem elemval, Node* nextval =NULL) { element = elemval; next = nextval; ) Node(Node* nextval =NULL) ( next = nextval; } of class List ( // Linked list class // Pointer to list header 1} pointer ‘to last-Elen. 7/ Position of (pointer to) ‘current’ Elem public: ” List); 17 constructor . -List(0; 7/ Destructor void clear (); 77 Remove all Elems void insert (const Elem); // Insert at current pos wold append(const Elem); // Insert at tail Elem remove(); 1/ Renove/return Elem “weld setPirst(); 7/ Set curr to first pos void prev(); 77 Move curr to prev pos void next (); 11 Move curr to next pos : int length() const: 17 Return length void setPos (int 77 Set current pos void setValue(const Elem); // Set current value Elem currvalue() const; // Return core value bool isEmpty () const; // TRUE if list is empty pool isnkist() const; // TRUE if now in list bool find(Elen) : 7/ Pind value Page 5 of 6 7 Vouk spt (LrbLe. Lun £6), a? " a sethire® (> : c,- cheer C) 4 Zz: choar ) ’ , Cuboke (1, staph) 4 of (eocomnltbuel) 12> = D ab art): WS. semnienel)) ? FINAL EXAM FOR COMP 352 | Department of Computer Science Winter 1999 Instructions * This is a closed. -book test. The test lasts 3 hours. * Nou must put your name and student ID on both your test book(s). Paper and vour answer (s) at the end of the test t be marked. The following operations are to be Performed on the records: 01 Search for a record containing a given LD number: al O( 25 3809) Yoh) ae 4a0) BOS” pat, of ed in a given course: 4) @ Yor) seta SOL a list of all students sorted bv ID numbers: = the following 3 date structures for vensional array balanced binary search tree sorted by 1D. nu table. hashing done on the ID. numbers ay Indicate. Consider the following recursive function what void what (ine sj { HEE <5) f (a) Show the sequence of numbers being printed when the function what is called with argument 1. Illustrate the contents of the system stack after each recursive call. Each entry in the stack consists of the function parameter the return address (use the statement line numbers) (b) Explain briefly how a stack can be used to simulate the execution of a recursive function svernn( nines B) 3, [10%] Input is a pointer toa binary tree. Each node has three components: a character 2 pointer to the left child, and a pointer to the right child. Write 2 function to print on the screen the characters in the leaves of the binary tree in the order of inorder ~ traversal. What_is the time complexity of your function? Explain your derivation of aaa the time complexity protec O72. gent cE OME EP On) Print nt phot or) 4. [15%] Heaps Poorer (ir bos hag kt) sy (a) Insert the follow order: sequence of numbers into an initially empty heap in the given aif 28. 10. 20, 19, 23. > Show the heap tree after each insertion step. (a Lee) (>) What is the worst-case time complexity for the above process to insert 2 numbers? {c) Delete repeatedly the maximal values from the above heap until the heap is empty e Show the heap tree after each deletion step. id) What is the worst-case time complexity for the above process to delete all values ina heap with mn numbers? 9.0) techniques va: Wate a non-recursive function QuickSort using a stack. You can use the stacs functions and the following function partition without declaration ant partation(ant e{], ant a, ant 3); / // Rezurns index k such that ali .. k-i)} end A alkes ji are left and right partitions where SortArray is defined as int array[1000} 'b) For your function QuickSort. what is the minimum stack size required in terms of the problem instance size n? Is your function optimal in terms of the required stack size? If not. suzgest modification(s) to your function to make it optimal pee 6: [15%] Use the hash function H(key) = kk ¢ mod'I5 (13 is the table size) to store the sequence of integers 7 ~ 7, 22. 28. 48. 39. 34, 23, 67 in a hash table, 8) “using linear probing (open addressing) b) using external chaining (1) For each of the above collsion-handling strategies, determine (after all values have 7 been placed in the table) (2) The load factor z § z 2 csses of the keys have an even distribution ) (2) Explain briefly the terms “primary clustering” and “secondary clustering” for : hashing, [15%] Memory management (a) Explain how the reference count method can e of linked si be used to deters *ructures are no longer accessible. (b) What is the main problem with the reference count method? Give an example (¢) Outline the garbage collection proces: ~ Explain why a recurs mark algorithm should not be ased ids Explain briefly how the collection without usin; ive or stack b: nodes ina generalized list can be t € Fecursion oF siack © END OF EAN © Name: ‘Student ID: 4 Question’ (6 marks) CONCORDIA UNIVERSITY COMP 352 : Data Structures and Algorithms Summer 2002, Term 2 Section: CC Midterm Examination What is the asymptotic time complexity in the average case for the following operations (a) (b) ( (0) ) 0 Remove an element from a linked stack (pop operation) Remove an element from an array-based stack (pop operation) Find an element in a linked list Insert an element into a linked queue (enqueue operation) eu LO) Lo) Cl) 'nsert an element into an array-based queue (enqueue operation) _(— Clear linked list Question 2 (3 marks) @ For the following code fra where T(n) expresses the T(n) in the best case: T(n) in the average case: ‘T(0) in the worst case: int DoIt (int* Olay agment give the running time T(n) in the best, average, and worst cases, ‘number of array element comparisons. fst beet = = 2/809 miidle = n/a / Ocon). dtu Fids = NV by cry A, int n, int k) { for (int i=0; in; i++) A af (ALi) == k) cy xeturn -1; return i; cr on Ta). nd + G Question 3 (2) (11mark) Convert the following infix expression into a postfix form Pit) . 13-4 Lap da fe (5+1)*(3-2)/3-4°2 I, i ie 7 / a oe <1 2Q-» 3/4 2 ae jx (b) _(11mark) Evaluate the following postfix expression ( 52+6°93/- ¢ 2 1 a) bo Question 4 (2 marks) Calculate break-even point for an array-based and linked list implementation for stacks when the size of an Elemis 16 bytes, a pointer is 8 bytes, and the array holds 100 elements, p22 N= DE, toni WO erik yp) (G8) et _ P23 = 66.66 ‘Question 5 (4 marks) What will print after the execution of the following code segment: Astack S; Lqueue Q; For(int i k<=4; ++k) ‘ Vv S.push(k); Q.enqueue(k); ) int x, yz while ( S.pop(x) && Q.dequeue(y)) f- { } u 5 Gy 2l Ke atpt 2 YI 3,2 an l C t Question 6 (5 marks) (a) Draw the BST obtained after inserting the values 10, 70, 20, 60, 30, 60, 40, 45 in the order z ‘oe sy (b) Give the preorder, inorder, and sani of the tree in part (a). eR Preorder, 11 LUC ———— 48) 503 Gey 10. T3405 CUR inorder: 19, 19, S014 1 124 Aa ul 5 BN Pastore ye yg 52192 LOL1]0 Question 7 (2 marks) Show the AVL tree that results from inserting 30 in the following BST. Question 8 (6 marks) Given a pointer to a linked list of nodes of type Node (see bellow) and a value Key, write a recursive function named search that returns true if the value Key appears in the list and false otherwise. Your function should have the following prototype: bool search(Node* head, int Key); where class Node { public: char KeyValue; Node* next; be Note: The list in question is not related to any class and does not use a header node. Moreover, function search is a free function (ie., not a member of a class) bool Search (Vole + heat cay key) if (hoe $ 22 MOLL) feturn (else [bote cas< iF (keg het okey ob) Tela boas eH (mm Geass (und react 1 ke) : X > Question 9 (10 marks) The following is a patal definition of the linked ist class given inthe textbook template class Link ( // Singly-linked node public Elem elene // Elen value for node Link *next; 7/ Pointer to next node ‘k(const Elem elenval, + nextval =NULL) { element = elenval; next = nextval; } Link(Link* nextval =NULL) { next = nextval; } template class LList :public List{ // Linked list class private: Link* head: // Pointer to list header inkcElem>* tail; // Pointer to last Elem in list {inkeElem>* fence; // Pointer to last element on left side int leftent; // Size of left partition int rightcat: // Size of right partition oid init() (fences tail= head= new Link; leftent=rightcnt=0;} void removeall(); // Remove all Elems public: Lbist(int size = DefaultListSize){init();) // Constructor List () (removeall() 7} 7/ Destructor void clear(){removeall(); init ();} // Reinitialize the list pool insert (const Elené); // insert at front of right partition bool append (const Elemé); 7/ append Elem to end of the list void setStart(); // Place fence at list start void setEnd(); // Place fence at list end void prev(); // Move fence one step left; no change already at start void next (7 // Move fence one step right; no change if already at end int leftLength() const? // veturn length of left partition Ant rightLength() const; 7/ return length of right partition bool setPos (int); // set the size of left partition to pos bool remove (Elemé) ; // Remove and Return in first parameter the first // element of right partitions Return true if 7/ successful, false if the right partition empty. bool getValue(Elemé) const; // Return in first parameter the first // element of right partitions Return true if // successful, false if the right partition empty. void print(jconst; // print the contents of the list a Given a lst A = , the tim operation applied to A will remove all odd-indexed elements a1, a3, a5, ...» from A to produce A = < jas, 2, a4 .... 42, 15>, then trim will produce A = <| 20, 10, 15>. Note that list A may initially have zero or more elements, and that the fence may be initially located anywhere within the list. . For example, if intially A= <20, 23 | 10, Your task is to add the tim operation to the linked list class as a new member function and implement it in ONE AND ONLY ONE of the following two ways: (1) using ONLY the class member functions, OR (2) using NO class member functions and without creating new nodes. If more than one implementation are given, only the first will be marked. The trim function should have the following prototype: void trim(); 2 list empty I ‘te Tra) Wa oe € uot has ab lest © Chest >roxt 2200LE) pak emp | ae |_sctin fend. $= aa lan amen ? Ts glomnt + It f thas 15 more thom F chery [Gaile Chead oad wor) 1) (poleodall He [cube Chee 7 iI) toodenda | Feces fis i esc ih | tied em nea Raed = Wad dend | counsea + * 1 : & 3 yexd SeWULTf pot o nelt at ent a fehrnc’ S Ne rede Ait beens hooti sot” Fe bak hoo heme deetegeds (tky |) Meme Leak Question 7 (5 points) Write a recursive function that searches an unsorted array A of N integer elements for the element K. IFK is found, then retum the index; otherwise, return —1 pee Search (ALT) Ny k) : BElwro) if @p-'J==6) reburn Nol) lee ee an gaasree (ALJ NED i noturn —l 7 4 lena of - fanctim Lo DEPARTMENT OF-COMPUTER SCIENCE CONCORDIA UNIVERSITY COMP 551/4 Winter 2000-2001 nal Examini Total Marks: 100 (50% of the final grade) Closed Book Examination ‘Time allowed: 3 hours No: Calculators allowed 21. Sorting (24 marks) (a) (9 marks) Suppose you have the following sorting methods available: ' + Merge Sort, * Heap Sort, * Insertion Sort. State which is the best of these methods in cach of the situations described below, and explain briefly why i is the best. Each situation is independent! i, Situation A. There are never more that 50 items to sort, and items with equal keys must be maintained in the order in which they appear in the input sequence. Situation B. The number of items to be sorted is very large, but you have just enough computer memory to store them all. sot Situation C. The number of items to be, sorted-is-not ‘more than half the number of that in Situation.B, and the data items are mostly in order in the input. —— tend Se (b) (15 marks) Use Quicksort to sort the following list of numbers. Provide sufficient. intermediate results to show that you understand the method. “31, 85, 6, 35, 42, 22, 4, 61, 67, 32. iii. 4.6 22 31323042 04 6/67 2. Hashing (20 marks) : () (12 marks) The following numbers are inserted into a hash table of size Mk ay 5, 3, 16, 27, 14, 25, 4. 19 Suppose we use double hashing to resolve collisions, and the two hash functions [| are: a a 313 HI(KeyValue) = (KeyValue mod 11), and . ol4 H2(KeyValue) = (KeyValue mod 10) +1. * Le Trace the inserti él ) (4 marks) Give an example of a poor hash function. Explain why it is poor. 7 rl (GJ (4 marks) Give an example of a probe sequence that fails to enumerate all table iat —* locations. e a } fr] eels . Tun Sree ES dbl of eek meng bf MB x2 = jap MO © = door Glucks / = f200¢MB =26) X 3. Extécnal Sorting (12 marks) i: Foon BS = fireeeMB =F. ve ie that working memory size is G4MBytes broken into blocks Of IGKBytes (there CAR additional space ay 1/0 buffers, program variables; ctc.)" What is of the largest file that can be merged using replacement selection ass of multiway merge? Explain how You got your answer. { 4. Union and Find (1d marks) Using the weighted I abl hould be in a separate” make the root with greater are of the same size, h lesser valuc. (911), (2,5), (6,1), (7,3), (8,6), (8,7), (5,3), (8,4). 5. Topological sort (14 marks) “A certain com; following tabl iputer science curriculum contains 7 courses: CS1, CS2, ... ic lists the prerequisite Structure: Wh: G2 ecg oa * course | prerequisitl 1 2 6% % f Si a — : CSI [none G51 est ; 82 |none- Su os: CB oe Ss] sa | ost ss. O84 C84" | CS1, cs2 : 32 oss | cs CS | none cs7_| ts3, css For example, in order to take C$3, one must have completed CSI, Use this example to ex; lain how you would schedule the courses so that the prerequi- sites are satisfied, : 5. Binary Trees (16 marks) " (2) Removing a node in a Binary Search Tree (6 marks) : Ila node & is to be removed fron a Binary Search Tree(BST), and R has two children, we can replace the value of by either the greatest value from the left subtree of Jor the least value from the’ he Fight subtree of 2, (and then removing the node with the greatest value or the nowe with the le: textbook notes that “If du ‘ast value). However, the plicates are stored, then wwe mu; ct the replacement from the right subtréc Give an example where Selecting the replacement from . the Telt subtree would be a ‘wrong choice, and explain why, (>) Array Implementation of Binary Trees(10 marks) Our textbook covers the “Array Implementation of Complete Binary Trees”. However, we can use the same method to store a general binary tree (i.c., one which may not be complete). Information about the parent, children and siblings of a node can be computed in the same manner. : i. (5 marks) Given the following binary tree, show how it will be stored in an array. A = i, (5 marks) In this array implementation of a binary tree, if we know that the maximum number of nodes in the binary tree is n, how big an array is to store all possible binary trees with n or less nodes? Justify your 1 & (b) Array Implementation of Binary Trees(10 marks) Our textbook covers the “Array Implementation of Complete Binary Trees”. However, we can use the saine method to store a general binary tree (i.¢., one which may not be complete). Information about the parent, children and siblings of a node can be computed in the same manner. i. (5 marks) Given the following binary tree, show how it will be stored in an array. A : F ii, (5 marks) In this arcay implementation of a binary tree, if we know that the maximum number of nodes in the binary tree is n, how big an array is required to store all possible binary trees with n or less nodes? Justify your answer. . S Sou, . 3 3: 37 B Ur ik ag ab 25.8 44 Ue sch} (1 S22 7 i ay t ¢ 1 tt if i ica. | = : £279 bos fra th. hee, i) some ~ phy apene i | %. M=zlo, ‘h(k= a) ral 2. j eS ® [pe oo . . | Pinkie etn 3 toe) (66) & RBS ot Otay Ss ee cs wee 1 ONE : ee sb eee SO ld thier bie, Gt ho: ven; ber) f re bur Biewy dene oe 's ARTMENT OF COMPUTER SCIENCE \ CONCORDIA UNIVERSITY & COMP 551/2 Fall 2000 & \ scember 6, 2000 , Final Examinatio ‘Total Marks: 50 (50% of the final grade) Closed book examination Answer all questions, Write your ID number, section number, and instrucwr's name on the examination booklet. ‘Time allowed: 3 hours. No calculators allowed. 1. (Algorithm Analysis) (6 macks) Given a floating point number z and a positive integer n, the function |, oo : ra ‘e Pover évaluites and returns‘z%, Determine the time commplexity of this function 7 using the © notation. Expres the answer in terms of nd ve a brief explanation bow you arrive at the complexity. Sp float Pover(float x, ‘int n){ » 9 “$loat ‘2’ = 110;7* 9) ° ete x NW float-a'= xz. °<. aes cat + inties= ¥ : SS > a Hiubdéie 22 Oet.acret a: — suite (fe % 2v=7 0) { Lowe / «x ie (2p yy. ; nN p Sadix Sor “is ui) bye) logs A a =” beatles sort + (b) (2 marks) The expressions below represent the growth rates of different algo- rithms. Determine the dominant term of each expression and express its time complexity using the © notation. i, Sn(logyg(n))? + L0n Vn + 5000 log, (loga(n)) ii. 50000 + 2n'/? + n3/1000 2. (Union and Find) ‘The following parent pointer array implementation represents the storage of equiva- lence classes. For each node, a value and a pointer to its parent are stored. Use this array to answer the questions in parts (a) to (t). ‘head ina general trea in which each node stores x pointer to the ieft child and a poinzer to the : d PPT Ife) ae lx sort on the following set of numbers. Show the intermedia 2 f :# radix of 10. You should use the version with buckets 27, 91, 1, 97, 17, 23, 84, 28, 72, 5, 67, 25. Pee %) (2 marks) Is Radix Sort a stable sortin 4 ' method? Give reasons to support your answer. DFS and BFS) Heected graph is represented by the following adjacency matrix: Cc 0 bolo coco oH+|a = io amoaWw> ecocoods Tis S:aPh should be used for the questions in parts (a) to (b) applicable, t ould be processed in incre Note that, when alphabetical value of their node labels Y, 8) (4 marks) Show the Depth labelled A. irst-Scarch tree for this graph, starting with the node (b) (4 marks) Show the Breadth-First-Search tree for this graph, starting with the node labelled A. 5. (Hashing) ; (@P Pemaris Giktin-t, hy as the hash functions foi double hashing and two keys ky, 2 where ky # ky. Under what conditions will the two keys follow the same probe Sequence when there is a collision? ue) (Cmarks) Insert the following keys i and double hashing with the functi nto a hash table of size 11 usinglased hashing =k mod 11 5 long as ths. key vabut 1+ (k mod 10) Is nob amultiple op AML keys: 10, 22. 31, 4, 15, 28.17, 88. 59 maded vou... Show where the ke} ys are stored. Please show the Probe sequence tor'each value stored, io 6. (Binary Trees) (a) (4 marks) A preorder traversal of a binary tree yields the following sequence of 9 keys of type char: An inorder fraversal of the same tree yields the following sequence of keys: JHIEZB OE. 7 = Draw the tree \ class BinNode { // Binary tree node class public: Belem element; BinNodes left BinNodes right \ Static BinNodes freelist; \ // Two constructors -~ vith and vithout initial values BinNode() { left = right = NULL; } i Binllode (Belem e, BinNodes 1 =NULL, -BinNodes r =NULL) { element = e; left = 1; right =r; } // The ‘node's value // Pointer to left child // Pointer to right child 3 - Brose ¥ Beidirte (chor 2 sche YEP) C 3 the third is an integer, n, which gives the n Your rou You can Perform e-ror checking. {} // Destructor Binllodes leftchiid() const { return left: } pitilodes rightchild() const { return rig 3 e() const { return element; }; void setValue(Belem val) { element = val; } bool iskeaf() const // Return TRUE if is a leat urn (left == NULL) g& (right == NULL); } voids operator, new(size t);\" /// Overloed ea void operator delete(voids); // Overload delete } should return a pointer to the root of the reconstructed binary tree ‘sume that the initial traversals are correei, ; Bield (naw * prewkr cher * andev, m ) A Toot = prrorder Cp 5 “Peed Obamclee’ on preorder CBT og ng sortie cory 9 Plen gom “Jatt setieny Iron swnordir Co 0 Se aft , : Cea wees Jom ore or fe 0) An . : on ee: whet jon fed ae merely avy, pod Syne tn Coogee f- che wom nein tae Ae ae clam der oe den (in - (eo, 0, She len (pre) pr 1 0, SITET v Pe Crosy VE (KL) oem ole £ @ a Pera CONCORDIA UNIVERSITY COMP 352 : Data Structures and Algorithms ‘Summer 2002, Term 1 \- e\N A\2 + w Midterm Examination Meenakshi Venkat Name: Student 0: SBS Questiont (9 points) Give the asymptotic time complexity in the average case forthe following operations: (a) to) 1) (9) (e) 0) (9) (hy a Clear a linked list & iN Delete an element in an array-based lis. Ofn YO Find an element in a linked list On 7 Create a linked stack of) w Insert an element into a linked stack (push operation) et 4 Insert an element into an array-based stack (push operation) __ 0 ip Create a linked queue oC) Insert an element info a linked queue (enqueue operation) ef) 4 Insert an element into an array-based queue (enqueue operation) _O 4 Question 2 (3 points) (2) Determine the number of times the functions F() and Gl) each are executed in the following code fragment: sum = 0; for (j=l; j<=2*n; j++) if( 582 == 0) 1; ixej; itt) : n FO) hb emecufid : 244464020 HW (n+) \ CF Saeetd tenerw) The oar, - Question 3 (2 points) Determine the break-even point for an array-based list and a linked list implementation when the sizes of a data element, a pointer, and the array-based list's array are 16, 4 and 100, respectively. ee ee od oy DE pa e£ 2) n> Come a \e+H ° _ 1609" ~ “36 = 80 Question 4 (5 points): For each of the following trees please stat both ether itis full, complete, neither, or @) @ AO On _. full Complete (both) complet (b) Ot, “ . Question 5 (4 points): Give the inorder and postorder enumeration for the following binary tree. node 3, 5, 6, 2,7,% I y, & -Postorder_ 3, 6 2,5 54€, 4 7 7 a NN ~ km Ns NO o> Question 6 (2 points) Draw the BST that results from deleting value 25 from the BST bellow Local: duplicates ow he AGF pyle? 4 Question 8 (8 points): The singly linked list shown below represents a list with no header node. esl fro [def [fe Ls Itis required to split the list into two lists, one holding the odd-indexed nodes, and the other holding the ever-indexed nodes, as follows: head headl eof ar [of 3 | tol as head? >| A0 >| A2 my At > > Ai VY Note that the original list may have zero or more nodes. \Wiite a function that performs the spliting operation without creating new nodes. Your function should the following prototype: void Split(Link *& head, Link *& headl, Link *& head2); where class Link // Singly-linked node { public: Elem element; // Elem value for node Link *next; // Pointer to next node Link(const Elem elemval, Link* nextval =NULL) { element = elemval; next = nextval; } Link(Link* nextval =NULL) ( next = nextval; } Mv via Split Clik wi head, tink * head), Link » 7 & (aed $= = nue” Twn Fj Link w pire heeds os ( pal=nneey ok fen 2. ae (ms h4) ; “Lt. mart (wlrey > exe) Question 9 (7 points) ‘A common problem for compilers and text editors is to determine ifthe brackets in a string are balanced and properly nested. For example the string“ ( ( (x+y) ) (ab) ) (c) " contains properly nested pairs of brackets, but the string “) (aery) (* does not, and the string ™ (x+y) } "does not contain properly ' matching brackets. Give an algorithm that retums the position in the string of the fist offending bracket if the string is not properly nested and balanced. That is, if an excess right bracket is found, return the positon; if there are two many left brackets, return the position of the first excess left bracket. Retum —-1 if the string is properly balanced and nested. Use a stack to keep track of the number and position of the left brackets seen so far. Stack GS 7 Wk R20 . pate Catryre ‘vo') : 2 oe Aan Uy a a p if (atiae= ‘c') if Epush ( , 3 ele if @E-T2= 0) if pep (#) ) 3 efse . return iy | if (S-istmpt0) ) Yen 1 7 elie p ee Name: Date: October 24, 1997 COMP 551, Section CC: Data Structures and Algorithms 7 aia, a / / Closed Book, No Notes, No Discussion Za ~ 1. Give a brief definition of Feeursive algorithm. (5 points) Recursiye alo rithm (Sa kine! of mettool (a Which ge ut calls itself te do port of its uwrk te solue -| the problem : boon wre + pet et Aorta, wy 2. Write a recursive function,tecilculate the following summation: (15 points) vw Summ(n) = 18428 4.04 nS 7 7 “ERS mam (ifn | - if (n=21) “Pan op. 7 "> retum t else nx n¥ ne née n + Summ(n-1 ) : ft j tas 3. Give a formal definition of 2(g(n)). (5 points) : 4. L f, L { mr) is a melation Sor form owe, bound 2» /ewer bounel indiet® He feast amount of feroot ce Hpuired Tor He algorHin. yyith imput sire lav) Sova ct’ th Fanning time cS Toads Tlndi's WSL @or) Uf Here are tun porctive infgr C and ne such that Wns ¢1G6 pete 4. Identify each of the following statements as being either TRUE or FALSE. (12 points) (a) n is in @ (logn’). frue (b) n?? is in O(10"). true {v (c) log? n = @(log n?). Fase 5. Determine @ for the following code fragments(in the average case): (22 points) (a) sum=0; Sa Os O(C,46, +Can) =O0n) Gn fromthe vrnev loop trough Secon of thner loo dhe | : op e cat es zis OCC 4 Cax(grtg nl) =6Cr ) 2 6. Define an ADT for list. (5 points) dato. tyPP 6 tt clef / ( form of te data ype dmc leading data 4 p2 and the cpewlienS performed on the va datu type Gonkcler ing te opel and cuts . 7. Give the average case performance(Big ©) for both array-based and (single)linked-list implementations of a list ADT: (16 points) Operation: array-based linked-list (a) prev Bo) O(n) (b) remove O(n) et) (c) insert 8(n) 61D (4) append OC!) C0) ADT 4 2) Lis bois on ordered finit seguente O] < itOns, We an perform Same operaction 5 such aS jnsert , Femerd, in the any position d of the List me 8. Let Q be a non-empty queue, and let S be an empty stack. Suppose that the element value types of both Q and S are ELEM. Using only the stack and queue ADT functions, write a function (void reverse(Queue & Q, Stack& S) ) to reverse the order of the elements in Q. (20 points) Void reverse (Queue Rg. Stack BS) ' aghile C! @- iSEmotyc) ) 5+ push ( G. dopucue () ) Gc. Gg) S118 Emptycr) Ql. enguee® (5, popay ) ; Comp €352/4 final exam. page 3 Question 4. (2 marks) If FDGBEAC is the inorder sequence and FGDEBCA is the postorder sequence of a binary tree, give its preorder sequence. Question 5. a) (7 mark) A binary search tree has n keys. a) What is the maximum number of comparisons when the tree is balanced and a given search key is not found in the tree? b) (1 mark) Comnent on the ‘ordering’ when the inorder sequence of keys is output. 4. [30%] Implement the stack class which you declared above Steck es push clemer VE ACelement tp)} it beep; Boke teowpi ; © tp cme gerd stacks: is Emp! if in Cty == tt oe Wee Midterm Examination + LL Student ID: 1 GoR3s Question? (10 marks) What is the asymptotic ime complexity in the average case for the following operations yn ln) (2) Create a linked stack (bo) Clear a linked stack (c) Find an element in a array-based list (d) Find an element in a linked ist {e) __ Insert an element into a linked stack (push operation) (Insert an element into an array-based stack (push operation) (g) __Insert an element in a balanced binary search tree {h) Delete the root of a balanced binary search tree Allogn)_ ~ () Insert an element in a degenerate binary search tree Oy 7 2 () Delete an element in a degenerate binary search tree Questigh2 (5 marks) / Draw the AVE tree resulting from the insertion ofthe items 18, 45, 51, 85, 49, 47 in the given order. Comp 3522 VW Febary 27,2002, Page tof Question 3 (8 marks) What is the running time T(n) and complexity @(n) ofthe following code fragments with respect fo problem size n ‘Assume that Mig a constant greater than 1, and that j, k, S are int variables. ni? a ++k) Ne) ele cn(nit) Tey) ew (W?) b. Ww) i in O(n) °. koc= M; ++k) - pj <= kr d+) vo) ee (441) Tory som OO) d k <= nj k*=3) logs” 1; j <= mn; jt) w son) 2 Cn logs sin) yin O(a lagen) Comp 3522 VW February 27,2002 Page 2 of 8 Question 4 (2 marks) Determine the break-even point for linked and array based lists when an Em consumes 6 bytes, a pointer 8 bytes, and the array can holds a maximum of 100 elements. : Ber foone) oe 8 att = bb, 66 — — (Question 5 (5 marks) ‘Write a recursive function to take an integer value N and print out the digits of N, one digit at the time, beginning with the rightmost digit. For example, if N is 123 then the function should print 321. ve vod Reverse i v) if (We 10) coul ce Wy alse Foul cs W104 rolurm Reverse CU/10) 4 ) Comp 35272 VW February 27,2002, Page dof Question 6 (5 marks) Consider the following binary search tree. a) Is itacomplete binary tree? b) Is ita full binary tree? c) What is the height of the tree? 5 ee 8) What would the tree look like after deleting the root of the tree? 40, 7 2) (e a aS Page 4 of Comp 3522 WV February 2 ‘ , ) Question 7 (5 marks) : (2) (1 mark) Convert the following expression into a postix form 2 C ) i 1) /6 a 34 (2 4 4) * (2 - ‘243 1 acta dD cl 3 a I< > ea ee j + — tee ail tH al (b) (1 mark) Evaluate the following postfix expression ce “So \ 23 a3 Sper mol iq qu (6) (3 marks) Give a pseudocode for the algorithm that you used to evaluate the postfix expression ( |ov ko dra ol 0) Shiny rom let te ghd ) Reed th, wale onde ding aC They are DP We operator slack a February 27,2002 Comp 3522 ¥ g the textbook. Link(const Elem elemval, Link* nextval lement = elemval; next = nextval; * nextval next = next: he : // Linked list class template class LList :public List private: LinkeElem>* head; // Pointer to list header LinkeElem>* tail; 7// Pointer to last Elem in list LinkeElem>* fence; // Pointer to last element on left side int leftent; // Size of left partition int rightcnt; // Size of right partition ightent=0;} void init () {fences tail= head= new Link; leftent void removeall(); public: LList (int size = DefauleListSize){init();) // Constructor ~List () (removeall ();} // Destructor void clear(){removeall(); init();} 7/ Remove all Elems bool insert (const Elem&) ; bool append(const Elemé) ; bool remove (Elem&) ; void setstart (); void seténd() ; void prev(); void next (); int leftlength() const; int rightLength() const; bool setPos (int) ; bool getValue(Elems) const; void print ()const; he Given a list A=, the trim operation applied to list A will remgve all odd-subscripted elements a1, 3, as... from A to produce A= < |ae, a, &, ....>. For example, if intially A= <2b, 23 | 46, 12, 15>, then trim should produce A= <| 20, 10, 15>. Note that list A may intially have zero or more elements, and that the fence may be initially located anywhere within the list. Your task is to add tothe linked list class a new member function ofthe form: void trim(); // trim list as described above and implement the function in two ways: (1) using ONLY the class member functions, and (2) using NO class member functions. Comp 3522 0V February 27,2002 Page oot Comp 3522 VY Elem, FAY wd counters 07 bool B= al Vole (EA) 1 sel Sod (4 while (B) g if ( cousler 93.9) a Fomove (£0), s nol C4 B= opiVabe (8) 5 Counle 4405 \ . ~ tet); 3 t February 27,2002 Page 7 of § Jd caw P heed * | Lie Type Tye tye Pian it t |r ly. ) Vy | Void thin) Ry ink — ¥ Carronl + hood swol, il_cowle sy Link < Blom > 4 provens while ( currend !: WOLE) d pee Corrosts Garren] snes], Lewd te Dhol _ : ( > previows = hosts ie deeds £3) Gueeewl ; cures] = pleveens i = ee 7 A tp? - Agt anc Acyht Centing Le > —/ Comp 3522 VW February 27,2002, Page kof & 2. [20%] Write a recursive function to first print the values in the nodes from head to tail, then print the values in the nodes in reverse order. For example. if we have 3 nodes. the printout should be: 1, 2, 3, 3, 2, 1. ERP FE NUL ved pack anh #2) f murs Mey Pe Tern 3. [30%] Write a nonrecursive function to solve the above problem based on a stack. Declare a stack class for your purpose. let ae S.pash (P+ 2lerer=) De Ponert 3} [S615 Euptt Coty p. ePOY : S Concordia University ® Summer 2003 Department of Electrical and ‘Computer Engineering (ECE) COMP352: Data Structures and Algorithms Final Exam July 02, 2003 Instructor: Abdestam En-Nouaary. Exam Duration: 3 hours. Total Marks: 55. Number of Pages: 3 Instructions: ‘© This examis a closed book exam. The calculator is permitted. Answer all of the questions in this exam. Place all the answers in the booklet. Read carefully each question before answering it. ‘The number of marks and suggested time to spend on each question is shown next to the question number. Question 1 (5 marks, 15 minutes) This is a True and False question. Answer this question by writing True or False next to every sentence number in the booklet. 1+ The algorithm to construct a heap from an array is in the order of O(n). 2. There is no algorithm that can sort an array of n elements in less than O(n log n). 3. The average number of comparisons required to locate a key in a hash table is constant, and therefore the performance of hashing techniques is, in the average case, better than that of AVL trees. 4. The worst-fit memory allocation policy is worse than the best-fit memory allocation strategy since it chooses the largest free block to satisfy a request that comes in to the memory manager. 5- The buddy method is a sequential-fit memory allocation policy, which organizes the free blocks into lists of size of 2. 6 The count reference method is used by the memory manager of the operating system for garbage collection, and basically consists of keeping track of the number of times each variable is accessed to in a program. 7- The height of an AVL of n nodes can never be larger than 1.744 logs. & The number of quick sort calls needed to sort an array of n elements is, in the best-case, equal to login, i Question 5 (8 marks, 40 minutes) a b Write a recursive function that takes the root of a binary tree as a parameter and retums the height of the tree, We assume that every node in the binary tree consists of an integer, a pointer to its left child and a pointer to its right child. Write a fonction that takes the adjacency matrix representation of a graph G(V, E) as a parameter and checks whether ot not the graph G is connected. A graph is connected if and only if there is a path ‘between any two vertices in the graph. a 7) Question 6 (12 marks, 35 minutes) Gy Given an array A of the following elements: 13, a 4, 12, 14, 10,5, 1, 8.2, 7,9, 11, 6, 20, 19. e b ce a e Give the result of sorting A after the third iteration of Bubble sort. Give the result of sorting A after the third iteration of Shell sor. Give the result of sorting A after the third call of Merge sort. Give the result of sorting A after the second iteration of Radix sort. Give the result of sorting A after the third call of Qui Good luck! a Question 7 (5 points) Write a recursive function that searches an unsorted array A of N integer elements for the element K. IfK is found, then return the index; otherwise, return —1 Preece Gh ie) Bows if Gly] = =k) cpeburn Nol) else “auen Suave (AL), DI J paturn —!) J lena of - farnctitm 4 CONCORDIA UNIVERSITY COMP 352 : Data Structures and Algorithms Fall 2000 Section: WW Midterm Examination October 23, 2000 Total Marks: 100 (20% of the final grade) Name: Student Ds, AS) (0°, Question? (16 marks) Give the asymptotic time complexity in the average case for the following operations: (a) Clear a linked list Bin) (>) Find an element in a linked tist__O.( 40) Create a linked stack OC) $$ (4) Insert an element into a linked stack (push operation) Oi) (©) Insert an element into an array-based stack (push operation) _@/«_) () — Createalinked queue sO) ay (g) Insert an element into 4 linked queue (enqueue operation) j (h) Insert an element into an array-based queue (enqueue operation) _ £14. Page 1 of 6 Question? (20 marks) \ Give T(r) and © running-time equations forthe following code fragments, jel: deen; 54+) for (i=l; Ey<= n/2; te N sumt++; C1 for (k=0; k else a oo | peturn false Count] +4 5 / 7 elseif Co=="}') if . court 2 445 Page 4 of 6 L LC coed) = = Court 2 ) Question 5 (24 marks) Using the List class given below, write a function yoid split (Liste L, List & Li, List & L2)7 that takes a linked list b of integers, and creates two new linked lists Li. and 12 of integers. 2 contains the odd integers that are in L, and L2 contains the even integers that are in L. For example, if b= (10,37, 48,51, 13,78, 35), the function call Split (Gy Li, L2)7 will produce the lists L1= (37,51, 13,35) and L 10, 48,78), and the list L will become empty. typedef int Elem; class Node ( // Singly-Linked node public: Elem element: // Elem value for node Node *next: 7/ Pointer to next node Node(const Elem elemval, Node* nextval =NULL) { element = elemval; next = nextval; } Node (Node* nextval =NULL) ( next = nextval: ) class List ( // Linked list class J/ Pointer to list header 7/-Pointer “to last-Elem - J, Position of (pointer to) ‘current Elem 11 Constructor ~List(): 71 Destructor woid cli 71 Remove all Elems void insert (const Elem); // Insert at current pos yoda append(const Elem); // Insert at tail Elem remove()j 7/ Remove/return Elem “void setFirst (); 7/ Set curr to first pos 5 void prev(); 7/ Move curr to prev pos : wold next (); 7/ Move curr to next pos int length() const; 77 Return length void setPos (int); 7/ Set current pos void setValue(const Elem); // Set current value Elem currValue() const; // Return current value bool isEmpty() const; 7/ TRUE if list is empty bool isinbist() const; // TRUE if now in list bool find (Elem) ; 77 Find value Page 5 of 6 Question 2 (3 points) (2) Determine the number of times the functions F() and G() each are executed in the following code fragment: sum = 0. for (j=l; j<=2*nz j++) if( 482 == 0) for (i=l; i<= PQ: ct yoo fo emcentat (1) ines C0) B emeetid : Bru rot BE . Shen = rhs. pam | itt) - Question 3 (2 points) Determine the break-even point for an array-based list and a linked list implementation when the sizes of a data element, a pointer, and the array-based list's array are 16, 4 and 100, respectively. El, h , Dzloo n> DE _ a ny (oo Ie 4 ve+H . a [60° Ww = 80 + Question 4 (5 points): For each of the following trees please state whether it is full, complete, neither, or bot (a) (a) Y . Question 5 (4 points): Give the inorder and postorder enumeration for the following binary tree. woer_3, 5, 6,2,7,4% 1, 6, & ~Postorder_ 3, 6, 2,554€, 4 77 CONCORDIA UNIVERSITY COMP 352 : Data Structures and Algorithms Summer 2002, Term 1 Midterm Examination name:_Mesnakshi Venkat student hSBUSG Question’ (9 points) Giye the asymptotic time complexity in the average case for the following operations: (2) Clear a linked lst ol Nt (b) Delete an element in an array-based list Ofn) a ()__ Find an element in a linked list Oln x (6) Create a linked stack of) vo {e) __ Insert an element into a linked stack (push operation) of) 4 () Insert an element into an array-based stack (push operation) & dh (@) Create alinkedqueve SOC) (0) Insert an element into a inked queve (enqueue operation) (1) (Insert an element into an array-based queve (enqueue operation) _O- i 7 . Vook splet(Lnt£e, Leaf Bey, tant ftv.) 7 gelloect (>| i ce hear CL) 4 - ehoar 6) % Gubate (13 ateplg0) { af (ls cuser tale id= = ') L, at Damon) )’ po sant) ; Question 6 (2 points) Draw the BST that results from deleting value 25 from the BST bellow Recall: dapl Coker tw Me AGE pesbeier 4 Question 8 (8 points): The singly linked list shown below represents a list with no header node. head palo [44 2 [fel ——[me It is required to split the list into two lists, one holding the odd-indexed nodes, and the other holding the even-indexed nodes, as follows: head head afar] tf 3 [Las TL >| ak head? »{ ao | tf a2 | tf as > Ai Note that the original list may have zero or more nodes. Write a function that performs the splitting operation without creating new nodes. Your function should the following prototype: void Split (Link *& head, Link *s headl, Link *s head2); where class Link // Singly-linked node { public: Elem element; // Elem value for node Link ‘next; // Pointer to next node Link(const Elem elemval, Link* nextval =NULL) (element = elemval; next = nextval; } Link(Link* nextval =NULL) ( next = nextval; } void Split (Lok wi heod, Link ® &head/, Link ¥Ké ; cE (famed G2 = NULO) -— Lenk pee woke ( perl = ee) i Xx NX tee Lr ware (6h) ; a fey ct Ge eS a Question 9 (7 points) ‘A common problem for compilers and text editors is to determine if the brackets in a string are balanced ‘and properly nested. For example the string " (¢ (2+) ) (ab) ) (e) "contains properly nested pairs of brackets, but the sting ™) (ety) (does not, andthe sting ™ (2e+y) ) does not contain propery matching brackets Give an algorithm that returns the position in the string of the first Offending bracket if the string is not properly nested and balanced. That is, if an excess right bracket is found, return the position; if there are {wo many left brackets, retum the position ofthe first excess left bracket. Retum -1 ifthe sting is properly balanced and nested. Use a stack to keep track of the number and position of the left brackets seen so far. Sack Gps 7 oe £20 while z le Cafe 2 ‘\o') Aen by - Pe if (Alide= ‘c') if bpush C y) ele if @f7+=')) if Eps (ey) 43 else F return iy 3 if (S. ictmptyC) ) Y Arner a; 8g vo | Aattewiarg, Again f Usrrans / ® 7 Show ihe ate iawelved jn buik Gut ine ange at prtrdunt Prdadure “Margret (ig inkan ) Vor k integen 4 j Pegi aed be A) cat ’ ' Regine As (beh -4) div 2 Meageaoat (1 ,&) ‘ ant oot see Final, Exar climg a dertemd.ing fuan fom 4 £5, 45, 40,42, 20, ho,” , 35,50 BT plat the Hlangent value at ast tion, +. Fuem tlemunt 4 ty nm yompan its value with it father volue by -Amewine that farho, of afi} a afi divad 5 if its son is biggun shun 4 4 a so 2845 S048 20 40 y 45 By 50 40 gy 85 42 gd 40g 35 3030 20 85 4k OAS. yo gas 50 300-0 85 48 15 OG OBB, — 30 30: 35 AR 45 kg YY, 50 yp Be oF. ici 4 \ Nees Give => lett t , a 4 Ve Ceerbeee. St — (with im prurdeeade 7 €); Daw tae cbtaimed by deleting 'hlue", "sang" im that onder Oto the boundary Tog matted of Atorag® om _ Qe in 2ach adfocated block . 7 b) The barte stem of the Gkuatar algesittn 7 | i | i / 2 anoun : cafe | black red , | eh Sam LES a beige apie syle : ° magenta white ¥ Jy debting an intomal node with “ twomen . rll subtazes 1 hephac the deleted node with « sede from dhe Aight subtite . -|a) imdicate what allocation imfovmain is dept im each {au bhock an vo4e. 1 Amey implementation avait ——> TT IS FT) ent ade! » | Fumction Getnode ( ¥ ess | 4 avail = mull thin | ~auhiteln (1 out of — : ) 1 anteger Maeva mext [oval J ve mull cee Evo 4 Prowduxe Freenode ( vor p : pointer ).. mextip] 2 wat : 1 awast = Pp P = mull ond 2 Sb) | Batd on the Menage ool above _eaemplement 2. queue mune — jester Lad tat - | Ded aration i amt 1 = AD ho type queue + recoad _ : data + ansay [4 99) af integer... front jscah = 0 oe ond j Vax qi quae 1 Fumetion REMOVE (ar gi queue ) ; Sl GBY oa beain 4 Arent 2 (Gear eh )-mod mf emely Y they Se Coes pire ie Ele, Eagan *enove fe _daty ron ] {sorted im descending ade ) @. — Batanced Vee Limtar Vienked Mishoo | nesPeoe = OUT peat Caz: o(4) . Want cote © 0(oq0) MOC Cater Goa e JAvnaqe 2 -0(tog.0) Average :0(2.) deletion | bertcae - o(4) Td West watt 2 0 (Log,.0) Ayaage = 0(40g.) a ae dosecg toy tiene] fodiens ate oie. sien (ey each tame or Fimat Exam 19 | O: dine Mu fetlowing = on cece 7 il ADT for pune + abiaae clate Type fom 2 cee a Atauctet vat abstract Lvl : \ om pata, tauchune 4 Aust in fiaat out _(E1£9,) «| Rimar ARO — which ‘ety data, "umands bas A Lift son... palo stduclune in git Aon. and the valu oll, soda. jn dhe Lypt_sub® ihe alae. of oll 2 “4 siaictla _bimona tane + (full) A due im which 2veny ered Gemnpletelg plavetly bina tate A Aticly bimony au in which all beta “an Son tbe same lee ye | Rinse da ct ondin M = co patonte( weds. well Which fal (acy OUR SO yw eile westel Double hashing :(o veloilie} sb ) ee 7 gigezeers bak ca Cher wed ¢ eave 22 FI (38 eee (ahora) ’ wed tebe) Rebaslag Cperter) = (peetien ee) j 4) pot St ume teqmunister : ovate | Agcadies ox abe Mate ) fe 4 por oy qe few ! CT v Thnaahing inv garbage edlection + sued by aang ellecti . y Hine axe Jew aod cam he ganhacg calectay wilt be poryoured vi, dace 7 tid thnaruing . nading peally, deqva de s 4) i oe ay pee {bem }___ eR ar ~~ BI) 23 mod 44. 40 64 mod y= 2 Ag Ms 4s 8 u 322434045 thd 4205 at . ° ° e (\ Ext, Uicinina | i a Resear ad Mh > Ga So Rta ert tet 2 OM 7 i637} > BE) t 7 z . Us tbaedrast og | ASG . 0 tL IA Oy 2 k Hl a Aad oes is N |, l= Aaa 5 AaQr é (oe r E is 4 2 0 v Total & 4 $2 whoo Frum ev Of Hamon | a wer) SW Aiea yeep 4 ul “a ~ © waite prowdere to grind out she modes of binary cee EROCEDURE LEVEL (7: nedepts) ; Van Qs quae of modepls } to ngdepia , ee begin _ Makeraf (@) ) MAS A fo% TE rep ah iment (8,7) while mot emyty (&) do Begin ti 2 Debleg (a) wate ln (4%. anya pte ut <> nit then imat (@ tt dyt) 4 ED right © > mil then irmert (@ + 8 aight’ ) an PEND a sduseend ng, Arionilyy i) —eap i ——----—-—~ The foltewing, 2 dota Atucluns enw seinsdvnd fr am ingle” EQUI hee "et oo ad in ng A ey Q) -Womt eo coh bu, En he at i nk es). ie te - tM —es Pe _Limeon Himbed. list. wot can =. ..0L4) ... peat cae =. OCA) PWD AGE Ui * oe qevtacp * sett Mak _A : : “intomal a a. ide nhoe + ae a mode IS..mapked .. suet 4 ‘a mode ism arhed _cAiE un itt oe _owaile A asa. — Dercnibe infowmall dhe to co phan. Of dhe. aohey ,collectio -stqumtially through 4 Fumetion EMPTY. (. $ : stack ). : boolea Fagin, - . . - fg we and tavceduay. rust (Van Vor Lip: antag - Regn : data [+] -|mect (t]} + S$ 4. end Lwocedure for (var $ » stack, Vor t . imteger 4 Begin — we ig amply (6 +) iam a . waste ln iS Hack. sede D) OS Begin 3 pis datas] . v END Ergedue Makenull ( Yor $: atack, mean anilegey 5 j while $< > auth de degin I tie mat (SJ 1 feted (5) Coat sagt is evtnant a mmungprort i <_ Manag AK moble 2 lan. : ve youn amquate choca met Japport poole, iy nunt a Atos o gf poo \ we amay *9 anglers sage urewoad Seer —— data, munt . ep ote ; and , » je function aplnadt ep ewe = tlk Mun anuteln (“Out of ATA ') gant (eval) mull Geimode v= ? and END (vor p: amteg ) 7 Prom duse FREENCDE Bequy Next (pd = onal Aveh § P meee ? fee ad yond ) b) pasd on He sesame gat abeve argument Atak amd Pus. EMITY IG Oe ‘thy syed TOT )) Explame " paimayy dustring fo frothing 1) Lrimony dusteung MBit; Povted te 0 partianer paihion wit follew 4 rare avhashing atten amd ecttide with each other J. Seeondany Uuateing Tie eihgabing pelle jon SOpeMMrbeRPRRTIE, com merge doglhr oS - a Brocedune IP (Van p : modenta ; Van IPL stove wamtegen ); Regin yp = mit Mun TPL ze O ade if (p taeff = nik amd pAright)=mil thon Erk = & ee TPL « dowel 4 re( pfileft , TPL ,fuwel at) ¢ EP (Pfright Pt, amd . : ' © explain how repre eunt can be wed to dot which 7 ep Hirde d Arvuuctures art mre lorger ace ble * (ans. when TRL repre, runt im amy mode becemes yor lahat mode i met_acumible dum the yam anymere tan cl is pstwued de He @ Ve -| . lak ee = thew ew the sontents ant shamged after ive op wed thin the mock § ort .dtlutid ancl Oe a 40 MAb —_ aoa a hu § 6 1 eeeeeeeeenee afblelélel sig thlil ilk Z| EPP ed Yd WE AE _ . ~ | RS i Avail i @ A bmawy segrch ets - - - SS ‘anon , blue , black 1 yellow, taewn , ange (Med jungle. beige magia white , AteAting wit am aemplay dame oo ———s—S—=—“aeE= gre oder oe Fo blake, fhe above newnes im the Z y) = Hh | Hack black hu im \ i ( 4)\ float oade, beiep back bacwas bhag magent@ purple Lr yallew oe ty —_ 4 a 7 CONCORDIA UNIVERSITY il ° DEPARTMENT OF COMPUTER SCIENCE CQMP352 WINTER 1992 rl Mid-term Exam 1. (15%) Implement two queues using one array. Your implementation must also detect queue overfiow and tunderfow, In sddition, an overflow occurs only if every element of the array is used. 2. (10%) Implement a queue with two stacks and analyze the asymptotic time complexity in O notation. \, 3. (20%) What is the result of applying the procedure function Kystery8(x:pList): plist; var t: plist; Pr begin Glee o 4f zens) then Mystery@:=nil _ wysterye:et n * a ond : to the list p as shown on the right? ApcD- ¥2/+AEFHI-¥+/4Xb¥- _4/(20%) Convert the arithmetic expression (A4B*(C-D)/2+A/(E+F*(H-D)X*Y) into both poet orm and binary tree form (so that postorde traversal of the tee can produce the postfix form). F cog tuk Ms meee OCD A ee/AAc in Uinen tata mad ee, 8, (25%) Design aa algorilben oe delet Ag ET Ble nhede ot the remaining no: / wochanged, (Bint: itis easier to think about the successor and predecessor of & node in preorder) = 1 “Beet sub Geb werk ‘ 6, (10%) Insert the sequence of numbers (15,9,2012,4,31,1.8), in the given order, into aa empty binary search _/ tree. Show the resulting trees after 7,5,9,10 are inserted, after 7,5,9,10,2,4,3 are inserted, and after all the numbers in the sequence are inserted. 4 ole eves CS be i | ie oa yelp c Tr 2 Wiakown Sektaciy res Question COMP SSR Aukumn 2000 Using zhe public functions for the class Li st given below, write a C++ function, *6 12) *@ Li, that creates a ist from elements in L1 and L2 by alternating elements in the two lists and then appending the remaining nodes of the longer of two lists. For example, if Lt = (10,20, 30) and L2 = (15, 25, 35, 45, 55), the calltoAlternate (Li, L2) produces the list (10, 15, 20, 25, 30, 35, 45, 55), and L1and L2 become empty lists. Assume that list elements are of type class List { // Linked list class private: Link* head; // Pointer to list header Link* tail; // Pointer to last Elem Link* curr; // Pos of "current" Elem public: List(); // Constructor ~List ()i // Destructor void clear(); // Remove all Elems void insert (const Elem) ; // Insert at current pos void append(const Elem); // Insert at tail Elem remove (); // Remove/return curr Elem void setFirst(); // Set curr to first pos ~ void prev); // Move curr to prev pos - void next); // Move curr to next pos int length() const; // Return length void setPos (int) ; // Set current pos void setValue(const Elem); // Set current value Elem currValue() const; // Return current value bool isEmpty() const; // TRUE if list is empty bool isInList() const; // TRUE if now in list bool find (Elem); // Find value he Solution List Alternate (List* 6 L1, List* & 12) { List 13; while ((!L1->isEmpty ()) &&(!L2->isEmpty(})) { L3. append (L1->remove ())}; L3 append (L2->remove ()) } while (!L1->isEmpty()) L3 append (L1->remove ()); while (!L2->istmpty ()) 3, append (L2->remove ()); return 13; Pace 2 of 4 Question \ sem alist A= (@p, 2), 2 ay @y -»- 2y), the trim operation applied to list A give = (ap, ), thats, elements a, with odd subscript‘ are removed. ‘Add to the linked tist class implementatio:. « member function void tr which tims the lst. To keep this question simple, m() should just reset the curr pointer to the head of the list. ‘You should assume the list node and linked list classes as given in your textbook. For your reference, the declarations for the list node class and for the linked list class are reproduced below: linked node class Link ( “ public: Elem element; // Elem value for node Link ‘next; // Pointer to next node Link(const Elem elemval, Link* nextval =NULL) { element = next = nextval; } Link (Link* nextval { next = nextval; } class List { // Linked list class private: Link* head; // Pointer to list header Link* tail; // Pointer to last Elem Link* curr; 7/ Pos of "current" Elem public: List); // Constructor List(s // Destructor void clear()i // Remove all Elems void insert (const Elem); // Insert at current pos void append(const Elem); // Insert at tail Elem remove ()i // Remove/return curr Elem void setFirst(); // Set curr to first pos void prev); // Move curr to prev pos void next (); // Move curr to next pos int length() const; // Return length void setPos (int); // Set current pos void setValue(const Elem); // Set current value Elem currValue() const; // Return current value bool isEmpty() const; // TRUE if list is empty bool isInList() const; // TRUE if now in list bool find (Elem); // Find value ae remove->n curr->next->next Pace % af 4 oR void List ( Link* temp; while(curr->next !=NULL) { if(positiont2 ) curr=curr->next; else { ltemp = curr->next; curr->next = ltemp->next; delete ltemp; ne positiont+; al tail = curr; curr = head; Question Fill in the code to remove an element from the top of the implementation with the following definitions: class Node { // Node class public: char aValue; Node* next; li class Stack [ private: Node* public: Stack() ~ Node* Remove // Linked stack class topofStack; Os stack, and return it to the calling routine, in a linked stack pede renee oO Sb (aon = 29 | chun; // Pointer to top element {topofStack = NULL;} // Constructor ution er } Stack: :Remove () LL) return NULL: if (topofStack Node* temp = topOfStack; topofStack = topOfStack->next; temp->next = NULL; return temp Pace 4 af comPss2/1 ca Concordia University Sumumer1998 Data Structures and Algorithms Midterm st July, 1998, Duration: | hr 15 min, a) What is an abstract data type (ADT)? How is it related to the term bj A double ended quene is a list in which all insertions and deletions are made at the ends of the list. Define an ADT for this double ended queue (DEQ). Your ADT should consist of the functions that can perform on DEQ, with each function defined in terms of its input and output. [1 2. py Exponentiation is implemented in (++ with the pow function, which is defined in the math library. Instead of using pow, write a recursive function to solve °, where n is a non-negative integer and + is a floating point number. [6] +b] Determine © for your recursive function. Explain how do sou obtain this © by write out the cost of recursive function using T(n) as the growth rate. [4] «Ts it always possible to imitate recursion with a stack? Rewrite your recursive function to a function that make use of stack to solve 2”. Assume there exists 4 ADT Stack that contains the following three functions: void push(const doublez x); //push x onto stack. double pop(); //pop the elenent from to of stack bool isEmpty(); //return true if stack is Yon do uot have to implement these three finetions. ‘10 $6 What fs mean bp Dies dean che i What y Tinets ns cue 2 L What is mean by Tin = 6 a os chat ya SO) er sit ee user write the wove Analysis the asymptot and worse vase, Asstiune + no more swapping is need. algorithm in its best rasy contents of +h suetion Banary takes (og) to the simpli iv aperations like ‘aces. Yuu should simplif wave learned in class. Al 1° @ uotation acrord sume in array where K should be inserted ia it. sot binary sat L© left int rs right * 1; // 1, F beyond bounds of array while (Let te 2) (// atop when 1 and F meat, ant i = (1¥z)/2; // look at middle of ubarray ince array, int left, int right) ¢ 42° Carreylil) v= ij // Te dete halt af (km array(i)) return i: // Found it if (> arrayli]) 1+ 4; | // Tn right halt > Fevurn F; // search value aot in array, return position > ) Outer for loop always execute n~ 1 times. The Binary function always execute fog(n) times. Best case: The inner fer loop executed 1 time. Hence, the time complexity is @(n(log(n) + 2) = G(n(log(n)}). ‘Average case: ‘The inner for loop executed { times. Hence, the time complexity is (n(log(n) + n)) = O(n?) Worse case: ‘The inner for loop executed i times. Hence, the time complexity is 8(n(log(n) + 8) = lr?) ‘COMP352/1 CA Concordia University Sommerioos Data Structures and Algorithms Midterm Solution Date: 2ist July, 1998. Duration: 1 hr 15 min. 1. a) An abstract data type (ADT) defines data type solely in terms ofa type and a set of operations on that type. Each operation is defined by it inputs and outputs ‘An ADT definition does not specify how the data type is implemented. ‘A-data structure is the physical implementation of an ADT. Each operation asso- Giated with the ADT is implemented by one or more subroutines, The term data sructure often refers to data stored in a computer's main memory. 1b) The following are the public functions (const int sz = LISTSIZE); // Constructor Queue; // Destructor 7 Cheer quese void enqueue front (const ELEXE); // Eague vesd anqueue-rear(const ELEME); // Eaqa ELD dequeuetrose(); / at front ELEM dequeuerear(); book isEapty(); // True if queue is empty 2a) double nypo (int a, double x) { if (2 <* 0) return 1.0; return x * nypow(s-1, 2); ? b) T(n) = Tin -1) +6. Hence, it is @(n), <¢) One of the most common application for stacks is the implementation of sub- routine calls in most programming languages. A subroutine cal is normally imple- mented by placing necessary information about the subroutine onto a stack. Since a recursive function is a subroutine, it is always possible to imitate recursion with a euack, double it count © Stack 9; while (count '* 0) { .push(x); jer (int m, double x) { > 3. a) T(n) isin the set O(/(n}) if there exist two positive constants ¢ and mo such that {7(n)| < ef(n}l Yn > mo. 2b) Tin) isin the vet M((n)) if there exist two positive constants ¢ and ny such that [7 (n)] 2 elf(n)] Wn > no, €) T(n) = OC/(n)) T(n) isin O(f(m)) and T(n) is in OLY(n))- 4) To show that (n+ a)! = O(n), we want find constants ¢1,c2,no > O much that O< enh <(nta)) Sean! Yn 2 no, Since ¢ > 0,lel= Note that n +e = pos; j--) array (jet] = array(j]; 4 Srsrlpee) = eames > ‘The following is an implementation of the binary search which returns the position vos saanzonzzs aS77 92 pouzca Gyice so apes38 953 wyataes (a) (491 rebuot ou sy pz0307 2 uaus seisssaz sua eo UyeTa2z (2) (481 sevenseura Keoens /3\ 53 paietse s ktsy te t22 | Bayaord seeer | (@) susuyeus ecexedag auayas udrsntosss-uoysstze9 947 Sursa sergees OV esr é «abe ‘ : coeisany use SUyROTIOR 20 fey MEISE) 56: sevgroua-aees. ANTS 227 TOR raw 1 shootlve 5 2a, ppnow (1.52298 See de Ge (isle au88 Te 3 cuyseazepe ve UT3a0 ve 2 ees uo os pue (a)a (116 tie (le te Te &, Govarwuscazger Suynottos 943 sae Eine setae westarey aa ata “Bs GEER eyauenbes pazoas sy & Bunose. pe: guest OTN dre ov ety eTzaew puss szenb tose sez0n 23 ple 4829 3494 $83, (309 107 sayayco6ye rok wy porynbes ZU0sT3E fecue 2u4 SESE pow w sew es pue sopou + sun azedans, Speritersturun wee $01: oa san TT ssaeyt oy 30a ‘wos ponouos sy 24 vaya. ‘7S Bus TS SISTE #05 UY F303 posomes, 3 37 “pson zouae OT “S35 3T e304 MIT Teese ous Waa Tee eastey og mTOR Se oBTeS (sero) geaboquy pervades ou axe oz0us PETE O02 UIA, 226924) ey — suoysyiteo sateses gy pean #4 & oS ESET aaa ur sped yews 30 PTeTy OME Nay ea Fe ease Seinonts. penuTey AteuT Ont HATE OD OO} paseeyeOS seu Goynese Save a a deel ™ tegew 1 Peet oe i LS : ? sauoyettio> saxonse says "exy 28 TEIN Se YOOTT LOH beyuuysoq sy uygond secure seus Suranses, epseen® se jun yes iy! He"say seereere Me on sh ee Nari: — Gan be —_ Instructor: Dr. L. Tao All solutions in this midterm should be in C++ 1. [20%] Declare a class named link for a node which contains an integer field for value, and a pointer field to link these nodes into a singly linked list. The class should have a constructor with optional parameters. Write a function to establish a linear linked list with 10 nodes such that the ith node from the head holds value i. This function will return a pointer to the first node. Link ¥ pounced § neh = P53 linia C Let Liem , tak* p2nu? § elemew akeeat hen de tem 7 Me 2. [20%] Write a recwsiv: function to tut print the veluey is she nodes from head to tail, then print the values ia the nodes in » verse ovdci. Vor example, if we have 3 nodes, the printot should be: 1, 2, 4, 3, 2,1. 19 - : i) vod pronk Unk + PD if C pas Nu rerern ' cok cc Por value . 4 void clear? 5 void pase C mt D7 unt ppc? , 09d ssEmpty 6); Cok cc Pup value ee")' / FS push C9 value) - = D> rat U j z while C'S. IsEmply 2 ) f Conca a Ou POC aay 4. [30%] Impleinent the stack cl:ss which you declared above. zu Stetk 1: stack C int 52) i ne Mee {[ wre*t; wha C +p) i ta sp oe na; delle ¢, / 3 3 [ vod seeks: 74h Cont p chem P 5 * Pr 2 new Lat ( item's pi} Uek Fe 2 pop cd, J a sseck Ct wempty cd DA 7 pestorder: . ‘e 5 nortan dBm gi ais po & c) "Give the preorder for the tee in the). a Poaec Mgnt jetermine the number of [2505] Write a recusive and a non-recusive algorithm which di nodes in a binary tree. Tow VIZ dee aa aa ryt eas tree t1) © > viel shan ote Apt + Gosh os Pe ‘ = zit the, Vee q iy Mite AC a+] ane ane ¥ 2 !Fee th) e>nil thee 255 esi oo a Gay £/ Mote 2) eg wb thers wings block Ch of these Five aTTocation reauests t Page d y. Qe qo 3 solution schemes chaining "8 count method dere: jer needed applying eh ce 4 containing « eye; 1 of we ‘Fonabdnr § 96 ef 86 fn vhtch che valug "0" rep pty call. Lae che pris 13,17, 19, 2, 1, 1 30 ring che heen marboda Detour m ty, nene probing vich tncganane of 1 scundracke probing wih ©) For wach of jventschene in witch equah #126 ne based solely of the uch of the felloving oparettons (assuse & Large Tc techntaue taleost appropriate for wach of the ftTowing ordered Stems, randon'fec r gagreancs + Me tha priaary hash fon of arrival for tuanrtione luting the hash aathods below: nent, schene in which equal sine ing nenocy of 1024 bytes, where the sagan the abated gree re Tess Lite {a’aipnabetical order’ AE chee Ifse ts polneea to r'the following state of & within a storace management # Farkslic. Deleting the node labeted F. 4 record stevcwre to store the nodes of & 8. "Show how the fo} be Storee using your noc +(e. aCe ypeoxad 12 souasajes ava uy sueqgosd Rone dun ayia (ext) (3) | se1e9 nok pe 09 setdwexe oydeys asn ‘worazetTo> Saya yo eostyd sua ATTeMIOsUy eqpazeeg (SxeH ST) C2) raya Fo ue Suyureys Teysoaxe aaeredss ( oe Tbuyuzeyad aesuy: Te 'parpuew sae euove¥rto3 t-o)keaze -ergea sea stars yeey ous ur seven ces ‘ue cy eae te ze Ut —azassaer 30 socantes ous ax035 of {1 pow Aeye(Aexiw UOTSSURZ eeu aut 8mn sorasen “5 vorsyrd oery Azeurg popeorys e 52 (8) uy ) uy asnsonsse pod ous duyen (oxzew 9) pax Azeurg pepeenn © ausmetduy 3 pesn ug uo yotun sansoniae Spou e onto. (sazea By esy sys 303 (esseaera repseasod oy UNOp 2aTIH essonesy ropsoa2d pur + sou doOoGoD Tesseness sepsduy-eey oan Aseura v (e408 Ov) porn Leute “+ 20) papuene si yumm g Wf pur “yee. uw {= tab suansve 1981200 spare ¢ 18 suansue y2023 ein sou aseatg “y009 U6) Bo gormpa re © sass 22.00 spscrzpangis wortte O41 tue FR woxy pur “35 eatin 8 “aenpaaard 1 03 pouzsu —- ua uretdea (@) (49 vrs: iq iEsor presy apssu xeSvoy ou ey pzo9e7 © vous sadepgy causes 2979p powsea! aunos souazeze2 ‘aud mou wyeTaey (8) [45] een auezeStuee KromK / “berusey, Youssouaud sya uTeTess (Py ts) S27 eazy aueexorn sua ssop uous 2 aazerxotab 20) so} 4 sed asz0n pur ebexeAe ous oT seus ee) INS) sretpen, sofen oun bursa) soreers//2) of 4 : fentattee ay vera aur = 265-250 09 de aon 4 so sees L2eurg buInoTtoy 943 zepTevey A © o8eq

Вам также может понравиться