You are on page 1of 14

Solutions to Chapter One Questions 1.

___________ is the process of executing a correct program on data sets and measuring the time and space it takes to compute the results? Ans. Profiling 2. Define algorithm? What are its properties? Ans. An algorithm is a set of instructions that provide step-by-step specifications to perform a task. The properties of an algorithm are

Input !pecifies the data set that is applied to the algorithm to check its validity. Output !pecifies the data set that is produced as a result of the algorithm execution. Definiteness !pecifies that the instructions described in the algorithm should be "ell defined and should not create any ambiguity. Termination !pecifies that the instructions described in the algorithm must contain a proper termination condition. Effectiveness !pecifies that the algorithm take less time and less memory space during its execution.

. What is debugging and "hat is profiling? Ans. Debugging is the process of identifying and fixing the errors in a program. #rrors in a program can be identified by executing the program "ith a sample dataset. $rofiling is the process of measuring the performance of the program by executing it on different data sets. $erformance of a program is measured by recording the time and memory space that the program takes during its execution. !. %ne of the properties of an algorithm is beauty &true'false( Ans. "alse

Solutions to Chapter T#o Questions 1. )ive at least * real life examples "here "e use stack operations. Ans. The real life examples of stacks are

$angles in a han% The bangles "ore in a hand follo" last-in-first-out &+,-%( strategy of stack. The bangle that you "ear first is the last one to be taken out "hile removing all the bangles from the hand. The bangle that is "orn last is the first one to be taken out. Same circumference circular rings in a pole The rings having same circumference placed into a pole also follo" +,-% strategy. The topmost ring. "hich "as the last to be placed in the pole. is the first one to be taken out. Sac&s full of #heat place% one over other The sack at the top is removed first and the sack at the bottom is removed last. The 'olts scre#e% to a single nut When the bolts are scre"ed to a single nut. the last scre"ed bolt is unscre"ed first and the bolt that "as scre"ed first is unscre"ed in the last. $atter( cells in a torch The battery cells in a torch also follo" the same +,-% strategy of stack.

2. )ive at least * real life examples "here /ueue is used. Ans. 0eal life examples of /ueue are

A )ueue of people at tic&et*#in%o# The person "ho comes first gets the ticket first. The person "ho is coming last is getting the tickets in last. Therefore. it follo"s first-in-first-out &-,-%( strategy of /ueue. +ehicles on toll*ta, 'ri%ge The vehicle that comes first to the toll tax booth leaves the booth first. The vehicle that comes last leaves last. Therefore. it follo"s first-in-first-out &-,-%( strategy of /ueue. Phone ans#ering s(stem The person "ho calls first gets a response first from the phone ans"ering system. The person "ho calls last gets the response last. Therefore. it follo"s first-in-first-out &-,-%( strategy of /ueue. -uggage chec&ing machine +uggage checking machine checks the luggage first that comes first. Therefore. it follo"s -,-% principle of /ueue. Patients #aiting outsi%e the %octor.s clinic The patient "ho comes first visits the doctor first. and the patient "ho comes last visits the doctor last. Therefore. it follo"s the first-infirst-out &-,-%( strategy of /ueue.

. 1ame 23 situations that can be represented by means of graphs. #xplain "hat each vertex and edge represents. Ans. The situations that can be represented by means of graphs are Example Displacement Shortest Path City Map Air route Population Growth per year In mathematical e pressions Daily temperature report Child"parent relationship %rgani&ation chart Chemical structure Vertex represents Position or state City Places of the city Different airports Population for an year Edge represents Distance between the two vertices connected through the edge Distance between the two vertices connected through the edge Distance between the two vertices connected through the edge Distance between the two vertices connected through the edge Variation in the population between the two vertices connected through the edge Conditions and calculations Variation in the temperature between the vertices connected through the edge $elationship %rder or flow 'onding between the elements

Value !emperature for a specific time #ame of the person Designation Chemical elements

!. Dra" a connected graph that becomes disconnected "hen any edge is removed from it. Ans. The follo"ing figure sho"s a graph that becomes disconnected "hen any edge is removed from it

Disconnected Graph

/. Dra" all trees of n labeled vertices for n42.5.6.7 and *. Ans. The follo"ing figures sho" the trees for various values of n. "here n represents the number of vertices in a tree. -or n42

-or n45

-or n 46 There can be a number of trees "ith 6 labeled vertices. !ome of the examples of the trees "ith 6 labeled vertices are

-or n47 Again. there can be a number of trees "ith 7 labeled vertices. !ome of the examples of the trees "ith 7 labeled vertices are

-or n4* Again. there can be a number of trees "ith * labeled vertices. !ome of the examples of the trees "ith * labeled vertices are

0. !ketch all binary trees "ith six pendent edges. Ans. The follo"ing figures sho" binary trees "ith six pendent edges

'inary !ree with Si Pendent (dges The preceding figures. A. 8. and 9. sho" three examples of binary trees having six pendent edges. All the binary trees having six leaf nodes come under this category.

1. Write ad:acency and incidence matrix for all the graphs developed. Ans. The follo"ing tables sho" ad:acency and incidence matrices for the graph of /uestion no. 7

Solutions to Chapter Three Questions 1. Design and develop algorithms for multiplying n integers. ;int -ollo" the algorithm to add n numbers given in the text Ans. Algorithm <ultiply_n_,ntegers Input2 integers. number of integers to be multiplied &n(. loop variable &i( Output mul. updated 3etho% Display =#nter the number of elements= Accept n Display =#nter elements one by one= for &i 4 2 to n in steps of 2 do( Accept a &i( end_for mul 4 2 for &i 4 2 to n in steps of 2 do( mul 4 mul>a&i( end_for Display =multiplication of n integers is 4 =. mul

2. Design and develop an algorithm for finding the middle element in three numbers. Ans. To find the middle element one has to first sort the numbers in ascending order. The smallest number element in the sorted list and the largest number becomes the last element in the sorted list. 9onsider three numbers 6. 2. and ?. The smallest number amongst these three is 2@ therefore. 2 becomes the first element in the sorted list. Amongst 6 and ?. 6 is the second element. The larger number ? is left out and becomes the last element. ;ence the middle number 6 is displayed. Algorithm 2 <iddle_6_#lements Input a. b. c the three numbers to be sorted. t"o temporary variables k2. and A5 Output <iddle element in the three numbers. 3etho% ,f &aBb( ,f &aBc( ,f &bBc( m4b else m4c end if else m4a end if else if &bBc( if &aBc( m4a else m4c end if becomes the first

else m4b end if end if . Develop an algorithm to find the number of $ermutations and 9ombinations for a given n and r. Ans. $ermutation of a given number is given by n>&n-2(>&n-5(...up to r factors. This is a generaliCed algorithm for nD5 Algorithm $ermutation of a number for a given r Input n and r Output $ermutation of n 3etho% a( per 4 2 for &: 4 n to n - r E 2 in steps of -2 do( ''"here : is a loop variable per 4 per>: end_for Display = $ermutation 4 =. per b( 9ombination of a number n for a given r is calculated by n9r 4 n$r ' rF 9alculate the permutation n$r using the above algorithm 9alculate the factorial for r using the algorithm fact 4 2 for &: 42 to r in steps of 2 do( ''"here : is a loop variable fact 4 fact>: end_for comb 4 per ' fact Display = 9ombination 4=. comb

!. Design an algorithm to generate all prime numbers "ithin the limits l2 and l5. Ans. Algorithm to generate all prime numbers bet"een the limits l2 and l5. Input l2 and l5 Output $rime numbers bet"een l2 and l5 3etho% for &n4l2 to l5 in steps of 2 do( prime4true for &i45 to n'5 in steps of 2 do( if &n G i 43( prime 4 false break end_if end_for if &prime 4 true( Display =$rime number is 4=. n end_for /. Design an algorithm to find the reverse of a number. Ans. Algorithm 0everse of a number Input number Output 0everse of a number 3etho% ne"_number 4 3

"hile &number D 3( n 4 number G 23 ''n denotes a digit extracted from the number number 4 number ' 23 ne"_number 4 ne"_number En ne"_number4 ne"_number>23 end "hile ne"_number 4 ne"_number'23 Display =0everse number is 4=. ne"_number

0. A number is said to be a palindrome if the reverse of a number is same as the original. Design an algorithm to check "hether a number is a palindrome or not. Ans. Algorithm check "hether the number is a palindrome or not Input number. flag Output number is a palindrome 3etho% count 4 3 "hile &number D 3( n 4 numberG23 a&count(4n count 4 countE2 end "hile half 4 count'5 palin 4 true for &:42 to half in steps of 2 and k4count to half in steps of H2 do( if &a &:(F 4a&k(( palin 4 false break end if if &palin 4 true( Display =1umber is a palindrome= else Display =1umber is not a palindrome= end if end for 1. Design an algorithm to check "hether a given string is a palindrome or not. Ans. Algorithm check "hether the string is a palindrome or not Input string. flag Output string is a palindrome 3etho% count 4 3 "hile &the next character ch in the string is not empty( a&count( 4 ch count 4 countE2 end "hile half 4 count'5palin 4 true for &i42 to half in steps of 2 and :4count to half in steps of H2 do( if &a &i(F 4a &:(( palin 4 false break end if if &palin 4 true( Display =!tring is a palindrome=

else Display =!tring is not a palindrome= end for 4. ,mplement all the devised algorithms and also the algorithms discussed in the chapter. Ans. Iou can implement algorithms discussed in this chapter in various languages. such as 9EE and Java. ;o"ever. you need to kno" the syntax of the respective language before implementing it. end if

Solutions to Chapter "our Questions 1. What are the serious shortcomings of the binary search method and se/uential search method? Ans. A serious shortcoming of the se/uential search method is that even if the element that you are trying to search is not present in the given file. the entire file is searched at least once. A serious shortcoming of the binary search method is that it can be applied only to a list in "hich the elements are arranged in ascending order.

2. 9onsider a data set of nine elements K23. 63. 7*. *7. *L. ?M. 526. 72*. *33N and trace the linear search algorithm to find "hether the keys 63. 2*3. ?33 are present in the data set or not. Ans. ,n linear search algorithm. each element in the list is compared "ith the given key element. ,f any of the elements in the list is e/ual to the given key element. the linear search algorithm returns T0O#. else it returns -A+!#. +et us apply linear search to find the key element 63 in the given list.

Take the first element 23 from the list and compare it "ith the key element 63. 9learly the t"o elements are not e/ual. Take the next element 63 from the list and compare it "ith the key element 63. 9learly. the t"o elements are e/ual. The algorithm returns the T0O# value. and the algorithm is terminated.

!imilarly. search for the key elements 2*3 and ?33. At the end of the search. you "ill find that the key elements 2*3 and ?33 are not found in the list.

. Trace the binary search algorithm on the same data set and same key elements of problem 5. Ans. 8inary search algorithm can be applied only to the sorted list of elements. +ets first apply the binary search algorithm to find the key element 63 in the follo"ing list taken from problem 5

Take the middle element from the list and compare it "ith the key element. 9learly. the middle element *L D key element 63. As the key element is smaller than the middle element. the key element can only be present in the left sub list that is as follo"s

Again. take the middle element from this list and compare it "ith the key element. 9learly. the middle element 7* D key element 63. As the key element is smaller than the middle element. the key element can only be present in the left sub list that is as follo"s

Again. take the middle element from this list and compare it "ith the key element. 9learly middle element 634 key element 63. therefore. the binary search algorithm returns a T0O# value and the algorithm is terminated. !imilarly. search for the key elements 2*3 and ?33. At the end of the search. you "ill find that the key elements 2*3 and ?33 are not found in the list.

!. Try to kno" more sorting techni/ues and make a comparative study of them. Ans. There are various sorting techni/ues. such as bubble sort. /uick sort. and shell sort. #ach of these sorting techni/ues is defined as follo"s $u''le sort ,n the bubble sort techni/ue t"o elements are compared at a time and if the t"o elements are not in ascending order these elements are interchanged. This process is repeatedly performed throughout the given list until the list is completely sorted. To sort a list of n elements using bubble sort you need to make a total of &n-2(5 comparisons. Quic& sort The basic idea underlying /uick sort is to allo" a specific element =a= "ithin the list =x= to find its proper position =:=. The proper position =:= is found such that it satisfies the follo"ing t"o conditions The elements on the left hand side of position =:= are all smaller than or e/ual to =a= The elements on the right hand side of position =:= are all greater than or e/ual to =a= ,f =a= satisfies these t"o conditions. then =a= is the :th smallest element in the list and =a= is placed at :th position in the finally sorted list. This process is then repeated for sub arrays x P3..:-2Q and x P:E2..n-2Q. Shell sort ,n shell sort. the given list x is divided into sub lists containing every kth element of the given list. -or example. if k4* then one sub list contains x P3Q. x P*Q. x P23Q.... another sub list contains x P2Q. x PLQ. x P22Q.... and so on. The elements of these sub lists are then compared t"o at a time and if the t"o elements are not in ascending order. these elements are interchanged. 1o". a ne" value of k is chosen "hich is smaller than the previous value of k and the process is repeated again. This process is repeated until the value of k is set to 2 so that the sub list consisting of the entire list is sorted. /. ;and simulate ,nsertion !ort on the data set K26. 7*. 25. R. 2. 23. 73N Ans. +et us apply ,nsertion !ort algorithm on the given list

5ote !he figure )*+ given on page )+ of the boo, is incorrect* It shows the steps for straight selection sort*

0. ,mplement all the algorithms designed in the chapter. Iou can implement algorithms discussed in this chapter in various languages. such as 9EE and Java. ;o"ever. you need to kno" the syntax of the respective language before implementing it. Solutions to Chapter "ive Questions 1. Trace out the algorithm <erge !ort on the data set K2.*.5.2R.7.2?.7*.25.LN Ans. !teps to perform <erge !ort on the data set K2.*.5.2R.7.2?.7*.25.LN are &2.*.5.2R.7NK2?.7*.25.L( &&2.*.5( &2R.7(( &&2?.7*(&25.L(( &&&2.*( &5(( &&2R(&7((( &&&2?(&7*(( &&25( &L((( &&&&2( &*(( &5(( &&2R(&7((( &&&2?(&7*(( &&25( &L((( &2.*( &5( &7.2R( &2?.7*( &L.25( &2.5.*( &7.2R( &2?.7*( &L.25( &2.5.7.*.2R( &L.25.2?.7*( &2.5.7.*.L.25.2?.2R.7*(

2. Trace out the algorithm Suick !ort on the data set K25.2.*.?.2R.2*.M.R.23N. Ans. !teps to perform Suick !ort on the data setK25.2.*.?.2R.2*.M.R.23N are K&25(.2.*.?.2R.2*.M.R.23N K&25(.2.*.?.23.2*.M.R.2RN K&25(.2.*.?.23.R.M.2*.2RN KM.2.*.?.23.R.&25(.2*.2RN K&?(.2.*.M.23.RNK25NK&2*(.2RN K*.2.&?(.M.23.RNK25NK2*.2RN K&*(.2NK?NK&M(.23.RNK25NK2*NK2RN K2.&*(NK?NK&M(.R.23NK25NK2*NK2RN K2.&*(NK?NK&M(.R.23NK25NK2*NK2RN K2NK*NK?NKMNK&R(.23NK25NK2*NK2RN K2NK*NK?NKMNKRNK23NK25NK2*NK2RN

. ,mplement all the algorithms designed in this chapter. Ans. Iou can implement algorithms discussed in this chapter in various languages. such as 9EE and Java. ;o"ever. you need to kno" the syntax of the respective language before implementing it.

!. Trace out the algorithm <ax<in on a data set consisting of at least M elements. Ans.

!teps to perform <ax<in on a data set &5.7.L.6.M.2.R.?( are &5.7.L.6( &M.2.R.?( &&5.7(&L.6(( &&M.2(&R.?(( ,n sublist &7.L(. max is L and min is 7. ,n sublist &M.R(. max is R and min is M. 9omparing max and min values of sublist &5.7( and sublist &L.6(. value of max is L and min is 5. Therefore. for sublist &5.7.L.6( max is L and min is 5. !imilarly. comparing max and min values of sublist &M.2( and sublist &R.?(. value of max is R and min is 2. Therefore. for sublist &M.2.R.?( max is R and min is 2. -inally. comparing max and min values of sublist &5.7.L.6( and sublist &M.2.R.?(. value of max is R and min is 2. /. +ist out the merits and the demerits of recursion. Ans. <erits of recursion are <athematical functions. such as fibonacci series generation can be easily implemented using recursion as compared to iteration techni/ue. Demerits of recursion are <any programming languages do not support recursion@ hence. recursive mathematical function is implemented using iterative methods. #ven though mathematical functions can be easily implemented using recursion. it is al"ays at the cost of execution time and memory space. The recursive programs take considerably more storage and take more time during processing.

0. The data structure used by recursive algorithms is ______. Ans. !tack

1. When is it appropriate to use recursion? Ans. 0ecursion is used for repetitive computations in "hich each action is stated in terms of previous calculation results.

Solutions to Chapter Si, Questions 1. What is a binary tree? Ans. A binary tree is made up of nodes "here each node consists of three elements. left node. right node and a data element. The root node is the topmost node of the binary tree.

2. Differentiate bet"een complete and full binary trees? Ans. The follo"ing table lists the differences bet"een complete binary trees and full binary trees Complete binary trees All the nodes at the previous level are fully accommodated before the ne t level is accommodated* #umber of nodes at the last -n. level may or may not e/ual to 0n* Full binary trees All levels are ma imally accommodated*

#umber of nodes at the last -n. level is e actly e/ual to 0n*

1eaf nodes may or may not be at the same level* A complete binary tree may or may not be full binary tree*

All leaf nodes are at the same level* A full binary tree is always a complete binary tree*

. What is the maximum number of nodes in the binary tree of level ?. M. and R? Ans. The maximum number of nodes in the binary tree is calculated by 5lE2 - 2 "here l is the level of the binary tree. The maximum number of nodes for level ?. 5?E2 - 2 4 5** The maximum number of nodes for level M. 5ME2 - 2 4 *22 The maximum number of nodes for level R. 5RE2 - 2 4 2356

!. What is the "astage of memory for a binary tree "ith 2L nodes represented in a 2D array. 5D array. and a linked representation? Ans. a( -or a 2D array. the formula for calculating percentage of memory utiliCation is &n -2'5lE2 - 2(>233 "here n represents the number of nodes and l represents the depth of the tree. ;o"ever. in the given /uestion. the depth has not been specified. Therefore. the percentage memory utiliCation cannot be calculated. b( -or a 5D array. the percentage of memory utiliCation is &n -2'n5(>233 4 &2L -2'2L5(>233 4 *.MLG Therefore. the "astage of memory in 5D array is 233 - *.ML 4 R7.27G c( -or a linked list. the percentage of memory utiliCation is &n -2'5n(>233 4 &2L -2'5>2L(>233 4 7L.MMG Therefore. the "astage of memory in 2D is 233 - 7L.MM 4 *6.26G

/. -or at least * binary trees of different depths greater than or e/ual to L of your choice. obtain the preorder. postorder and inorder se/uences. Ans. The follo"ing figure sho"s a binary tree "ith 27 nodes "here A is the root node

'inary !ree with +) #odes The preorder traversal se/uence for the above binary tree is A8D;A<1+#9-,J) The infix notation for the above binary tree is <A1;+D8#A,-J9) The postorder notation for the above binary tree is <1A+;D#8,J-)9A

You might also like