You are on page 1of 58

# Classification of Algorithms Algorithms can be categorized into different classes depending upon the paradigms used to design these

algorithms. The names of these classes are same as the name of the paradigm used. Some of the paradigms are: Divide and conquer: Specifies a technique in which a problem is reduced to one or more sub problems. This process of reducing the problem into sub problems is repeatedly performed until the final sub problem is easy to solve. For example in merge sort algorithm a list is divided into sub lists. Then each sub list is sorted separately. Finally all the sorted sub lists are merged and the resultant list is a sorted list. Dynamic programming: Specifies a technique that avoids re!computation of solutions that are already computed. "n dynamic programming algorithm a problem is divided into sub problems. These sub problems are then solved and the solutions of these sub problems are stored somewhere so that it can be used again to solve any other problem if required. For example in an algorithm of finding the shortest path between two nodes of a weighted graph the shortest path can be found by using the pre!calculated shortest paths between ad#acent vertices. The greedy method: Specifies a technique which is similar to dynamic programming technique. The difference between the dynamic programming technique and the greedy method technique is that in greedy method technique you do not have to solve all the sub problems. "nstead you can select a sub problem that can produce the best solution of the problem. For example if you need to search for an element in a tree you can start traversing from either the left or right of the sub tree. \$ou can decide which sub tree is to be traversed first depending upon the value of the %ey element that needs to be searched. "f the value of the %ey element is less than the value of the right sub tree then traversing the left sub tree may yield a better solution. Linear programming: Specifies a method in which a program is divided into a finite number of linear functions that contain several variables. These functions are then sub#ected to a number of constraints. These constraints are in the form of linear inequalities. These linear inequalities are used to minimize or maximize the inputs to the linear function. For example when you need to write an algorithm to find the maximum flow in a directed graph you can use linear programming paradigm. &ith the help of linear programming paradigm you can find and add an augmented path to already established flow in the graph. The addition of this augmented path provides the maximum flow of liquid in the pipe.

Performance of Algorithms The performance of an algorithm can be characterized depending upon two factors the space complexity and time complexity. The basic idea underlying the time complexity is to determine a function of n where n is the size of the problem for which the algorithm is to be written. This function represents an expression of the number of steps required to solve the problem. Since counting the actual number of steps to perform a tas% is not easy the time complexity is not measured by counting the actual number of steps. "nstead the time complexity is measured as the number of critical operations

performed to complete a tas%. There are some standard notations that are used to represent the measure of time complexity. These notations are explained as follows:

'!(otation )Same order*: ' !(otation is defined as the expression f)n* + ' )g)n** where n is the size of the problem. This notation bounds the function f)n* within constant factors. \$ou need to find three positive constants n, c- and c.. The values of these constants should be such that if the value of f)n* is calculated for the values which are larger than n, the value of f)n* always lies between c-g)n* and c.g)n* inclusive. This can be explained with the help of following figure:

c .g )n * f )n * c -g )n * n

n,

Figure Depicting the -Notation /!(otation )0pper 1ound*: /!notation )0pper 1ound* is defined as an expression f)n* + /)g)n** where n is the size of the problem. This notation gives an upper bound for the function f)n* within constant factors. \$ou need to find two positive constants n, and c. The values of these constants should be such that if the value of f)n* is calculated for the values which are larger than n, the value of f)n* always lies on or below cg)n*. This can be explained with the help of following figure: c ) gn * f )n *

f )n *

O + )g )n * *

## Figure Depicting the O-Notation

2!(otation )3ower 1ound*: 2 !(otation )3ower 1ound* is defined as an expression f)n* + 2 )g)n** where n is the size of the problem. "t gives a lower bound for the function f)n* within constant factors. \$ou need to find two positive constants n, and c. The values of these constants should be such that if the value of f)n* is calculated for the values which are larger than n, the value of f)n* always lies on or above cg)n*. This can be explained with the help of following figure:

f )n * c ) gn *

Figure Depicting the -Notation Solutions to Chapter One Questions 1. 44444444444 is the process of executing a correct program on data sets and measuring the time and space it ta%es to compute the results5 Ans. 6rofiling 2. 7efine algorithm5 &hat are its properties5 Ans. An algorithm is a set of instructions that provide step!by!step specifications to perform a tas%. The properties of an algorithm are: Input: Specifies the data set that is applied to the algorithm to chec% its validity. Output: Specifies the data set that is produced as a result of the algorithm execution. Definiteness: Specifies that the instructions described in the algorithm should be well defined and should not create any ambiguity. Termination: Specifies that the instructions described in the algorithm must contain a proper termination condition. Effectiveness: Specifies that the algorithm ta%e less time and less memory space during its execution.

## 3. &hat is debugging and what is profiling5 Ans.

7ebugging is the process of identifying and fixing the errors in a program. 8rrors in a program can be identified by executing the program with a sample dataset. 6rofiling is the process of measuring the performance of the program by executing it on different data sets. 6erformance of a program is measured by recording the time and memory space that the program ta%es during its execution.

. /ne of the properties of an algorithm is beauty )true9false* Ans. False FAQ 1. :an we represent algorithms in a pictorial form5 Ans! \$es you can represent algorithms in the pictorial form using flow charts. Flow charts ma%e use of many geometrical shapes such as rectangles and circles to represent the input output and instructions of an algorithm. 2. &hat should " do if " have to solve a problem that contains many complex tas%s5 Ans! \$ou can write separate algorithms for each tas% and then access these algorithms in other algorithms in a sequence. For example if you have to solve a problem in which you have to perform the following tas%s:

:alculate the difference of two numbers :alculate the sum of other two numbers 6rint the output of both the operations

\$ou can write separate algorithms for each of the first two tas%s and then print the output by writing a separate algorithm for the final tas%. 3. Are there any algorithmic notations to write a nested conditional statement5 Ans! \$es there is an algorithmic notation that you can use to write a nested conditional statement and it is as follows: if ;condition -< if ;condition .< 1loc%. end if 1loc%end if . &hat should " do if " have to terminate a loop structure in the middle when a particular condition arises which is different from the terminating condition of the loop5 Ans!

\$ou can use 1rea% statement to terminate the loop when a particular condition arises which is different from the terminating condition of the loop.

Chapter Two Complete Binary Tree and its Array representation "n a binary tree structure each node can have minimum zero and maximum two child nodes left child node and right child node. A child node having no other child node is %nown as a leaf node. "f all the leaf nodes of a binary tree of height n are at the depth n or n!- the binary tree is called complete binary tree. "n a complete binary tree all the nodes are filled either from left to right or from right to left. "n the following figures figure A shows an incomplete binary tree and the figure 1 shows a complete binary tree:

Figure A

Figure B "n figure A the leaf nodes having value = and . are at the level . and > respectively therefore this violates the condition for the complete binary tree. ?owever in figure 1 all the leaf nodes are at level n and n!-. A complete binary tree can be represented by a simple one!dimensional array. The following figure shows the array representation of the above complete binary tree considering the nodes are filled from left to right:

Array Representation of a Binary Tree B-tree &hile wor%ing with large sets of data you need to store the data in secondary memory such as magnetic dis% and floppy dis%. ?owever the magnetic dis% is slower in data processing as compared to primary memory such as @AA. Therefore the process to retrieve data from the secondary memory ta%es long time. For this a balanced!tree )1! tree* data structure is used which minimizes the data access time. To minimize the access time each node in a 1!tree contains an associated child node where each child node contains the data %eys less than or equal to its preceding nodes. A data %ey represents the data value contained in a node. A node has an additional right!most tree which contains data %eys greater than its preceding nodes. 8ach node in the 1!tree structure tends to have large numbers of child nodes as a result you can find any %ey in the structure by traversing a few nodes. Therefore a 1! tree minimizes the number of dis% accesses to find the desired %ey. The following figure shows an example of a simple 1!tree:

B-tree

The preceding figure shows a 1!tree structure. "n the figure each node has three data %eys which are less than or equal to the preceding data %eys. ?owever the right!most node has data %eys more than the preceding data %eys.

Operations Performed on a B-tree The various operations that you can perform on a 1!tree structure are: "inding a #ey in a \$%tree structure: To search a data %ey such as -. in the above 1!tree data structure first of all compare the first data %ey of root node B with the data %ey to be searched -.. ?owever the data %ey -. is greater than B therefore the next data %ey -- is compared with data %ey -.. The data %ey -. is greater than -- therefore the next data %ey -B is compared with data %ey -.. ?owever the data %ey -. is less than -B therefore the associated child node is selected and the first data %ey -. is compared with it. (ow these two data %eys have same value therefore this data %ey in the structure is the desired data %ey. Inserting a #ey in a \$%tree structure: To insert a data %ey such as -= in the above 1!tree data structure first of all compare the first data %ey of root node B with the data %ey -= to be inserted. The data %ey -= is greater than B therefore the next data %ey -- is compared with data %ey -=. The data %ey -= is greater than -therefore the next data %ey -B is compared with data %ey -=. ?owever the data %ey -= is less than -B therefore the associated child node is selected and data %ey -= is arranged in this node in the ascending order.

The following figure shows the 1!tree structure after inserting a data %ey -=:

B-tree after Inserting a Data Key 15 Solutions to Chapter Two Questions 1. Cive at least = real life examples where we use stac% operations. Ans. The real life examples of stac%s are: \$ang&es in a hand: The bangles wore in a hand follow last!in!first!out )3"F/* strategy of stac%. The bangle that you wear first is the last one to be ta%en out while removing all the bangles from the hand. The bangle that is worn last is the first one to be ta%en out. 'ame circumference circu&ar rings in a po&e: The rings having same circumference placed into a pole also follow 3"F/ strategy. The topmost ring which was the last to be placed in the pole is the first one to be ta%en out. 'ac#s fu&& of (heat p&aced one over other: The sac% at the top is removed first and the sac% at the bottom is removed last.

The )o&ts scre(ed to a sing&e nut: &hen the bolts are screwed to a single nut the last screwed bolt is unscrewed first and the bolt that was screwed first is unscrewed in the last. \$attery ce&&s in a torch: The battery cells in a torch also follow the same 3"F/ strategy of stac%.

2. Cive at least = real life examples where queue is used. Ans. @eal life examples of queue are:

A queue of peop&e at tic#et%(indo(: The person who comes first gets the tic%et first. The person who is coming last is getting the tic%ets in last. Therefore it follows first!in!first!out )F"F/* strategy of queue. *ehic&es on to&&%ta+ )ridge: The vehicle that comes first to the toll tax booth leaves the booth first. The vehicle that comes last leaves last. Therefore it follows first!in! first!out )F"F/* strategy of queue. ,hone ans(ering system: The person who calls first gets a response first from the phone answering system. The person who calls last gets the response last. Therefore it follows first!in!first!out )F"F/* strategy of queue. Luggage chec#ing machine: 3uggage chec%ing machine chec%s the luggage first that comes first. Therefore it follows F"F/ principle of queue. ,atients (aiting outside the doctor-s c&inic: The patient who comes first visits the doctor first and the patient who comes last visits the doctor last. Therefore it follows the first!in!first!out )F"F/* strategy of queue.

3. (ame -, situations that can be represented by means of graphs. 8xplain what each vertex and edge represents. Ans. The situations that can be represented by means of graphs are: Example Disp ace!ent 'hortest "ath (ity )ap Air route "opu ation *ro\$th per year In !athe!atica e,pressions Dai y te!perature report Vertex represents "osition or state (ity " aces of the city Different airports "opu ation for an year +a ue Te!perature for a specific ti!e Edge represents Distance #et\$een the t\$o %ertices connecte& through the e&ge Distance #et\$een the t\$o %ertices connecte& through the e&ge Distance #et\$een the t\$o %ertices connecte& through the e&ge Distance #et\$een the t\$o %ertices connecte& through the e&ge +ariation in the popu ation #et\$een the t\$o %ertices connecte& through the e&ge (on&itions an& ca cu ations +ariation in the te!perature #et\$een the %ertices connecte& through the e&ge

## Re ationship Or&er or f o\$ Bon&ing #et\$een the e e!ents

. 7raw a connected graph that becomes disconnected when any edge is removed from it. Ans. The following figure shows a graph that becomes disconnected when any edge is removed from it:

Disconnecte& *raph .. 7raw all trees of n labeled vertices for n+- . D > and =. Ans. The following figures show the trees for various values of n where n represents the number of vertices in a tree. For n+-

For n+.

For n +D There can be a number of trees with D labeled vertices. Some of the examples of the trees with D labeled vertices are:

For n+> Again there can be a number of trees with > labeled vertices. Some of the examples of the trees with > labeled vertices are:

For n+= Again there can be a number of trees with = labeled vertices. Some of the examples of the trees with = labeled vertices are:

/. S%etch all binary trees with six pendent edges. Ans. The following figures show binary trees with six pendent edges:

Binary Tree \$ith 'i, "en&ent .&ges The preceding figures A 1 and : show three examples of binary trees having six pendent edges. All the binary trees having six leaf nodes come under this category. 0. &rite ad#acency and incidence matrix for all the graphs developed. Ans. The following tables show ad#acency and incidence matrices for the graph of question no. >:

FAQ 1. ?ow will you insert an element in an empty queue5 Ans! \$ou need to increase the value of rear end by one and then insert the value at the location where the rear end of the queue points. 2. :an a three!dimensional array be represented on a paper5 Ans! \$es a three!dimensional array can be represented on a paper by using bloc%s where each bloc% represents a two!dimensional array. 3. &here do you implement stac% operation in a program5 Ans! \$ou implement stac% operation during recursion and function call operations in a program. . :an a matrix have equal number of rows and columns5 &hat is the name of this matrix5 Ans! \$es a matrix can have equal number of rows and columns. This matrix is called a square matrix. .. :an a tree be structured5 Ans! \$es a tree can be structured. A structured tree is used to represent a hierarchical relationship among the various nodes of the tree. For example parent!child relationship in a family can be well represented using a structured tree. /. &hat are the basic differences between a graph and a tree5 Ans! The basic differences between a graph and a tree are: A tree cannot have any cycle however a graph can have a cycle in its structure. All the nodes in a tree structure should be connected to a root node either directly or through any other node however in a graph it is not necessary. The numbers of edges in a tree are always one less than the number of nodes however in a graph edges are less than the vertex but no relation exists between the vertex and its edges.

Chapter Three Control Structures :ontrol structures are used in an algorithm to determine the flow of the algorithm. Two types of control structures used in an algorithm are:

## :onditional statements 3ooping statements

Conditional Statements :onditional statements determine the flow of algorithms based on whether the condition is true or not. A conditional statement is of four types:

## if statement if else statement if...elseif...else statement switch statement

The if statement is a conditional statement used to execute a set of code when a specified condition is true. The syntax of using the if statement is: if )condition* E code to be executed F An example of using the if statement is: if )a is equal to b* E accept )a* F The if else statement is a conditional statement used to execute a set of code when a specified condition is true and another set of code when the condition is false. The syntax of using the if else statement is: if )condition* E code to be executed F else E code to be executed F An example of using the if else statement is:

if )a<b* E display )a* F else E display )b* F The if...elseif...else statement is a conditional statement used to execute a set of code when a specified condition is true from a set of conditions. The syntax of using the if...elseif...else statement is: if )condition* E code to be executed F else if )condition* E code to be executed F else E code to be executed F The example of using the if...elseif...else statement is: if )a;=* E display )a* F else if )a<= and a;-,* E display )b* F else E display )c* F

The switch statement is a conditional statement used to replace if...elseif...else statement. The syntax of using the switch statement is: switch)choice* E case -: executable code brea% case .: executable code brea% case D: executable code brea% default: executable code F Note /ou use the #rea0 state!ent after the e,ecuta# e co&e to ter!inate the s\$itch case state!ent1

The example of using the switch statement is: switch)choice* E case -: display )apple* brea% case .: display )mango* brea% case D: display )pineapple* brea% default: display )banana* F 3ooping statements determine the flow of algorithms based on number of iterations required for the algorithm. 3ooping statements are of three types:

## while loop do while loop for loop

The while loop statement is used to execute a bloc% of code as long as the specified condition is true. "f the condition is false initially the bloc% of code is not executed at all. The syntax of using the while loop is: while )condition* E code to be executed F An example of using the while loop is: while )a<b* E display )a* F The do while looping statement is used to execute a bloc% of code as long as the specified condition is true. The do statement executes the code at least once before chec%ing the condition. The syntax of using the do while loop is: do E

## code to be executed F while )condition is satisfied*

The example of using the do while loop is: do E display )a* F while )a<b* The for looping statement is used to execute a set of statements until the test condition is terminated. The syntax of using the for loop is: for )initialization test condition action* E code to be executed F An example of using the for loop is: for )a+- to = in steps of G-* E display )a* F The following figure shows the categorization of control structures:

## (ategori-ation of (ontro 'tructures ultiplying Two :onsider atrices

&hen multiplying two matrices the number of columns in one matrix should be equal to the number of rows in the other matrix. The procedure is described as follows: The two matrices have to be read initially in a two dimensional array. The row elements of first matrix are multiplied with the corresponding column elements of second matrix. For example the elements of the first row of the first matrix are multiplied with the elements of the first column of the second matrix. Similarly the elements of the second row of the first matrix are multiplied with the elements of the second column of the second matrix and so on. The sums of all these multiplications realize the elements of the resultant matrix. A&gorithm: Aatrix Aultiplication Input: order of the matrices )n* a)n n* b)n n* the two input matrices Output: c)n n* the resultant multiplication matrix 1ethod: Accept n for )i +- to n in steps G - do* for )# +- to n in steps G - do* accept a )i #* end4for end4for for )i +- to n in steps G - do* for )# +- to n in steps G - do* accept b )i #* end4for end4for for )i +- to n in steps G - do* for )# +- to n in steps G - do* for )% +- to n in steps G - do* c)i #*+ c)i #*G a)i %*H b)% #* end4for end4for end4for for )i +- to n in steps G - do* for )# +- to n in steps G - do* display c)i #* end4for end4for

Solutions to Chapter Three Questions 1. 7esign and develop algorithms for multiplying n integers. ?int: Follow the algorithm to add n numbers given in the text Ans. A&gorithm: Aultiply4n4"ntegers Input! integers number of integers to be multiplied )n* loop variable )i* Output: mul updated 1ethod: 7isplay I8nter the number of elementsI Accept n 7isplay I8nter elements one by oneI for )i + - to n in steps of - do* Accept a )i* end4for mul + for )i + - to n in steps of - do* mul + mulHa)i* end4for 7isplay Imultiplication of n integers is + I mul 2. 7esign 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 becomes the first element in the sorted list and the largest number becomes the last element in the sorted list. :onsider three numbers D - and J. The smallest number amongst these three is -K therefore - becomes the first element in the sorted list. Amongst D and J D is the second element. The larger number J is left out and becomes the last element. ?ence the middle number D is displayed. A&gorithm ! Aiddle4D48lements Input: a b c the three numbers to be sorted two temporary variables %- and L. Output: Aiddle element in the three numbers. 1ethod: "f )a;b* "f )a;c* "f )b;c* m+b

else m+c end if else m+a end if else if )b;c* if )a;c* m+a else m+c end if else m+b end if end if

3. 7evelop an algorithm to find the number of 6ermutations and :ombinations for a given n and r. Ans. 6ermutation of a given number is given by nH)n!-*H)n!.*...up to r factors. This is a generalized algorithm for n<. A&gorithm: 6ermutation of a number for a given r Input: n and r Output: 6ermutation of n 1ethod: a* per + for )# + n to n ! r G - in steps of !- do* 99where # is a loop variable per + perH# end4for 7isplay I 6ermutation + I per b* :ombination of a number n for a given r is calculated by n:r + n6r 9 rM :alculate the permutation n6r using the above algorithm :alculate the factorial for r using the algorithm fact + for )# +- to r in steps of - do* 99where # is a loop variable fact + factH# end4for comb + per 9 fact 7isplay I :ombination +I comb . 7esign an algorithm to generate all prime numbers within the limits l- and l.. Ans. A&gorithm: to generate all prime numbers between the limits l- and l.. Input: l- and l. Output: 6rime numbers between l- and l. 1ethod: for )n+l- to l. in steps of - do* prime+true for )i+. to n9. in steps of - do* if )n N i +,* prime + false brea% end4if end4for if )prime + true* 7isplay I6rime number is +I n end4for

.. 7esign an algorithm to find the reverse of a number. Ans. A&gorithm: @everse of a number Input: number Output: @everse of a number 1ethod: new4number + , while )number < ,* n + number N -, 99n denotes a digit extracted from the number number + number 9 -, new4number + new4number Gn new4number+ new4numberH-, end while new4number + new4number9-, 7isplay I@everse number is +I new4number /. A number is said to be a palindrome if the reverse of a number is same as the original. 7esign an algorithm to chec% whether a number is a palindrome or not. Ans. A&gorithm: chec% whether the number is a palindrome or not Input: number flag Output: number is a palindrome 1ethod: count + , while )number < ,* n + numberN-, a)count*+n count + countGend while half + count9. palin + true for )#+- to half in steps of - and %+count to half in steps of O- do* if )a )#*M +a)%** palin + false brea% end if if )palin + true* 7isplay I(umber is a palindromeI else 7isplay I(umber is not a palindromeI end if

end for

0. 7esign an algorithm to chec% whether a given string is a palindrome or not. Ans. A&gorithm: chec% whether the string is a palindrome or not Input: string flag Output: string is a palindrome 1ethod: count + , while )the next character ch in the string is not empty* a)count* + ch count + countGend while half + count9.palin + true for )i+- to half in steps of - and #+count to half in steps of O- do* if )a )i*M +a )#** palin + false brea% end if if )palin + true* 7isplay IString is a palindromeI else 7isplay IString is not a palindromeI end if end for 2. "mplement all the devised algorithms and also the algorithms discussed in the chapter. Ans. \$ou can implement algorithms discussed in this chapter in various languages such as :GG and Pava. ?owever you need to %now the syntax of the respective language before implementing it. FAQ 1. "s there any operator that determines the remainder during division operation5 Ans! @emainder can be found out using the operator N.

2. &hat will happen when the user tries to find out the quadrant for the coordinate input ), ,*5

Ans! &hen the user inputs ), ,* the first condition in the algorithm that is x<+, and y<+, gets satisfied and the program will output first quadrant as the solution.

3. ?ow to calculate the factorial for number ,5 Ans! M, +This exception is generally specified by the programmer. This condition can be chec%ed using if else statement. . ?ow to find the largest of three numbers a b and c5 Ans! largest + a if )largest;b* largest + b if )largest;c* largest + c 7isplay I3argest number isI largest .. ?ow to interchange the values of two numbers a and b5 Ans. :onsider a variable c to temporarily store the value of variable a. The following algorithm shows how to interchange the values of two numbers by using a temporary variable. 7isplay I8nter the value of aI Accept a 7isplay I8nter the value of bI Accept b c+a a+b b+c 7isplay IThe values of a and b are I a b /. ?ow to interchange the values of two numbers a and b without using temporary variable5 Ans! 7isplay I8nter the value of aI Accept a 7isplay I8nter the value of bI Accept b

## a+aGb b+a!b a+a!b 7isplay IThe values of a and b are I a b

Chapter Four !nde"ed Se#uential Searching "ndexed sequential search is a technique used to search an element in a given list. "n indexed sequential search technique it is necessary to have the elements to be arranged in the ascending order in a list. "n indexed sequential search an auxiliary table is set aside along with the list in which the %ey element is to be searched. This auxiliary table is called "ndex. The "ndex contains two columns %index and pindex. :olumn %index contains elements from the given list. :olumn pindex contains address of the memory location where the elements of the given list represented by %index are stored.

"ndexed sequential search can be explained with the help of following example: Suppose you have to find the %ey element .QR in the given list of -Q elements. 3et us ta%e an index table that contains D records. Therefore the given list is divided into three parts each having B )calculated as -Q9D + B* elements and each record in the "ndex represents the Bth element in the given list.

The %ey element .QR is smaller than the first element D>. in the %index. Therefore you do not need to search the entire list. \$ou can simply search for the %ey element in the sub list x S,..BT. A&gorithm : Input : "ndexed Sequential Search n Size of the input domain A S-..nT array of n elements % search element indexsize size of the auxiliary table called "ndex Output 1ethod i+, while )i; indexsize and %index SiT; %* i+iGend4while if i+, then lowlim + , else lowlim + pindex Si!-T : : # position of %

end4if if i+indexsize then hilim+n!else hilim+pindex SiT!end4if #+lowlim &hile )#;+ hilim and A S#T M + %* #+#Gend4while if #< hilim then return !else return # end4if Bu\$\$le Sorting The basic idea underlying the bubble sorting technique is to pass through the file containing n number of elements n!- number of times. "n each pass each ith element in the file is compared with its successor )iG-*th element. "f the ith element is greater than its successor element these elements are interchanged. :onsider the file containing the following elements:

Following changes are made during the first pass: .- is compared with =D =D is compared with >Q =D is compared with D= =D is compared with -. =D is compared with QJ QJ is compared with Q. QJ is compared with DD )as .-; =D* )as =D< >Q* )as =D< D=* )as =D< -.* )as =D; QJ* )as QJ< Q.* )as QJ; DD* no change in the order of the elements. interchange the elements. interchange the elements. interchange the elements. no change in the order of the elements. interchange the elements. interchange the elements.

The resultant order of elements after the first pass is as follows: Similarly the subsequent passes yield:

1ubble Sort

## n Size of the input domain A S-..nT array of n elements a S-...nT sorted

for )i+, to n!- in steps of - do* for )#+, to n!i!- in steps of - do* "f )a S#T< a S#G-T* then interchange a S#T and a S#G-T end4if end4for end4for Solutions to Chapter Four Questions 1. &hat are the serious shortcomings of the binary search method and sequential search method5 Ans. A serious shortcoming of the sequential 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 which the elements are arranged in ascending order. 2. :onsider a data set of nine elements E-, D, >= => =B JQ .-D >-= =,,F and trace the linear search algorithm to find whether the %eys D, -=, J,, are present in the data set or not. Ans. "n linear search algorithm each element in the list is compared with the given %ey element. "f any of the elements in the list is equal to the given %ey element the linear search algorithm returns T@08 else it returns FA3S8. 3et us apply linear search to find the %ey element D, in the given list. Ta%e the first element -, from the list and compare it with the %ey element D,. :learly the two elements are not equal. Ta%e the next element D, from the list and compare it with the %ey element D,. :learly the two elements are equal. The algorithm returns the T@08 value and the algorithm is terminated.

Similarly search for the %ey elements -=, and J,,. At the end of the search you will find that the %ey elements -=, and J,, are not found in the list.

3. Trace the binary search algorithm on the same data set and same %ey elements of problem .. Ans. 1inary search algorithm can be applied only to the sorted list of elements. 3ets first apply the binary search algorithm to find the %ey element D, in the following list ta%en from problem .:

Ta%e the middle element from the list and compare it with the %ey element. :learly the middle element =B < %ey element D,. As the %ey element is smaller than the middle element the %ey element can only be present in the left sub list that is as follows: Again ta%e the middle element from this list and compare it with the %ey element. :learly the middle element >= < %ey element D,. As the %ey element is smaller than the middle element the %ey element can only be present in the left sub list that is as follows: Again ta%e the middle element from this list and compare it with the %ey element. :learly middle element D,+ %ey element D, therefore the binary search algorithm returns a T@08 value and the algorithm is terminated. Similarly search for the %ey elements -=, and J,,. At the end of the search you will find that the %ey elements -=, and J,, are not found in the list. . Try to %now more sorting techniques and ma%e a comparative study of them. Ans. There are various sorting techniques such as bubble sort quic% sort and shell sort. 8ach of these sorting techniques is defined as follows: \$u))&e sort: "n the bubble sort technique two elements are compared at a time and if the two 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 ma%e a total of )n! -*. comparisons. 3uic# sort: The basic idea underlying quic% sort is to allow a specific element IaI within the list IxI to find its proper position I#I. The proper position I#I is found such that it satisfies the following two conditions: The elements on the left hand side of position I#I are all smaller than or equal to IaI The elements on the right hand side of position I#I are all greater than or equal to IaI "f IaI satisfies these two conditions then IaI is the #th smallest element in the list and IaI is placed at #th position in the finally sorted list. This process is then repeated for sub arrays x S,..#!-T and x S#G-..n!-T. 'he&& sort: "n shell sort the given list x is divided into sub lists containing every %th element of the given list. For example if %+= then one sub list contains x S,T x S=T x S-,T... another sub list contains x S-T x SBT x S--T... and so on. The elements of these sub lists are then compared two at a time and if the two elements are not in ascending order these elements are interchanged. (ow a new value of % is chosen which is smaller than the previous value of % and the process is repeated again. This process is repeated until the value of % is set to so that the sub list consisting of the entire list is sorted.

.. ?and simulate "nsertion Sort on the data set E-D >= -. R - -, >,F Ans. 3et us apply "nsertion Sort algorithm on the given list:

Note The figure 211 gi%en on page 21 of the #oo0 is incorrect1 It sho\$s the steps for straight se ection sort1

/. "mplement all the algorithms designed in the chapter. \$ou can implement algorithms discussed in this chapter in various languages such as :GG and Pava. ?owever you need to %now the syntax of the respective language before implementing it. FAQ 1. " have stored some messages received from my friends in a folder and " want to sort these messages. ?ow can " do that5 Ans! To sort a list of elements you need to compare each element with the other element in the list and then place these elements in the sorted order. The messages do not contain

any information that can be used to compare one message with the other. Therefore you can sort these messages only with respect to the names of your friends which can be easily compared.

2. "s there any other %ind of selection sorting technique which is different from the straight selection sorting technique5 Ans! \$es there is one more selection sorting technique %nown as the general selection sort. "n general selection sort each element is selected one at a time and placed in its proper sorted position in the given list. The elements are selected in the same order in which they are placed in the given list. 3. :an we implement binary search technique to find an element in a data structure other than arrays5 Ans! \$es you can use the binary search technique to search an element in a tree data structure. To apply the binary search technique on a tree data structure the left hand child node of the tree data structure must be less than or equal to the parent node. "n addition the right hand child node must be greater than or equal to the parent node. . To sort a list of alphabets " need to compare two alphabets and place them in proper order. ?ow does the computer understand that alphabet a is less than b5 Ans! The computer does not compare the alphabets as it is but it compares the AS:"" values of alphabets which are in the form of numerals. .. &hat should " do if " have to insert an element in a given list such that the elements in the list are in ascending order5 Ans! Sort the elements in the given list in ascending order using insertion sorting technique. Then select a position in the list where the new element is to be inserted. Aove all the elements that are placed at the right hand side of this position by one position to the right. This process of moving the elements creates an empty space in the given list. 6lace the new element at this newly created space in the list. The space is created such that the element is placed in the ascending order in the list with respect to the elements already present in the list.

Chapter Fi%e Nested &ecursion A recursive call is called nested if the result of the recursive call to itself depends on the result of another recursive call to itself. The following algorithm illustrates the functioning of nested recursion. Algorithm: nestrecurs)i* input: i if)i<-,-* return)i!-,* else nestrecurs)nestrecurs)iG--** end4if "n the above algorithm nestrecurs)nestrecurs)iG--** represents nested recursion. The result of the outer recursive call nestrecurs)nestrecurs)iG--** depends on the result of the inner recursive call nestrecurs)iG--*. For example ta%e a number i+ RR. The processing ta%es place in four recursions when the value of i is put in the algorithm nestrecurs)i*. 7uring the first pass through the algorithm you will obtain the following value: As i;-,, nestrecurs)RR* + nestrecurs)nestrecurs)--,* After the first recursive call by the inner recursive function nestrecurs)--,* you will obtain the following value: As i<-,, nestrecurs)RR* + nestrecurs)-,,* After the second recursive call by the outer recursive function nestrecurs)-,,* you will obtain the following value: As i+-,, nestrecurs)nestrecurs)---* After the third recursive call by the inner recursive function nestrecurs)---* you will obtain the following value: As i<-,, nestrecurs)-,-* After the fourth recursive call by the outer recursive function nestrecurs)-,-* you will obtain the following value: As i<-,, R-

Shell Sort "n shell sort the original file is divided into sub files and each sub file contains %th element of the original file. For example if %+= then one sub file contains xS,T xS=T and xS-,T another sub file contains xS-T xSBT and xS--T and the list of sub files continues till the value of first element of the sub file reaches to xS>T. These sub files are sorted and a smaller value of % is selected. The process is repeated till the value of % is set to - so that the sub file consisting of the entire sub files is sorted. The following algorithm shows the shell sort process. a&gorithm: shellsort )original file* Input: original file % subfile )original file %* sort )subfiles* %+%!. if)%<+-* shellsort)sorted file* else return )-* end4if To understand the above algorithm ta%e an example of an original file which is .= BJ =B DR ., -,D RJ DJ

Ta%e the value of % + =.Therefore the first sub file contains the elements of the original file at ,th and =th position and the second sub file contains the elements of the original file at -st and Bth position. The third sub file contains .nd and Jth elements the forth sub file contains Drd and the fifth sub file contains >th element of the original file. (ow elements of each sub file are sorted in ascending order. The following table shows all the sub files in ascending order: Sub file First su# fi e 'econ& su# fi e Thir& su# fi e Forth su# fi e Fifth su# fi e 35 67 57 58 34 Elements 145 87 56

(ow the value of % is decreased by . therefore the value becomes D after the decrement. The value of % is greater than - therefore shell sort algorithm is called again for %+D which represents first recursive call. The following table shows all sub files in ascending order after the first recursive call: Sub file First su# fi e 'econ& su# fi e Thir& su# fi e 35 34 57 Elements 58 56 145 87 67

(ow again the value of % is decreased by . which is - after the decrement. The value of % is equal to - therefore shell sort algorithm is called again for %+- which represents the second recursive call. The following table shows all sub files in the ascending order after the second recursive call: Sub file First su# fi e Elements 34 35 57 58 56 67 87 145

(ow again the value of % is decreased by . which becomes !- after the decrement. The value of % is now less than - therefore shell sort algorithm will return the file which is arranged in the sorted order. Solutions to Chapter Fi%e Questions 1. Trace out the algorithm Aerge Sort on the data set E- = . -R > -J >= -. BF

Ans. Steps to perform Aerge Sort on the data set E- = . -R > -J >= -. BF are: )- = . -R >FE-J >= -. B* ))- = .* )-R >** ))-J >=*)-. B** )))- =* ).** ))-R*)>*** )))-J*)>=** ))-.* )B*** ))))-* )=** ).** ))-R*)>*** )))-J*)>=** ))-.* )B*** )- =* ).* )> -R* )-J >=* )B -.* )- . =* )> -R* )-J >=* )B -.* )- . > = -R* )B -. -J >=* )- . > = B -. -J -R >=* 2. Trace out the algorithm Uuic% Sort on the data set E-. - = J -R -= Q R -,F. Ans. Steps to perform Uuic% Sort on the data setE-. - = J -R -= Q R -,F are: E)-.* - = J -R -= Q R -,F E)-.* - = J -, -= Q R -RF E)-.* - = J -, R Q -= -RF EQ - = J -, R )-.* -= -RF E)J* - = Q -, RFE-.FE)-=* -RF E= - )J* Q -, RFE-.FE-= -RF E)=* -FEJFE)Q* -, RFE-.FE-=FE-RF E- )=*FEJFE)Q* R -,FE-.FE-=FE-RF E- )=*FEJFE)Q* R -,FE-.FE-=FE-RF E-FE=FEJFEQFE)R* -,FE-.FE-=FE-RF E-FE=FEJFEQFERFE-,FE-.FE-=FE-RF 3. "mplement all the algorithms designed in this chapter. Ans. \$ou can implement algorithms discussed in this chapter in various languages such as :GG and Pava. ?owever you need to %now the syntax of the respective language before implementing it. . Trace out the algorithm AaxAin on a data set consisting of at least Q elements. Ans. Steps to perform AaxAin on a data set ). > B D Q - R J* are: ). > B D* )Q - R J*

)). >*)B D** ))Q -*)R J** "n sublist )> B* max is B and min is >. "n sublist )Q R* max is R and min is Q. :omparing max and min values of sublist ). >* and sublist )B D* value of max is B and min is .. Therefore for sublist ). > B D* max is B and min is .. Similarly comparing max and min values of sublist )Q -* and sublist )R J* value of max is R and min is -. Therefore for sublist )Q - R J* max is R and min is -. Finally comparing max and min values of sublist ). > B D* and sublist )Q - R J* value of max is R and min is -.

.. 3ist out the merits and the demerits of recursion. Ans. Aerits of recursion are: Aathematical functions such as fibonacci series generation can be easily implemented using recursion as compared to iteration technique. 7emerits of recursion are: Aany programming languages do not support recursionK hence recursive mathematical function is implemented using iterative methods. 8ven though mathematical functions can be easily implemented using recursion it is always at the cost of execution time and memory space. The recursive programs ta%e considerably more storage and ta%e more time during processing. /. The data structure used by recursive algorithms is 444444. Ans. Stac% 0. &hen is it appropriate to use recursion5 Ans. @ecursion is used for repetitive computations in which each action is stated in terms of previous calculation results. FAQ 1. &hat will happen if a terminating condition is not given in a recursive process5 Ans! "f the terminating condition is not given the recursive process the recursive process will be continued in an infinite loop. 2. &hat is the complexity of quic% sort and merge sort for an average case5 Ans! The complexity of both merge sort and quic% sort for an average case is: /)n log n* 3. :an " solve any problem without using recursion5 Ans!

\$es you can solve any problem without using recursion. ?owever the number of iterations in a program increases when you create a program without recursion. This is because recursion provides an easy and efficient way to solve complex problems. . Cive some examples of sorting where you can use recursion5 Ans! There are various types of sorting that use recursion such as shell sort and heap sort.

.. "n the worst case complexity which sorting technique merge sort or quic% sort should be used and why5 Ans! "n the worst case complexity you should use merge sort. The complexity of merge sort in worst case is /)n log n* which is better then the complexity of quic% sort in worst case that is /)n.*.

Chapter Si" !nfi"' Prefi"' and Postfi" ("pressions "nfix prefix and postfix are various notations that can be used for representing a mathematical expression. "n infix notation the operator is placed between the two operands. "n prefix notation the operator precedes the two operands whereas in postfix notation the operator follows the two operands. The prefixes IpreI IpostI and IinI refer to the relative position of the operator with respect to the two operands. :onsider an example that represents the sum of two variables A and 1. The infix notation for this equation is represented as AG1. The postfix notation for this equation is represented as A1G The prefix notation for this equation is represented as GA1.

:onsider another example AG1H:. This equation is written in the standard infix notation. 1efore evaluating the expression you must %now the operation to be performed first. The operation to be performed first can be determined from the arithmetic precedence of operators. "n the absence of parenthesis in the above equation it is explicit that multiplication precedes over addition. The general rule during the conversion process is that the operations with highest precedence are converted first. The expression obtained after this conversion is then treated as a single operand. The above equation can be represented in infix notation with parenthesis as: A G )1 H :* A G )1 H :* AG7 parenthesis for emphasis evaluate the multiplication

evaluate the addition where 7+ 1 H : parenthesis for emphasis convert the multiplication

The same equation A G 1 H : can be represented in postfix notation as: A G )1 H :* A G )1 :H* A 1:HG

A )1:H*G convert the addition postfix notation parenthesis for emphasis convert the multiplication The same equation A G 1 H : can be represented in prefix notation as: A G )1 H :* A G )H1 :* GA H1:

GA )H1:* convert the addition prefix notation A mathematical expression can also be represented in the form of a binary tree called expression tree. For example the expression .GDH= can be represented as: H G . D =

The inorder traversal of an expression tree yields the expression in inorder notation. The postorder traversal of a binary tree yields the expression in postorder notation. Similarly the preorder traversal of a binary tree yields the expression in preorder notation. Strict Binary Tree "f every non!leaf node in a binary tree has non!empty left and right sub trees the tree is %nown as a strict binary tree. A strict binary tree with n leaves always contains ).n!-* nodes. (ote: A non!leaf node is the node that is not present at the last level of the binary tree and has at least one child node.

## The following figure shows how to represent a strict binary tree:

'trict Binary Tree Solutions to Chapter Si" Questions 1. &hat is a binary tree5 Ans. A binary tree is made up of nodes where 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. 7ifferentiate between complete and full binary trees5 Ans. The following table lists the differences between complete binary trees and full binary trees: Complete binary trees A the no&es at the pre%ious e%e are fu y acco!!o&ate& #efore the ne,t e%e is acco!!o&ate&1 Nu!#er of no&es at the ast 9n: e%e !ay or !ay not e;ua to 3n1 <eaf no&es !ay or !ay not #e at the sa!e e%e 1 A co!p ete #inary tree !ay or !ay not #e fu #inary tree1 Full binary trees A e%e s are !a,i!a y acco!!o&ate&1

Nu!#er of no&es at the ast 9n: e%e is e,act y e;ua to 3n1 A eaf no&es are at the sa!e e%e 1 A fu #inary tree is a \$ays a co!p ete #inary tree1

3. &hat is the maximum number of nodes in the binary tree of level J Q and R5 Ans. The maximum number of nodes in the binary tree is calculated by .lG- ! - where l is the level of the binary tree. The maximum number of nodes for level J .JG- ! - + .== The maximum number of nodes for level Q .QG- ! - + =-The maximum number of nodes for level R .RG- ! - + -,.D . &hat is the wastage of memory for a binary tree with -B nodes represented in a -7 array .7 array and a lin%ed representation5 Ans. a* For a -7 array the formula for calculating percentage of memory utilization is: )n !-9.lG- ! -*H-,, where n represents the number of nodes and l represents the depth of the tree. ?owever in the given question the depth has not been specified. Therefore the percentage memory utilization cannot be calculated. b* For a .7 array the percentage of memory utilization is: )n !-9n.*H-,, + )-B !-9-B.*H-,, + =.QBN Therefore the wastage of memory in .7 array is -,, ! =.QB + R>.->N c* For a lin%ed list the percentage of memory utilization is: )n !-9.n*H-,, + )-B !-9.H-B*H-,, + >B.QQN Therefore the wastage of memory in -7 is -,, ! >B.QQ + =D.-DN .. For at least = binary trees of different depths greater than or equal to B of your choice obtain the preorder postorder and inorder sequences. Ans. The following figure shows a binary tree with -> nodes where A is the root node:

Binary Tree \$ith 12 No&es The preorder traversal sequence for the above binary tree is: A17?LA(38:F"PC The infix notation for the above binary tree is: AL(?3718A"FP:C The postorder notation for the above binary tree is: A(L3?781"PFC:A FAQ 1. 7etermine the condition in which complete binary tree is called full binary tree. Ans! A complete binary tree is called full binary tree if

All the leaves are present only at the last level. All the nodes at the previous level are fully accommodated.

2. &hat is static allocation for representing a binary tree5 Ans! Static allocation means that the memory allocation for representing the binary tree using -7 or .7 arrays is made statically at compile time.

3. &hat is dynamic allocation for representing a binary tree5 Ans! 7ynamic allocation means that the memory allocation for representing the binary tree using lin%ed list is made dynamically at run time. . &hat is the use of a binary tree5 Ans! 1inary trees are used in search techniques such as binary search. 1inary trees designed for binary search are called binary search trees. 1inary search trees have the following characteristics: The data %ey in the left child node needs to be smaller than or equal to the data %ey of its parent node. The data %ey in the right child node needs to be greater than or equal to the data %ey of its parent node.

.. &hat conditions are required to ma%e a binary tree a complete binary tree5 Ans! Two conditions that are required to ma%e a binary tree of depth d a complete binary tree are:

Any node at level less than d !- has two children. Any node in the tree with a right child at level d must have a left child and every left descendant of the parent node either is a leaf at level d or has two children.