Download as pdf
Download as pdf
You are on page 1of 24
J CSc Do4 Guagions Bonny Phototepy Gs 826 bh UNIVERSITY OF BUEA FACULTY OF SCIENCE FIRST SEMESTER EXAMINATION 2020/2021 DEPTARTNENT: COMPUTER SCIENCE [COURSE INSTRUCTOR(S): Denis Naweteyim Nyanga Beran MONTHIVEAR: Februaryi2021 DATE: 03/02/2021, [COURSE CODE: CSC 301 TINE ALLOWED: 2 Hours (13:00-15:00) [CREDIT VALUE: 6 = cover page of your answer booklet. SECTION A: Answer 2 Questions Question 1: (4 + [343] + [445] = 19 marks) (@) Given the S-line code fragment below, line of code is executed. Do INSTRUCTIONS: All programs and ilustrations should iiustration assume a C pi questions, Start each question on a NEW page! Indicate the quest COURSE TITLE: Data Structures & Algorithms [VENUE: CRB I-100B/CR8 WSOC Z rogramming environment. Aerpt all tions you have attempted on the front this Section complete the table by writing the contents of the varsbles as each notleave any cells blanki.use (Line|Code fevjezyeno al the question mark (2) to Tnitial state of variables |? |? |? |? denote that the value in the av c2-= ‘B', tmp:|* | > 2 corresponding variable is not 2 ¥q.e BC2; known. 3 [imp = "ik EF 4 ; At: & 5 (b) Given the following global declarations: ‘struct Time! {| typedef struct { int hour; int hour; int minut int minute; int second; int second; ort } Time2; | @ @) (9 Incase (A), declare simple variable t1_s and pointe variable 12D» and assiga the time 13:05:35 (i () Assume that a linked lists used to store tims fa struct as illustrated in (), and a pointer field been set co NULL. linked lst. ‘Also assume that you have ‘minutes and thiry five seconds after 13 hours) to the variables. (a Incase (B), declare simple variable t2_s and pointer varisle 2M, and assign the time 13: (Ge, S minutes and tity five seconds after 13 hours) tothe variables 5:35 formation, with each node comprising the data stored in next. The next field on the last node has zlready ‘a poiner head that currently points tothe star of the ave (You want to create anew node to represent the List the Hl list and insert the data held in you ward p in this new node, and its | CK ie UNIVERSITY OF BUEA FACULTY OF SCIENCE FIRST SEMESTER EXAMINATION 2019/2020 DEPTARTMENT. COMPUTER SCIENCE [COURSE INSTRUCTOR(S): Denis Neweteyim [MONTH/YEAR: February/2020 [COURSE CODE: CSC 01 DATE: 20/02/2020 [COURSE TITLE, Data Structures & Algorithms TIME ALLOWED: 2 Hours (18100-1600) [CREDIT VALUE: 6 INSTRUCTIONS: Al programe and illustrations should assume a C programing envirenment. Anewer Questions ‘One, Two, ané one other question, Start each question on a NEW page! Indicate the questions you have attempted on the front covor page of your answer booklet. All program code should be in C. Question 1 (Compulsory): Multiple Choice (20 marks) Write in your answer booklet, the LETTER (A, B, C, or D) that corresponds to the best answer from the four that are sven below each statement. {uesions (0) are relted to array numbers depicted below andthe cove agent its ‘hespalingsoftecambers one tosiandthe Garter a index posens oy and31 ear OL 56 78 9 10.11 12 13 14 15 16 17 18 19 20 21 22 23.24 Oper numbers{25], (OTNTETIWIONOTTMTRIE Te TF To TUR [OIF PVE WWIs [i fx Jeneep=manbess7, | ‘What alt wlth anton srlen(wumbers) produce (ncton len) retuns th leg of estring)? Ree By ca Da 1) Wat yale the ton strlen +) produce?_ A3. Ba GIS DNoteef tie above 6) What outa wil result om the statement prints") A. The aray is interspersed with a ‘A THREEFOUR FIVE SIX B THREEFOUR FIVE THRE" FOUR D oNETWo Given the code agment onthe ight: camT 4) What value isstored in y? fine aE) = 2, 4, 8, 5, 24 495 Ad BO C6 D4 int “ptr, ye: 9 wi tf statements exec peent ts }) What willbe printed when printQ statement i executed? Bee cccueges: ayo) Axo Bact printe(ate"s2)2 C x2 DThereisa syntax err inthe coe, sonothing wll print |p 4) What faneion shoud be use to release dynamically allocated memery that Ibnolonge: needed? Aunaliog) ——-Bedealloc)— Crees) fee) * 8) Which ofthe following is NOT a requirement fora recursive function? ‘A. thas at least one recursive ease B Any base case approaches a recursive case C_Ithasat least one base case D_ Any recursive ease approaches a base case : bh) Which isa true statement given the function en the right? Sa | nt aye ‘A. The function has no recursive case He (0) B The fonction has no base ease return 0; (©The function may not terminate due to infinite tration > D_ The function may not terminate due to infinite recursion else ( 1) Considers que @ and empty ac. nally Q has items A,B, Cand Din hat order, a’ |, FORE foRCa*N) Being the ont je Ifyou perform the following operations Soqentaly, wat willbe the final configuration of queue Q? Operations area allows be 1h Remove the ist tte tems from queue Q and push them in sack S 2 Pop each tem from stack Sand insert it ato queue Q. (A) DABC (D being the fort item) (@®)ABCD (A beng the ert item) (©)DCAB D beng te ent item) ()DCBA being the font ism) 4) Suppose tha ems A,B, Cand D are pushed, in that ower, oto an ntl empty stack Sis then popped thre times; as cach items popped of, itis inserted nto an nally empty qve, Iwo Kem are then removed fem the gucae, wha is the next tem that wil be removed fom the queue? 4) item A ‘@)item B (©iteac (item D ) What king of inked lst begins with aponter tothe first nods, and each node contains a pointer to the next node, and the poiatr nthe last noe pons back to the ist nods? (A) Circa, singly linked list (®) Gis, doubly-tinksd fst {© Singhs tix (©) Deabyinkes ist 1) What werd is usd a describe a node ina tee that has no chile? i ACh. B= Interior Co Leafs? D" Roor : higher -— ‘auth ce onthe ight, and gifen dt the level of anode is one hig in he level ofthe node's parent, withthe root node at level 0. The ‘es depict intemal nodes, and the squares external nodes. ) What is thepat length of the tres? a 2 Bot © se Dp ‘What isthe internal path length ofthe re a) sc 7 pg ‘What isthe extemal pat length ofthe tee? A wR Te 6 Das sume that en agent l (x algorithm) needs to mavers the graph onthe ah Alco assume thst Scinmatemeaidnattewadmonte [ GG) | ‘sisted esate ee ae ae ) Matisteadeofegminattentenen epee ’ hfs search, starting a Node O? 2 43S Bo 2 6 3 1 6 4 Do 3 4a oY & 2D Wists order of expansion ofthe nodes in brenda search stating atNode 0 aol <5 6 Bors e415 C02 s 34 6 4 D023 4 534 9 What isthe engt ofthe path 0.3.6-47 Az? Bo 4c 3. pg > "eg gy est eights ined bya ert aver hs il ese ed A 94171612116 B 9i76aisz2i2 © 69174162212 D 61794221612 9 Wiis of lowing set algoithms work by fndg the sal lant rey and ee geens tt lent inthe Si pein ten ener sna oe exchanging wid, ‘he elemert inthe second : ‘Ay Bubblesert B Selon srt © Shall sort ‘Quetlon 2 (Compaen) [34343] +4 + [25125] 2 +2 5¥25]625 snark) typedet struct node “Link; QQ ® = ¥ Aa Line bea = headd = malLoc(atcaot(etisk)); hoedi <> noxt = head? > next «hone, (@) @) ts) eunl(2, headi); newsa(2, needa) RewN(7, head); new2(7, head2); | BeuN(S, hendi); newa(s, neaday, | steniaton ofthe graph bore | sewa(2h, heeds memeeesee head?) ; Rew(12, headl; newi2(2, heads), Void neui(int item, Link’ hy ¢ (2) Give tee diferent re en) () asasetof vertex pairs, wy, Where wis asouree and va destination vertex. angen) me eats ee Soetit te © Tekan te ihispssetaponin ‘used to process linked lists, Sketch the two linked lists | void newta (int item, Link t) { | "5 ae s Link tap = neltoc(aizcotttap)); | np => date = test t= “> next = min, tee next = tape to emp Using the same linked fist node — - definition in (b) above, assume | void my_tonei ink my that you create a linked list with patter tet) rotveny infoingnambe os digs | PENA M8 hd 45,3, 8,6 stored in that order, - 5 with atthe head ofthe lst. The Toca ume 8 my_fune20 below, cach takes an argument tht pont tothe head a the ox Write {hecuiptyou wold get from the functions my_funeH( and my. Tane2), (Rear ihe code forthe node of linked lis (ie, theft five lines ofthe code above) this tie o representa node ina binary tre, Underline the changes or additions you make (©) Assume an initially empty stack), implemented as an ay. (i) Sketch the resulting stack after the following operations, array indices, and relevant pointer(s): Push(S, 20); push(s, 40) ;push(s, 25); = NULL) et, y_fne2( printe("ta in the order given, clearly indicating its contents, Push (S,-5);push(S, 60) ; i Sketch the stack that results after the following i operations are applier' ‘othe stac indicating its contents, array indices, and relevant pointer(s): pop) ), PoP: Question, (15} + 4+ (2.542.5]+ (34444) = 25 marks) @ For each ofthe following scenarios choose the “best” data structure, or the follewing list: an unsorted array, linked list, doubly linked list, ei k in (i) above, clearly Combination of data structures, from linked list, staek, queue. In each case, usity your answer briefly. (] "Suppose tha a ior desided tht customers who come fst willbe served fst G_Alstmust be maintained so that any element can be accessed rarniomly ii) program needs to remember operations it (iv) The size ofa data file is unknown. The enti ‘ome in. Entries must be deleted when they. ‘memory management (9) Alist must be maintained so that elements can be added anywhere, directions. The same amount of effort is required to move from the firs node to the last node, as from the last node to the first node, (©) Given the following declaration: int *ajL0}, write a for loop that ‘converts aay a toa 10 % § matrix ©) Consider the recursive function on theright. Work out the output given by: @foo(I7,3) Gi foo, 9) Performed in opposite order inthe file need to be entered in the data structure as they are no longer needed, It is important that structure has flexible ‘The list can be traversed in both SE (atb == 0) return by veturn f0o(b, etb); (©) Answer the following questions relating to hashing (0 Reda the table and previde ash values fash fc 3]54]09]74[i8 19) function hI) eon 74 i) Consider a hash table with ten slots. For the hash h(x) =x mod 10 | function hi(x), insert the keys (33, $4, 69, 74, 18, 19) (in the order given) into the table using the following approaches for collision resolution Ciel) separate chaining, and Gi-2)linear probing. Public tne footint «, int 5) «| Question 4 (343] + [243] + [2+2] + [445] = 28 marks) (6) Assay 8: 23,5,711,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97 Given the binary search funetion on the right, and a sorted eray a above, that contains the prime numbers fiom 21097 inorder, () Skeich wo or more arrays that illustrate the various ‘Phases thatthe binary search algorithm goes through ‘when asearch in made for the key 67 in array a (i) Sketch two or more arrays that illustrate the various phases tht the binary search algorithm goes through ‘when a search in made for the key 12 in aay a, [Note: Each sketched array in () and (i) above should clearly itastrate| > the following: the aray contents, the aray indices, and the perameiersvariables left, mid, right. Assume thatthe parameters that ‘are passed tothe function are respectively array a the key, andthe left and right indices ofthe array. (©) Show (write) the pre-order, in-order, and post-order traversal ofthe binary tree on the right. fine wearch(ine af eint Bey int mids bile (right >= left) 4 ey mid = (left + right)/27 if Qioy == amid) return mid; 4€ (key < almid]) right = mid — 2) clee left = mid + 17 ) return “1; (©) Draw the binary search trees that result from the following inputs as data: ()$3491278620 Gi) 59367841220 (@ Answer the following questions in relation to the programa the right. @ Wee te output you would get when the rogramn the right i un. (Gi) Write function fact_rQ, a recursive version of function factorial() in (c) above. Sne nai iat 8 1 d ant factorial (ie) Printe(*n = ta\nr,n); Prints (*Satsta\aryn,*! = *, factorial (a)): Prints tn = sd\omra 7 Ant Factorial (int in) ( int fact = 1 print£ (a = Qa\n"sn) walle (n> 0) | printe Printe ttn = Se\aten) (void) | 3: = Aalnts nd ersity of Bucs Student Name 301 - Data Structures & Algorithms — Student UB Numbers t, 11 Jan 2019 (90 minutes) Student Department Attempt oll questions for a meximum ef 20 morks rower Grid for Question () = 6) ‘question 1: MCQ (14 marks) a) [toy] ] co] red [co] oafeo [wi va [oy [ima]eor] inthe grié proviedentherigh, check (x) the letter thot [a [A ]@R[A [A |A DK DR [A [A IR [A [a [A Srreapods 10 the best answer from the list of options ae Ce aectite qustns (Hele: Cech oe open ony, Pale (e [& [2 [2 (2 [0 [8 [0 WORRIK [Bt tnd mark your erewer clerly) le fe [ele le |e fixie [Xe > [0 |m]o [0 |se[0 [> [o fe [x (6) Gwen the code fragment in Figure 1 fine waingy Wht vlueis stored iny? foe wo Or as (ye | Pern et Se y = ptraxti; 2 = x[0) - ‘ptr (©) Whot willbe printed when printf statement is executed? | print £(~z-¢d", 2); a 0 @x @re ors [)__ Fiseet Questions (0) to (c) re related to crrcy munbere depicted below end the code fragment below it.The ary is interspersed with the spelings of the nunbers one to sx end the character "NOt index positions 6,16, and 2 of the erey o123456789 OUR % 7 BY 2 a 2 2 OWE WOMrmrelelelrlole lol: vie lols: x char numbers{25} char *p = nunbers+7: (©) Whot volte will the function strlenfrumbers) produce Function strlen() returns the length of string)? (aye ()7 (C24 (O)25 (fh Whar vo Whe fnction stolen» 6) rode? rl (4 9 (op 12 (0) Who ug i ce fram the sttemen prinfRe 9? @ TReEroUR FIVE SIX —@)FIVE. «== THREEFOUR __@JONETWO Grothe clement Figs onrrthenst oust, [PE SRR RTC (What the upto the fs print fertion cl ' amy @ couruTee — (OM (oyaveoneuren [EDEN & (6) Wha isthe output of the second printf uretion el a ae (A) OMPUTER (eye (o (©)COMPUTER ) pene ‘e ) myFunc(x+4)) 7 {h) Ingeneral inked lists alow (A) Insections ond removels (8) Trsertions and —_(C) Insertions at the back (0) None of the above cated remevels only at one end ond removals from the front (i) Sey youhave the flloning declaration: char "x: What best describes what xis pointing te? (A) cherocter (8) errey of characters. (€) string __(D)orray of pointers that point to pan osc 91 -Frsts Semester 2018 2020 - (How mary poivers are con ri Ae de reule, doubly linked list of integers uit, onsh tcined es data members in the nodes of o cir ly we (five nodes? = 5 st oe @s ov oH a ©) What ki of linked lis: begins with a pointer tothe first node, end each nade contains a pointes wert, Age "ede, end te pointer in the last node points back to the first nade? (A) Gireuta, sing linked lst (@) circular, doubhy-lirked — (C) Singly-linked ist (D) Doubly-linked list ist (© Assume the flowing vrioble declaration: int Fee =O: int *ptr = Foe; Which of the following ctotements will change the value of Foo to 1? ()ptrse: @ Foor; (3) C Foo): 4) Cpteder (A) Land 2 onty (8) Land 4 only (0) 2nd 4 only (©) 3.and 4 only Consider the code in Figures 3 and 4 ine 7B void nystery Gat a, int By int whofnows = a: int natn (void) { int main(void) { inex = 183 ine x= 18; ant y = 3; Ant y= 33 9. mystery tex, ey}; mystery (Gx, ty) 20. prante ("a = ta oor pe wet prince m= a, wy S Feimcetsy 2 03 ine oy = Ad," fa: Een 0% feo op 3 ' Figure 3 Figure 4 (3) Wht des the program in Figure 3 produce? (A) The code runs with the following output: x = 18 y = 3 (©) The cede runs with the following output: x = 3 y = 18 (©) The code cannot compile (©) The cade compiles, but there is @ run time error (hn) What does the pregram in Figure 4 produce? (4) The code runs with the folloing cutput: x = 18 y = 3 (@) The code runs with the following output: x = 3 y = 18 (©) The code connot compile (©) The code compiles, but there iso run time error uM CSC 32 Fists Semestéy 2019-2020 - > Jnlversity of Buea ( fSC 301 - Data Structures & Algorithms ‘Test, 11 Jan 2020 (90 minutes) Que: ion 2 (1+3+2+2 = 8 mrks) Student Name Student UB Number,___ Student Department QI. Given the program below, with line numbers included for convenience: (©) Write the output you get from Lines 21-23 (©) Write! the values ef acrray{) after ‘the for lop is executed (ie, Lines 24 ond 25) ait [eat [avr [amp [ara Alzl[ayr|e semi [eame_ [asp atlas als [A [mln ES er 4a [af] | is |e jason [splot [aaraniT [aaragie] [aaa He [14 [a0 [al static int 10; print (Msta\ne, i); return {447 Yoid printhede {node *n) { Sn for (epi peineeinid *, PEintE("te\n", me); void main{vold) ( node ay by "Pz ine sy a char ‘univ ~ vauea Uxverasty*; Print£i"tS.3£ 45.36 S3E\n", (float) (Sloat) (6.0/5.0), ‘ieat) (9/5-0)) print: valiant, * (univ?) univ Hor (Sel, 300; i<20; 4042, Je8) 8.azray(}}=L+£00() beat atowaty pice! a.array(2)5; “b.array(3}~9: | p-oareay[f]-17; rintNods(6a); printiode ( eintivode(p)! , (@)_ Using the sketches below representing variables a and b, insert the ‘ond ¢ after the code in Lines 26 and 27 are executed i contents of the fields called array Variables Venable’ 3 oP Eee ep Pi a eae (4) Write the output you get when the statements Ua St 301 - ds Semester 2019°2020 ine 28 ore executed yr. : ag Shae st (E1204. Bate) rene, Hanae of f08 ia” i artion_weight; //weight in grany’” On ye! rons TNE on he nt ised wnt ety | ie orelon inte; “Pecan in Satetigs| en int alo i @ } What isthe 19 name of this structure? )--— —~I< T > a a Ney A Sree ned tenor idem SheMet ferll| cong Ty rs or eg eee contcis 200 colries. Write the stotement yu would rit 1 sin values tothe ‘free menbers of meal] torepresert such opie? (©) Complete the ede frag ! reheat conte entrees ina ed affine dens, aig ‘tat trey n(b) cbove hasbeen declared onlpopated i i There*/ for (40; 5: s c ‘(Mosse cKie to Soapate and display calories neret/ ‘Assume the inked lst below, with each node having date type Node head : INGE “Gaia net Write the statements to insert o new node, write the whole method, but just a few 5 OLN'CSC 301 -Fests Sémesier 2019-2030, jim? betwen the node with the 5 and the node with the 1, Do not Tatemients to make the conne lection, oe ee / oa 302 - Data Structures & AIG J, 22 Jan 2018 (90 minutes) 0 marks il foe Qoestins (2) -(0) [es] eae) [en [rod em] fn] 0979 [tm [a To. Bla fe [A KIA TAIA [AIA » fe, [|e |B |B |B pe |B x, Kc Iclele fel [clele ic [ix |e [elele ob & be Ixlo I © [pol Attempt all questions for ¢ moximum of 3¢ 1 (13 marks) hat cecresponds 10 4 sptions given forthe questions (a)~ (i) Note: Check ene option onty) psi teeth 1) Cle be By By be OF #3 @o C6 Os eae )Whet ill be prise spt = a1): | (x0) @)xt 2 ae (Ox? 0) Thereisesyntoxerror inthe code ond so |, PNET rales D2 7B er renters dpa cd reet aoe 8 Th re ae eee ae terre osian te che Wo exporting 6162 S$c-Fal f the erry. 612345678 9 1M 213 1415 6 17 16 19 20.21 22 23 24 OIE Ir wlo holt HR Te le Ir Jo Ju Je holr Ir Jv Je fiols Tr Ix] charrsabersi25p " char *p = ranberst7: ) What value wi the furction strlen(numbers) produce (function strlenQ) returns the length of a string)? ws @7 24 (D)25 ) What vel will the function stlen(p + 6) produce? 5 4 O13 (O)Noneof the above | What eutput will result from the statement printf ("%i"p)? (A) THREEFOUR FIVE SIX (8) THREEFOUR FIVE (€) THREEFOUR —(D) ONETWO. [ohare myFunc(ohar *pee) return (pe) Hine maine)’ ¢ iven the code fragment in Figure 2, answer the next two questions ‘What is the output of the first printf( function call (A) STRING (6) RING (©) ING (0) NG What is the output of the second print function eall? (A) STRING (8) RINS = (C) ING (0) NG V- Phatoco fy ‘igure 2 . wy In genera, inked list elon: <= (A) Insertions end removals anywhere (8) Insertions end reriovals only at one end Gaara rancher Sere ey ‘Sy you have the followin declaration: char **x; What best describes what x s pointing to? character (B)erray of characters. (C)string (0) array of pointers that point to arrays of characters NSC 201 istssumesser 2014-2015 -chib : : i B c p Tena Tine (fs eek Tine | [rtructs Tine 1 Sint hoor, | [int ors || ane hors 1 {ne minocer | int minite, | sme moter | int minotes : ' u (4) Suppose that items A, B, Cand B ere pushed, in that eder, ante an intially empty stack S. S ig shen popped ‘three times: as each item is popped off, itis inser -d int » an initially enipty queue. If two itens are then removed from the queue, what is the next item tha’ will b . removed from the queue? ap (A)iten 4 @)items (iter ¢ ©yitend — f () Consider a queue Q and empty stack S. Titielly Q hae item, If you perform the fellowin Operations are as follows: tems A, 6, C and D in that order, “A’ beitg the front 19 operations seque, tally what will be the final configuration »f ques Q? Ao Ale 1. Remove the first three items from queue Q nd yesh tnem insteckS 2. Pop cach item from stack S ond insert it int) que Q. ie (A) DABC (0 being the front item) (©) A8CD| A being the front item) f (C)DCAB (© being the Frnt item) {©)0CBA (being the front item) 4 NG) structs are not allowed ta contain . Ob poisters to structs of differeht types @) struct sribles ofthe some type (pointers to themselves (0) both floats end ints, 1 (0 By default, structs are passed to functions (B) callby-value @)callby-reforence (©) struct res connot be paszed between func ons rent cte nig ont [i= void aystery (int va,, Int +b) 1 (@onemember at « time i eases Gee eo jz: “ist ehotincus = +0 2 “ine ehotiows say) ne)! aS . ochr 3B Moxon: Ss ocr s 7. int i iM int x ap ei ae lb) Gy Figure 4 Figure 3 a does the progrein in Figure 3 produce? "® (A) The code runs with the following output: x © 18 = 3 p(B) The code runs with the fellowing output: x = 3 y = 18 2 (© Thecade camet compile * (0) The code compiles, but there is a run time error lin) What does tne program in Figure 4 produce? rc (A) The code runs with the following output: x 218 = 3 (G) The cade runs with the fllowingcutput:x = 3 y = 18 (9 Theeade cannot conpile (©) The code compiles, but there is @ run time error ‘Gu CSC 301 - Fists Semester 2014-2015 - CX IH peje fainat fake rut is e it € ———————— hordes ore 18 me \y Given the program below, with (@ Write the o [eos sya atl sse () Write the cathe you ect, er loops oan te (©) Using the sketches representing variables ¢ and b, i ‘contents of the fields called ermay end € efter the code in Lines 26 ani oui 3s afr you gt from ine ‘numbers included: » cor venience: (1+2+2+2 = 7 mrks) ie is. Tindivd typed t t foci) { ‘gtatic int: 490; 5 iar erie ih thea es Vola grin ote) | nade, by ink 3,3 char ten PHELE" 5.36 U5.3E US.3e\n", (EL0st) (8/5), rray(d]o1 rintiode(p)s rintitode (4b); 3 25 ere Ko Verigble Veriabie b 2 e\K Js ove |? 1# B73 [eT +5 [Ie 6 SLs j (@) Write the output you get oz 9 b= 9 next printe(*td *yhe>d , typedef struct node stinky Nite ee “igs int data; is fonsmy. func () and {© These shove et) shows the defn of node o's inked lst. The fuetionsmy. void my_funcl (Link h) { Lf (hr== NULL) xeturn| prinef("td " he>data) Link next; h to a) ( detorn; lata), une? () each take an argument that points tothe head of thelist. Assume that ee ae z i! = rated with the numbers 4, 5, 3, 8, 6 stored in that order, with 4 stored in the head node. ‘put you would ge fommy_tunci (} andmy_tune2() @ Rewrite the code A J fei node of inked Fist otis tine repeset anode in binary tee, Underine the changes ‘r adkitions you make, ©) White funtion cated averse that takes potest the root of binary tre, and traverses the tee post ‘Question 2 (34343) + (343) ema typedef struct node *Link; struct node {+ int dataz ink next; Mm Link head) = head? = na: headl -> next = hoad: Rewil(2; Béwal); new2(2, head2); RowN(7, headly; newti2(7, head2), Moe stz00e +n Rewn(S, headi); nevi2(5, head2};, Reuti(20, headl); newti2(20, heads); © Give tee diffrent representtions of he raph above Rewti(12, headl; newti2(12, ‘heada)y (et). \ Wold newt(int item, Link hy ¢ (© Beet of vertex pais u-, where wis a some Link tmp = malloc sizeoe(step)); and va destination vertex. tmp -> data = iten; | (ides an adjeceney matrix tmp => next = hy Gi wing aceney Hts Be tp; ) © Teese fragment onthergh is ptotaprogan | fota newii2(int ten, Link t) ¢ tg OSs linked Hiss, Sketch hetwe inked ts | tink tote alloc (size0t(+tnp) ); deters deente coders. In cach tit you | tap => data a Teel ‘fold clearly identify the head the nodes and oe or. at, and the inks, Question 3(6+3+6 =15 marks) (@) _Bxplin the fo lowing with respest o hash bes (hashtable (i) hash funetion; i) clision ©) Reda the abs snd provid hash values for ish functions h(x) and 12(4). © nitrteh ate {0 separate chaining Gime atte ect f( te slots, Fer the hash function hI), inet the Ks (23, 54,6, 41,19) ble unng he eowi ppronhesfrccison eff 54 7415, 19) ee order. sk) ); 2 > next = wut; ite a ull ee ; e Sesesse saan A «erfortn a depth-first traversal of the graph show ahele, stating wih vertex Cas bee Start with vertex C 10 Use a stack to store exps is Visited Select the smallest edge first w vbed nodes as each node appropriate List the vertices in the order in wh i hich they ere vi 7 , Wo na brendft reves af the graph in (a, tring sertex Ce follove: aie Stet with vertex C Use aquese sstion§ (242) + 24} + (Rank the following tee code fragments (whic produce the seme resus), in order of increasing efficiency. Explinyeerresiag 2 fine Sy 4, tp, one = 07 oak = OF leer (i 0; dc Oy deed sort < 10; asp 2 tet tap» . 2100; Seer 100; 344) for (5 = 0) 3 < 20033909 ‘emp © 5; entiey entre: | intl ("4 tele tenes ent nce (red Gale “rtp, cata: | forinesinte tain seme) entds | ‘ a : @ Ranke f functions according to thei growth, from: slowes 3n,5n°, 2, 82), 1, 62)n, 20° 9G) Redraw tie table below (eft) and compete it by plcing a cross (X) i the cll that corresponds tothe growth that best characterizes each ofthe given functions (nis the problem size). ing to fastest growing: [Consent [Linear [Polynomial | Exponential 30 kf) 3a? as running time Gy 7 [1000 1 (3/2)0 | _ an (Gi) Reda the graph above (sight) and provide appropriate labels forthe horizontal and vertical axes, and the point of intersection ofthe dotted line withthe horizontal axis. Then write ONE or TWO conviee cor ‘hat expin() th compleity(bg-O) ofthe function that depicts the ruing tae ofa lgort (Determine the best, worst and average ease completes of squat seach onan unsorted aay it searl it (Le, the emt searched fois found.) & UNIVERSITY OF BUEA oe Po FACULTY OF SCIENCE END-OF-SEMESTER EXAMINATION ; ; eS NOMRIMENT_ Compute Scien ‘COURSE INSTRUCTOR(S);__Dr. Denis Nhowete ‘ | Monru: Samar Scionee Neat = : aaa 20 Tine = COURSE TITLE:, 05 TIME ALLOWED Tian SE Se ‘CREDIT VALUE: 'NSTRUCTIONS: ed rogh EAC quan bey at weer Al opi Sle al cole Fags aed, "0 1,2 and ONE other question, Ifyou aver ll four questions, only Queton 1, 2 and 3 will bc ded, Wilh fhe following it NOT a requirement fer a reese funetion? A Ithasat least one recursive esse B Any base case approaches a recursive case © Iehas atleast one base case D_ Any recursive case approaches a base case ) Which of the following is NOT true A and consumes additional ‘function that call itself Which isa tue statement piven the 3 memery fine fuatine aye Se (ose fenton on the ight? saturn of A Thefinetin has no recursive ca » B Thetinction ha no base cnee tase ¢ §, Tes finetion may nt teint due to inition D The funetion ay not terminate due to infinite recursion 8) ‘The binary search tree shown on the Return fun(ait); , 453491278620 B 59376841229 © 59786122034 D 39367841220 ©) Given the sketch ofthe linked list on the right withthe and the left pointing links called left, refer to thethird node in the list? A panext. B © piprev.next, ht pointing links called next Which ofthe following expressions docs nor Aenext.next D nnoxt.next.prev.next 1) Mthe binary tres below sprinted by a reorder esvesal, what wl A 941716 2116 B 9176416210 © 69174162212 D 61794221612 the Fest be? 8 fappese Gt items A,B,C, D and ae pushed, nt ode, ont an {hen popped four kms; as ach item is popped off tis insercd ine Hy empty stack S. § ig (poulsmsarthen removed fom the queue, wit isthe next em tet ally empty queue. Ir beremoved from the cc Db az ow ucue? AA BB AX ROY SUcE thst an agent (oF algorithm) needs to trav eda drastcst men terete tote fei a [ict he lowest numeric value. Answer Question (h) fo) below. the order of expansion of then: ) is 6 5 i 6 D i k) ed to desoribs ¢ nods ins tee that has no chi Tecerier Leaf D Root » ity of tn elpovthm ie O(1). Suppose tit the progrem that uses the algorithm uns in 10 seconds for« date set of size n. Ifthe ¢: is doubled, how long wil! ito" (epproximately) to run the program? A Wseconds BB ) 10Dscconds _ (0) Implementation fledistaneee Hinetode "point sh" float distance(point a, point b) float Gx'= 8.x ~ Dt, AY = Gy ~ Duy ent intertoce and implementation cole above righ, | fet salae + det ay + os sectively for defining a point in 2-D space using Cartesian dinates and for computing the distance between two points on 2-D space: \Writea code fragment that declares two variables pl and p2 as ponies oa point in 2-D space, and one variable to hold the distance between any two points in2-D space. p1 and p2 should hold the addresses ofthe points (3, 5) and (5, 10) in2-D space, The code should then compute and assign the distance between the two points to varabled. ‘Now assume that you want to extend your code to handle polar coordinates as well. Define a user-defined type point Polar as astruct with members rand thet ha, both of type float representing the poloar coordinates of point. ‘Then write funtion called polar that takes two parameters (cartesian coordinates x and y), and computes and retas the caesponding polar coordimatss Assume tat r=Vx+y? and theta =arvtan(?/) Alo assume ‘thatthe math library supports functions sqrt and atan2 with prototypes: double sqrt (double x); and double atan2 (double y, double x); forsquareroct and arctan respectively. int fun(ine i ity) ) What does the fnction on the right calelat? Hint: use two integers (ay danas} MOY == OVC ‘for x and y respectively) to arrive at your answer. reniee ae Eoturn (x + fonts, ¥7 2 b | ) What values retumed from the function given onthe ht piven the cll int Fantiat sant y) ‘fan (4, 3)? Note: Show the series of recursive calls and returned values. | if (x == 0) return yj : | Foturn fun( 2 i) Redraw tetree on the right and Ibel each node with its level ‘Computethe path length ofthe tree iil) Which node(s)isare) the sibing(s) of E? yas 1647 = 20 marks) ive the best Big-Oh characterization for each of ie Gime estates (Mis the size ofthe inp presen) re renin lng (). togln) + 100008 i Gi, nlon(a) + 152+ 0.00020 Gi 378 Fnlogkn) + 5690 fogsn) Gu) 1000a + 16n+ 2 GDF DH TEED i 0 bo insetted: 15 17 8 23 3 5. 1g hash tables when the keys of tize 7, end the following end (i & breadibefirst f1 i of the right, in each ease ‘the smallest edge first wh the vertices in the order traversal of the graph sho stasting with vertex C. Seles ‘appropriate. In exch caso, which they are visited. 20 7 as C3 E D ve Juestion 4G 45454346 =20 mets) In (@) axe @) betows that ere ral rasan popen iter off the stock: 8) Given the sequence: EAS*Y*QUE' **ST**I0 the sequence of values returned by the pop ‘Sperations when this sequence of operations ie performed on ar inally empty LIFO stack by Sea cat ay to inser eters nthe sequence BASY so thet the sequence of values retumed by the pop operations pr9% fe stee’y c letter means pus the letter onto the stack and an asterisk is: * (EASY GDYSAE Gi) ASYE (Ww) AYES; ein each instanceprove that no such sequence exis «) Inthis exemple that is related to prozessing a queue, a letter means enguewe th the queue and an asterish TRcens dequewe en item off te queue. Given the sequence: BAS*Y*QUE***ST**#10¢N**, determine the sequence reece euumed by the degisue opecations when this sequence of operations is performed on an initially empty FIFO quewe. Assume a deta sructere dog's to which dat can be added end removed beth at the front and the back. An uppe eee letter means put the leter et the beginning, a lowercase letter means pus the letter at the end, a plus sign mean igetfrom the beginning, and an asterisk means ge from the end in te following sequence: BASHY+QUE*stHHO"ni* ‘Determine the sequence of values returned by the get operations when this sequence of operations is performed on at initially empty deque. 1) Using the tonventions in (2) shove, give a vay to inset plus signs and asterisks in the Sequence EasY so that th sequence of values retumed by the get operations is: | @EsaY (i) Yas ‘aYSE (iv) asYE; onjn eqhh instance,prove that no such sequence exists.

You might also like