You are on page 1of 90
TACK Ce , rmsek is one of the most commonly used data ie A stack, also called a Last-In-Frst-Out (LIFO) se linear list in which insertions and deletions can ten te only at one end, called the top. This structure a in much the same way as stack of trays. If we one place anoet tray, it can be placed only at the top ar ry if we want (0 remove a tray from stack of trays, i similarly, ed from the top. The insertion and deletion nly be remove ions ‘stack terminology are known as push and pop operations. - y | |S Fig. 1 Stack of trays rhe following operations are performed on stacks: 1. Create stack(s) - To create s as an empty stack. 1) -To push element i onto stack s. 3, Pop(s)- To access and remove the top element of the stack s. 4, Peek(s) - To access the top element of the stack s without removing it from the stack s. 5, Is full) - To check whether the stack s is full. 6. Is empty(s) - To check whether the stack s is empty. All ofthese operations run in O(|) time. Representing a Stack using an Array : To implement astack we need a variable, called top, that holds the index of the op element ofthe stack and an array to hold the elements ofthe stack. Let us suppose that the elements of the stack Data Stauctures ann ALGORITHMS CuapTer In A NUTSHELL are of integer type, and the stack ean store m such elements, i.c., stack size is 10. represented using a linked li The array-based representation of stack suffers from following limitations. iaximum of 10 The following are the necessary declarations = # define MAX 10 typedef struct { int tops int elements [MAX] ? ) stack; stack 35 Representing a Stack using a Linked List : A stack also known as linked stack, © Size of the stack must be known in advance. © We may come across situations when an attempt to push an element causes overflow. However, stack, as an abstract data structure cannot be full. Hence, abstractly, itis always possible to push an element onto stack. Therefore, representing stack as an array prohibits the growth of stack beyond the finite number of elements. The linked list repredentation allows a stack to grow to a limit of the computer's memory. The following are the necessary declarations : typedef struct nodeType { int info; struct nodeType *next; } stacks stack *top; Applications of Stacks s mentioned earlier, stack is, one of the most commonly used data structures, Some of its applications are 1. Stacks are used to pass parameters between functions. On a call to a function, the parameters and local variables are stored on a stack. High-level programming languages, such as Pascal, N, it verif , ete, that provides support for recursion use stack for book keeping. Remember, in each recursive call, there is a need to save the current values of parameters, local variables and the return addi (the address where the contro! has to return from brackets “[]”. Foran input expre left parenthesis, brace of bracke closing symbol and the symbols are appre Some examples of aid ape are Seri a Parenthesis Checker : Parenthesis Checker is a Program that checks whether a mathematical expression is Property parenthesised. We will consider three sets of grouping, symbols: the standard parenthesis “()", braces “{)”, and ns Inside parenthesis (braces or bracket any valid arithmetic expression. If the no even then it is valid input otherwise itis inva) Previous YEARS QUESTIONS 3, Write: BEG-> END. 4, [Move N= I disks from peg AUX 10 peg Call TOWER(N - 1, AUX, BEG FD 5. Return. So the Tower of Hanoi problam can be sioved the recursion. | Prob.l What are the applications of stack? [R.T.U. 2018} aT Sol. Applications of Stacks : As mentioned earlier, stack is one of the most commonly used data structures. Some of its applications are : 1. Stacks are used to pass parameters between functions. On a call to a function, the parameters and local variables are stored on a stack. 2. High-level programming languages, such as Pascal, C, etc, that provides support for recursion use stack for book keeping. Remember, in each recursive call, Prob.3 Convert following infix expression into notatior A+B-(C+D)/E*F-(G+h) 1 IRL. Ded Sol. A+ B-(C+D)/E*F-(G+h)/I Symbolscanned Stack Postfix Expression there is a need to save the current values of i a“ parameters, local variables and the return address e a (the address where the control has to return from & AB the call). Ge AB —— ae SHC ae: Prob.2 Write down the recursive algorithm to solve tower G-¢ ‘ABC of Hanoi problem? [RTU. 2018] GG ABC ABCD Sol. Procedure : Tower (N, BEG, AUX, END) ABCD+ ‘ABCD* This procedure gives a recursive solution to the Tower of Hanoi problem for N disks ABYD+E 1. IPN = Lthen: ABYD+E) (a) Write: BEG—> END. ABYDHEF (b) Return. AB+D+EF* [End of, If structure.) aan 2. [Move N = | disks from peg BEG to peg AUX.] Se a - |, BEG, END, AUX). Call TOWER(N - 1, BEG, END, AUX). ee Prob.7 What is STACK? Write algorithms to insert om clement in STACK and delete an element from STACK with example. [RTU, Dec. 2016) :AB+D+E/F*Ghot/ + Sol. Stack : A stack is a list of elements in which an element may be in ‘serted or deleted only at one end, called the top of the stack. This means, in particular, that elements are removed from a stack in the reverse order of that in which they were inserted into the stack. Special terminology is used for two basic operations associated with stacks: (a) “Push” isthe term used to insert an element into # stack. (b) “Pop” is the term used to delete an element from stack. not with other data structures. Example “Suppose the following 6 elements are pushed, in order, onto an empty stack: ‘AAA, BBB, CCC, DDD, EEE, FFF : Figure shows three ways of picturing sueb a stack. For the following expression in Postfix DYE - FG + WK) IRTU, Jon 2016) (p+D)/E-F*(G+H/k) {o(BD+)/E-F*(G+ HK) +(b*(e-d)+(e)-(F*8))) into peru. 201g notational convenience, we wil frequently designate the stack by writing: ‘STACK: AAA, BBB, CCC, DDD, EEE, FFF ‘The implication is that the right-most element isthe top clement, We emphasize that, rogardless of the way a stack is described, its underlying property is that insertions and deletions tan occur only atthe top of the stack. This means ee ad EEE cannot be deleted before FFF is deleted, DDD cannot be deleted before EEE and FFF are deleted, and s0 on. Consequently, the elements may be popped from the stack only in the reverse order of that in which they were pushed ‘onto the stack, tponed Decisions iaaean frequently used to indicate the order of the processing of data when certain steps ofthe processing must be postponed until other conditions are fulfilled. This is illustrated as follows. Suppose that while processing some project A we are required to move on to project B, whose completion is required in order to complete project A. Then we place the folder containing the data of A onto a stack, as pictured in figure 2(a), and begin to process B. However, suppose that while processing B we are led to project C, for the same reason. Then we place B on the stack above A, as pictured in figure 2(b), and begin to process C. Furthermore, suppose that while processing C we are likewise led to project D. Then we place C on the stack above B, as pictured in ow figure 2 (c), and begin to process D. ” Fig.2 On the other hand, suppose we are able to complete the Processing of project D. Then the only project we may continue to process is project C, which is on top of the stack. Hence we remove folder C from the stack, leaving the stack as Pictured in figure (4), and continue to process C. Similarly, afier completing the processing of C, we remove folder B from the stack, leaving the stack as pictured in figure 2(e), and continue to process B. Finally, after completing the processing of B, we remove the last folder, A, from the stack, leaving the empty stack pictured in figure (f), and continue the processing of our original project A Observe that, at cach stage of the above processing, the stack automatically maintains the order that is requited to complete the processing. An important example of such a processing in computer science is where Ais a main program and B, C and D are subprograms called in the order given, Array Representation of Stacks Stacks may be represented in the computer in various Tay, usually by means of a one-way list ora linear array Unless otherwise stated or implied, each of our stacks wit be maintained by a linear array STACK; a pointer variable TOP, which contains the location of the top element of the Stack; and a variable MAXSTK which gives the maximum number of elements that can be held by the stack. The o ow empty. erie rhe such an array representation op, ; (For notational convenience, the array is drawn hon’ rather than vertically.) Since TOP ~ 3, the stag Jemets, XXX, YVY and Z2Z; and since MAXSTy “ rooms for 5 more items in the stack, C 77] a) = = [ZS maxsx [o Fig. 3 The operation of adding (pushing) an item onto, 7 and the operation of removing (popping) an item froma ( may be implemented, respectively, by the Talli procedutes called PUSH and POP. In exscung | procedure PUSH, one must first test, whether there in the stack for the new item; if not, then we have the known as overflow. Analogously, in executing the POP, one must first test, whether there isan element stack o be deleted; ifnot, then we have the conditionla| as underflow. Procedure 1: PUSH(STACK, TOP, MAXSTK, ITEM) This procedure pushes an ITEM onto a sia [Stack already filled?] If TOP = MAXSTK, then: Print: OVER and Return, Set TOP : =TOP + 1. [Increases TOP by 1] Set STACK[TOP] := ITEM. [Inserts ITEM int TOP position,] . Return, Procedure 2: POP(STACK, TOP, ITEM) This procedure deletes the top element of STACK assigns it to the variable ITEM. 1. [Stack has an item to be removed?] If TOP = 0, then: Print: UNDERFLOW, Return, Retum, Frequently, hence the proced PUSH(STA Respectivel before the inserti after the deletio TOP and MAXSTK are global lures may be called using only ‘CK, ITEM) and POP(STACK, ITEM) I, We note that the value of TOP isch ion in PUSH but the value of TOP ish nin POP, write an algorithm for conve jn to prefix expression and give sion of infix Prefix form for IU, 2013 soppose Q is an arithmetic expression writen in infix PP salgorthm finds the equivalent postix expression fy Pst "C 080 STACK, and 2dd")" to the end of Q Q from left to right and repeat steps 3 t0 6 0 St element of Q until the stack is empty, ee, {jan operand is encountered add it to P, ale parenthesis is encountered push tonto the stack. ‘operator is encountered, then: (@) repeatedly pop from STACK and add to P each operator (on top of the STACK) which has some precedence as or higher precedence than the operator encountered, (0) add the encountered operator to the stack [end of IF structure] |} Wfaright parenthesis is encountered, then : (@) repeatedly pop from the stack and add to P each operator (on top of the STACK) until a left parenthesis is encountered. (6) remove the left parenthesis (do not add left parenthesis to P] [End of IF structure] {End of step 2 loop] 0) Exit OR !) Reverse the input string | Examine the next element in the input. 1) tis operand, add it into the output string. 4) Ititis closing parenthesis, push it on stack. 5) Witis an operator, then (0) Ifstack is empty, push-operation on stack. (IF the top of stack is closing parenthesis puch perator on stack. (©) Ifithas some or higher priority then the top of stack, Push operator on s. P () Else pop the operator from the stack and add it to Eee String repeat s. from stack 'S opening parenthesis, pop operator from stac’ Pi them to's unitl 2 Fiosing pare Fthat®**4: POP and discard the closing parenthes's “eis more input, goto step 2. i (8) Ifthere is no more input, unstack the remaining operators ‘and add them, (9) Reverse the output string. Prefix form for (A*B + (C/D)-E) =(A*B+(CD)-E =(A*B+(CD))-E Let/cD=T =(A*B+T)-E =(A*B)+T)-E =((*AB)+T)- E Let * AB=U =(U+1-E =(@UN-E Let+UT=V -E VE Putting the value of V +UTE Putting the value of U =-+* ABTE Putting the value of T =-+* ABICDE ———— Prob.9 Write an algorithm to evaluate the prefix expression. [TU 20] ee Sol. Initialization 1, Read the token from input stream. (@) Ifitis an operand, push it onto the operand stack. (b) If itis an operator, push a marker onto operand stack, and push the actual operator into operator stack. Loop while (there are more input tokens) 1, Read a token. 2. Iftoken is an operator, push operator into operator stack and push the marker onto operand stack. 3, Else if, the token is an operand, check the top of the operand stack for a marker. (a) Ifthe marker is on the top of the stack, push the read operand onto the operand stack. (b) Else if- the top of the operand stack contains another operand. Loop while (the top of the stack contains another operand.) 1, Pop operand from operand stack. 2. Pop marker from operand stack and the corresponding operator from the operator stack. 3. Apply the operation on the read token and popped operand to obtain result, ‘expression has been reached, pop the SN = time and print them. ick is another operand (a) If the top of the continue looping (as stated above, in looping constraint) (yasB*c+D ecilotion sad (©) Else if the top of the stack ifan operator or | Hone —_ ee aiioa he mul the operand stack is empty, push the result | "4S . ‘current symbol | operator stack | p and exit the loop. 7 A A 4. Go back to step 1 (Loop) 2 + a A 3 B [AB a ee aE 3 Cc 7x [ABC $ + + |ABCAS 7 D + ABCARy 7 |ABCAY ——————— Prob.10(a) Convert following expression in its equivalent When the “+” is encountered in line 6 postfix expression. @ A* BC {RTV. 2015} | compared to the ‘”” on top of the stack. Since it has Gi) A* BYC+D (27.2017, 2015] | precedence, the “is popped and printed. But inte, i 2017, 2015] | pushing the “+” sign onto the stack now, We must compa Gi) A* (BYC*D) +E (RE. (@) Explain the concept of recursion using stack with a suitable example. What are the difficulties in dealing with infix expressions? (RIU. 2015] vith the new top of the stack, the ‘*”. Since the operator, has higher precedence than the ‘+, it also must be Pond if and printed. Now the stack is empty, s0 the “can be prea iy onto the stack. OR Define the concept of recursion using stack using suitable | (iiy 4 * (B+ C *D) +E , examples. What are the difficulties in dealing with infte caret] operator] postinaag) | expression? (REU.2017 onl a i Sol@A*B+C i A x i The order in which the operators appear is not | |2 e = A. reversed. When the ‘+” is read, ithas lower precedence than | [3 ¢ *¢_ TA 5 j the ‘**, so the ‘*” must be printed first. 4{ _B fe We will show this in a table with three columns. The 2 z + “ aoe a first will show the symbol currently being read. The second | [> € are ABE q will show what is on the stack and the third will show the | Fy > +57 ABED current contents ofthe postfix string. The stack will be written | [> ; pep |' from left to right with the ‘bottom’ of the stack to the left. | fig] ——+ $ABCD#+* current | operator postfix string MEE + JABCD* +E | |= i symbol | _ stack ABCD *+*Es] |" 1 A A bp Ff = + AS Sol(b) A typical implementation of recursion involves te} - f a stack. Each call to a subprogram generates 1 + ‘AB * (pop and print the oe ; program Bi a : activation record to contain its return address, parametes tu and local variables. The activation records are accessed iat Last-In-First-Out manner. Thus a stack is the choice of és structure, Recursion can be supported by systems and languages that use dynamic storage allocation. The procedut parameters and local variables are not bound to address until an activation record is created at run time. Thus multiple copies of the intermediate values of recursive calls to program can be supported, as new activation records a* created for them, '* before pushing the ‘+’ The rule used in lines 1, 3 and 5 isto print an operand when it is read. The rule for line 2 is to push an operator onto the stack if it is empty. The rule for line 4 is ifthe operator on the top of the stack has higher precedence than the one being read, pop and print the one on top and then push the new operator on. The rule for line 6 is that when the end of the (PSEC ER g= ic storage allocation, in isreserved al Compile time for gaan ett & tingle raced (2) Only one disk may be moved at a time. Specifically, le of a Pe seat; Ther i'n place ea only the top dak on any peg may be moved to any prodiate 'Y Fepeated nested Peg. re procure: Therefore, systems and langua, calls to (b) Atno time can a larger disk be placed on a smaller tie storage allocation cannot Support rec ‘ges with disk. se) by recursive method "ursion, lic stati Tong factorial (ong ny 4 fro 1 disks may be reduced to the following subproblems : (1) Move the top n ~ 1 disks from peg A to peg B. (2) Move the top disk from peg A to peg C: A-» C. (3) Move the top n — I disks from peg B to peg C. \ ——S—————— (| Funit Whar doyou mean ‘by Tower of Hanoi problem? || Eplain with suitable example. (RT. Jan 2016) . OR *) Explain tower of Hanoi problem. Explain using suitable dagram and example, (RTU, 2017] oR Cin the Tower of Hanoi problem be solved using neursion? [RTU.2013] ‘61 Tower of Hanoi : Suppose three pegs, labeled A, Band Cue given and suppose on peg A there are placed a finite Amber n of disks with decreasing size. This is pictured in 1 for the case n= 6, The object of the game is to move Ae disks from peg A to peg C using peg B as an auxiliary. Therues ofthe game are as follows: 1 4 ‘ i d A 5 5 Oem Gamma Fig.3 This reduction is illustrated in figure 3 for n=6. That is, first we move the top five disks from peg A to peg B, then we move the large disk from peg A to peg C, and then we move the top five disks from peg B to peg C. Let us now introduce the general notation TOWER(N, BEG, AUX, END) ‘rows. 4.8, G—a~c 0.8.4.0) ‘Toweno, 4. 0)——a=9 ih IR EBA) OWEN € Keb sone WAC AaB Towent,4/8,0——a+c PSE rowang, 2.4. 0 WER A.C. 9) rowena. ALS. "Fowen.0,.0) Fig. 4 : Recursive solution to Tower of Hanol problem for n=4 To denote a procedure which moves the top n disks from the initial peg BEG to the final peg END using the peg AUX 1s an auxiliary when n= 1, we have the following obvious solution: Ane aoe TOWER(I, BEG, AUX, END) It consists of the single instruction, BEG» END Furthermore, as discussed above, when n > 1, the solution may be reduced to the solution of the following three subproblems: (1) TOWER(N - 1, BEG END, AUX) (2) TOWER(!, BEG, AUX, END) or BEG-> END @) TOWERN - 1, AUX, BEG, END) Observe that each of these three subproblems may be solved directly or essentially the same as the original problem Cra BRIER TA, using fewer disks, Accordingly, this reduction process yield a recursive solution tothe Towers of Hanoi proj Fig. 4 contains a schematic diagram of the recursive solution for Observe that the recursive solution for n = 4 consists of the following 15 moves: A5B, A+C, BoC, A+B SA, C4B, ASB A2C,B5C, Boa’, ce BoC, A>B, A2C , BoC In general, this recursive solution requires mil moves for n disks We summarize our investigation with the folloyigg formally written procedure. Procedure : Refer to Prob.2. ——— Prob.12 (a) Derive an algorithm which converts any expression to its postfix expression. Also write algoriig which evaluates the posifix expression. (0) Write the insertion and deletion algorithms for Stack Sol.(a) Algorithm Prefix (Q,P) Suppose Q notation. This al ty % @) () so TOWER(4, A, B, C) lg (RT. 209, an arithmetic expression written in inf um finds the equivalent prefix expression, Push “)” onto STACK and add “(” to end of Scan Q from right to left and repeat step 3 to 6 fer each element of Q until the STACK is empty. Ifan operand is encountered add it to P Ifa right parenthesis is encountered push it onio STACK. Ifan operator@ is encountered , then (a) Repeatedly pop from STACK and add to P each operator (on the top of STACK) which has the same precedence as or highet precedence than @ (b) Add@ to STACK. [End of if structure] Ifa left parenthesis is encounterd, then. Repeatedly pop from STACK and add to P each operator ( on the top of STACK) until a right parenthesis is encountered, Remove the right parenthesis (Do not add the right parenthesis to P] [End of if structure} [End of step 2 loop] Exit ge ix Expression : P is Tocedure to evaluate Push x expression 7 :0 Pop (2) ‘procedure EVAL POSTFIX (f3) Print result ye get_next_charncter (E); Sol.(b)Stack : Refer 10 Prob.7. 3 /* get the mext character of expression E#/ case x of cry Prob.13 (a) Define stack as Important data structure. as aismonsand Push sino tack 5 Explain tts baste operation and implement a stack using : sxisan operator; ee ee get opemnds linked list, IR, 2015, RU. 2006, 2002, 2001) . ick S, evaluate th f qPerator and push the result inte | (b) Write algorithm, for postfix expression evaluation. Show the stack s; each step for the following posifix expression evaluation. aes” * Pop out the result fom stack $; ABT C*D— where A=2,B=1,C=2,D=2 end EVAL-POSTFIX, MeTU.201 Postfix expression evaluation step, a a re 5 Sol. (a) Stack : Refer to Prob.7, x Push a Implement a Stack Using Linked List : Stack is ; Pop(1) * | implemented and maintained using linked list Thic 0 P implementation is more sophisticated compared to the one Pop (2) ‘that uses an array, the added advantage being we can push Result=24 ae anany élements as we want, A new node is ereated by Push push () (using malloc()) every time an element is pushed in 2 Push the stack. Each node in the linked lst contains two members, prev; 4. | Array are fixed in size so | Linked list are quite current —>prev = current > next; resources must be flexible can grow to rece - consumed in advance. any size up to resource current femp; limit and each node {J current = current ~>prev; can be of differen size } 5. | Inserting and deleting an | Insertion and deletion If (temp ! = NULL) item in the array is difficult. | of a node in linked list " = . is quite easy. *head_ref =temp -prev; 6. To access a particular In linked list its tough } . element is fast because its | to find any node Assume that reference of head of following doubly linked location in memory can be | because previous node Ust Is passed to above function | <—>2 <-> 3 <> 4<— determined directly, ‘must be examined ad >5 <> 6, what should be the modified linked list after have to follow the function call? IRTU. 2015) pointers 7. | In Array there is aproblem | In linked list we assign Sol. When call the given above function it reverse the given of memory storage and | memory at runtime so dookly lnedltasdcheouput te ware because memory is | no problem as amy inked assigned into advance. 6S Pd I< 21> Hence follow Static r Memory Allocation. inked Tt canbe circular or doubly liked." “YY Linked Tist sores abi Sutra memory due to Pointer atthe last, clement. 7 follows Satie memory allocation. eversing the String qb reverse a string stack can be use nism is to push all the characters of a pid then pop all the characters from F yem. For example ‘the input string is d. The simple string onto the the stack and to} ‘Then push all the characters onto the stack till \0" is eacountered. Now if we pop each character from the stack and stack Fig. which isa reversed string. [fh Wie down the algorithm for insertion of a node ite middie of doubly linked list IRTU. 2018) Sol. Insertion at Middle location in doubly linked list Algorithm Insert tlocDIK(info, prev,next,start,end,loc,size) 1. set nloc = loc-1 , n=1 2.create a new node and address in assigned to ptr. 3.check{overflow] if(ptr=-NULL) vrite:overflow and exit 4.set Info[ptr}=item; S.if(start=NULL) set prev(ptr] = next{ptr] = NULL set start = end = ptr else if(nloc<=size) Tepeat steps a and b while(n != nloc) & —— loc=next{loc] b n=ntl [end white] next{ptr] = next{loc] prev[ptr] = loc Prev[next{loc]} = ptr next{loc) = ptr else set prev[ptr] = end next(end] = ptr set ptr{next) = NULL set end = ptr {end if] Exit, es | fy) froin HACK : Prob.9 Write an algorithm to Implement stack operation | STACK before por ‘operation using linked list. (RT. 2011) t Wh, Write down the algorithm to Important stack using Unked (xT Taq lst. MEU oy ster pop: enmen: ce | Sol. Stack Implementation t The linked represontation of a stack, commonly termed linked stack Is a stack that is implemented using asingle inked lst The INFO fold ofthe modes hold the elements of the stack and the LINK fields hold pointers to tho neighbouring clement inthe stack. The | AIMCTINN START pointer of the linked list behavesistho'TOP polntor | twee Hgewrint ‘variable of the stack and the null pointer of the last node In|, PUSH! = LINKSTACK ( » AVAIL, rue (TEM) 1 elias be oe, | mist ed Tre in proceduropustios an ITEM Into a linked sag, 4 r favalable space?) IF AVAIL NULL, than yg We USTART) OVERFLOW and Exit. {Remove fst node from AVAIL list) fet NEW := AVAIL and AVAIL = LINK (AVA Sot INFO[NEW] := 1 EM{copios FHM ing Algorithms Tonal Doviom of stack ode). Fig. |. Sot LINKINEW] = TOP {new node polite ity ion i ginal top todo in the stack}, A push operation into STACK is accomplished by orignal top not te inserting a node into the front or start of the list and a pop ol TOP » NEW {Hone op to polnt 10 the ney on is undertaken by deleting the node pointed by the nie a te operation on the linked stack STACK shown in Fig, |. Stack-Doletlon iwi POP_LINKSIACK (INFO, LINK, TOP, AVAIL, Tia STACK tee push operon ‘This procedure delctes the top olement ofa linked suk T nd assigns Ito the varlable ITEM. ’ ; {Stack has an item to be removed) =o ir a } IF TOP = NULL then write : Underflow and eat, STACK ae uh operon . SotTTEM : = INFO[TOP] [copies the top een te of stage into ITEM], Uy Sot TEMP : = TOP and TOP = LINK(TOP] way. ae wy ae | [Kemembor tho old value of the Top pointer ia Fy) ‘TEMP and reset. ; ‘TOP to point tothe next element inthe sack} The array representation if stack calls for the maintenance of a variable MAXSTK which gives the | [Return deleted nade tothe AVAIL ist] maximum number of elements that can be held by the stack. sot LINK[TEMP] « AVAIL and AVAIL = TEM Also, itcalls for the checking of OVERFLOW in the case of one push operation (TOP = MAXSTK) and UNDERFLOW in In the above example, INFO field of the nodes hold the the ease of pop operation (TOP = 0). In contrast, the linked J &lements of the stack and the LINK fields hold pointes representation of stack is free of these requirements, There | "He Neighbouring element in the stack ino limitation on the capacity of the linked stack and hen co | itcan support as many push operation (insertion of nodes) as | Pt0b.10 Discuss concepts of Head Node ln linked Ut lt the free-storage list (the AVAIL list) can support. This | Prlef with sultable example, (MEU, Jon 1d, dispense with the nced to maintain the MASSTK variable ORK and consequently on checking of OVERFLOW of the linked | Usiug sultable dlagram explain the concept of Head Node stack during a push operation, in Inked lists, (RTU. I es 8 lines 8 separate object, case of head node the previous pointer is obviously NULL ‘and last node's next pointer points to NULL. This list is @ linear one. / Head Node in Circular Doubly Linked List : it a node) of a tist i tnd a reference tne 0 Tence to null. The ‘is called the head of the list. It should node, but the reference to In circular doubly linked list the previous pointer of first node and the next pointer of last node is pointed to head node. Head node isa special node which may have any dummy data or it may have some useful information such as total ‘number of a nodes in the list which may be used to simplify the algorithms carrying various operation on the list. Various algorithms for operating upon the head node areas follows: Deletion : Removal of an element at the head of a singly linked listis relatively easy. Algorithm removeFirst() if (head == null) then ee ‘Therefore head node mark the reference to the fst without the presence of the head i 1 speration inthe linked ist, "O° 8 etnnot ‘The head node is a node which reside inked list. Sometime such extra nod, ofthe list. This node basically does not aia ofthe linked list. But it may contain woe cent tion about linked lst such as total number of nodes in Jt address of last node or some specific distinguishing *s at the beginnii leneedsto be kent = Ee in Singly Links List : fy Lin} Indicate an error: the list is Inthistype inka list only one link is used to pointto | tmp = hed ccead clement and this listis circular means that the lastnode’s | head = ok feld points to the first or head node, SpwNeten Head node in a singly link list have been shown in | size = size— 1 Insertion: Insert a new node at the head of the list is straightforward. The main idea is that we create a new node, set its next link to referto the current head, and then set head to point to the new node. Algorithm addFirst(String newData): create a new node v containing newData v.setNext(head) head size —— Prob.11 Write down an algorithm for insertion and deletion operation performed on the dequeue. IR. Jan, 2016] size +1 Fig. d Node in Doubly Link List : lo] Fe Te] He Dele lel Header ft OR Write an algorithm for dequeue and circular queue. (REV. 2012, 2010} OR What are the application of queue? Explain the algorithm ‘for insertion and deletion in circular queue. [RT.U. 2011] : Fig. __ This list called doubly because each node has two Bier previous and next pointers. The previous pointer points vious node and next pointer points to next node. Only in ‘Step 2: [Delete element from FRONT end} Pe ee VALUE: = DOTFRONT] set FRONT : = FRONT + 1; Step 3: [Delete element from rear end] set VALUE : = DQ[REAR] set REAR : = REAR ~ 1 Step 4: [process the deleted value] write : VALUE Stop 5: Exit (3) Display : ©) DisPIJQDISPLAY(N, QUEUE) Step: [check for underflow condition] if REAR = FRONT - | then : write : Queue is underflow and exit, {end of if structure) ‘Sol. Dequeue : A dequeue is a linear list in which elements ccan be added or removed at either end but not in the middle, The term dequeue is a contraction of the name double ended queue. Two types of dequeue : (1) Input Restricted Dequeue : Dequeve which allows insertion only at one end but allows deletion at both ends. (2) Output Restricted Dequeue : Dequeue which allows insertion at both ends but allows deletion only at one end. Insertion. = Deion a Front Rear Figt Application of Queue : The major application of Step 3: Repeat while i queue is in the operating system and in network. write Quevefi] (1) Operating system : Often maintains a queue of seti:=itl processess that are ready to execute or that are waiting for a [End of loop] particular event to occur. All the processess that are submitted | Step 4: Exit Circular Queue : Refer to Prob.!. Algorithm for Circular Queue : (1) Insertion Operation + ‘CQlnsert(QUEUE, N, FRONT, REAR, DATA) Step 1: [check for overflow condition) if FRONT = | and REAR =N, then write : CQ is overflow and exit. else REAR = FRONT - 1; then : Write : CQ is overflow and exit. to your processor or CPU are first taken by in a queue and then processed as various algorithm. (2) Network: Similarly on a network if a number of users wants to access a resource their request is taken in a queue and then processed. (3) Print server : Maintains a queue of print jobs. (4) Disk server : Maintains a queue of disk input/ output request. (5) Scheduler (c.g. in operating system) : ‘a queue of processes awaiting a slice of machine time. Avi re fu cas DOINSERT (QUEUE, N, FRONT, REAR, DATA). | St? 2! [Perorm inseition] Bion 2h fehens cover oe onan| Set FRONT = 1, REAR := 1 sri BQ OVAELOW aif . Step 2: [chek the vale of FRONT) ee pREARTN and FRONT> 1stea; = nin ZS ERONT 1 set COREAR] = DATA set REAR : = REAR + | f else vite : Insertion is not possible from rear end and exit. [End of if structure] Step 3: Exit (2) Deletion operation + DQ Delete (N, QUEUE, FRONT, REAR) ‘Step 1: [Check for underflow condition] if REAR = FRONT |, then : write : DQ is UNDERFLOW and exit [End of if structure] CQ[REAR] : = DATA [End of if structure] Step 3: Exit (2) Deletion Operation : Refer to Prob.3. Step 1: [check for empty condition] if FRONT = 0, then : write : CQ is empty and exit [end of if structure) BE reckitrene s greater than if EAR> = FRONT, then ; gti: = FRONT Repeat while i<=REAR write : CQL] getiszitl [End of loop] , Else + et i= FRONT Repeat while i<= size ite : CQLi] setizzitl [End of loop] seti:=] Repeat while i<=REAR write : CQL) fend of oop] 1d of loop] vend of it sructue) p4: Exit. FRONT) = 12 What is dequeue? Write down ; the algorithms ihe insertion and deletion operations performed na om IRTU. Dee. 2016) ou Double-Ended Queue : A double-ended queue is an data type similar to an simple queue, itallows youto xt and delete from both sides means items can be added deleted from the front or rear end, peleion Insertion a Rear ad gorithm for insertion at rear end Sep -1: [check for overflow] if (tear =MAX) print (“Queue is Overflow”); ms Sep -2: [insert element] Tear= rear +1; g{rear] = no; [set rear and front pointer] If rear rear iffront=0 front = 1; ep 3: return Algorithm for Deletion from front end Step -1 : (check for front pointer] iffront=0 print ("Queue is Underflow”); retum; Step -2 : [Perform deletion} else no = q{front}; Print (“Deleted element is”, no); {Set front and rear pointer] if front = rear front else front = front +1; Step -3 : Retum Linked-List Representation of Dequeue Insertion Step 1: [check for overflow condition} If Rear = size and front = 1, then; Write : DQ is overflow and exit [End of if structure} [check the value of front] iffront> 1, then : set front : = front — 1 set DOQffront] : = Data else ‘ite: Insertion is not possible from end and exit. End of if structure, [check the value of Rear] if Rear next)t fein , mead ->data): me tary, gorithm 1 Doubly Linked List Insert ib | (Het, dataln) data into a doubly Finked list, structure to a valid list datain contains the data to be Inserted /e boon inserted in sequence 1; succousful 2: falled ~ duplicate key presented 1 return 0 Locate insertion point in list, (list, predecessor, successor, dataln key) { allocate new node 2 move dataln to new node Inserting before first node or into empty list J set now node back pointer to null 2 net new node fore pointer to list head 3 fet list hond to new node Aolue Ingerting into middle or end of list te 1 not new node fore pointer to predecessor fy pointer ! 2 sot now node back pointer to predecessor 5 Send if Me “Tost for insort into null lst or at end oflist | 6 (predecessor fore null) 2 Inserting at end of list ~ set roar pointor Tel Tolse h Inserting in middle of list -- point successor tonew | | not successor back to new node Jen Bond if Iie 9 sot predecessor fore to new node ad 10 return 1 Le Algorithm to delete from a cireular linked list. ry) (value) : Start Step 2 : Set LOC = search (value) kal the search module to search the location ofthe node to ‘be deleted and assi 10 LOC pointer Step 3: IFLOC =NULL goto Step 4 else goto Step 4 : Return (“Delete operation unsuccessfi Ot present”) a ep 5 : IF LOC=FIRST 6 else goto Step 11 UCheck ithe element robo deleted isthe he clement inthe Step 5 Element FIRST=LAST goto Step 7 else goto Step 8 {Check if there is only one element in thelist Step 7 : Set FIRST=LAST=NULL and goto Step 10 Step 8 : Set FIRST=FIRST-> NEXT (Reset the FIRST pointer Step 9 : Set Last>NEXT=FIRST ‘TLink the last node with the updated FIRST pointer Step 10: Return ("Delete operation successful") and Stop Step 11 : Set TEMP=LOC-1 ‘Assign the location of the node present before LOC to ‘temporary pointer TEMP Step 12 : Set TEMP.> NEXT=LOC->NEXT cate TEMP node with the node being currently pointed y Step 13 : ILOC=LAST goto Step 13 else goto Step 15 Check if the element to be deleted is currently the last element in the list ‘Step 14 : Set LAST=TEMP ‘Step 15: Set TEMP>NEXT=FIRST Create circular link Step 16 : Retum ("delete operation successful”) thm : Doubly linked list delete cert deleteDbI (list, deletenode) gorithm deletes a node from a doubly linked fi r Docaules dracacu ena ee | celeteNode is pointer to the node to be deleted si node deleted i(deleteNode null) |abor (“Impossible condition in delete double”) hed if bif(deleteNode back not null) Step 17: Stop Point predecessor to successor ‘Sol.(b) Explan fun () prints the given Linked List in 1 set predecessor to deleteNode back reverse manner. For Linked List 1>2>3>425, funl() prints set predecessor force to deleteNode force So45251. ee ———___. Uplate head pointer Prob.15 (a) Hrite an algorithm to insert a data item in a 1st list head to deleteNode force circular queue, Seti (8) How will you use arrays for multiplication of polyno ‘é(deleteNode fore not null) mials? Explain, [RTU, 2014) Point successor to predecessor Ist successor to deleteNode force 2set successor back to deletenode back Telse int rear to predecessor ™ I setlist rear to deleteNode back Sol.(a) Circular Queue : Refer 10 Probl. Sol.(b) Polynomial Multiplication Consider a polynominal a(x) of degree n Vedi A(X) =a, +4,x+0,x7 +...40,x" Sneycle (deleteNode) Itis assumed that a, # 0 (because the polynomial is of “aideleteDb1) degree n-1 otherwise), Here we describe the problem of Set Front = 0 Let a(n ay 49,8 4? Ht ag ‘Set Rear = 0 else ifrear = (Size ~ 1) then Set rear = 0 else set rear = rear +1 id value (data) at rear end Set Item [queue(rear)] = data ‘Step 3 + Return, Nov, we sve equivalent Ccade for INSERT ¢@ algorithm as i Void QINSERT (queue *(Q, { DOR) = by HBX +B AR? +t BAX™ ‘The product x)b(x) is (m+ n) degree polynomial defined By BDI) = O(n) = 69 + 6X + 02 +o. + gn, where Sm Med 6= a,b 400, = Ab, +4), 44,6, 6 ab +, ‘multiplying two polynomials of degree n and m, Step 1 : If Front =~ I then RV Step 2: data)) Heom==-1/*itqveesiniatyempy, | ( s front=0 o where 0 k < m+n assuming that a, = 0 for i> n, and rear 0) 1 8 = 0 for j >. If we try to solve the problem straight from ) the formula foro, each can be evaluated in parallel using elseif rear == size ~ 1) mén groups of processors. In each group to caleulate¢,, we rear=0 need k processors simultaneously to work for O(log k) time, eke , rear = rear + 1; (quewefrear] = data; : amalgorithm is stated below : ) , Algorithm ST-POLY-MUL Input : A(0 : n) and B (0: m) Prob.l7 (a) What is Josephas problem? Write algoriy to ereate circular list and delete from circular Uist cag () What isthe significance of header in a linked ism How can a polynomial be represent in a linked let? Output Begin 1. Assign A(a + 1:n+m)=0 2. Assign B(m +1:n+m)=0 3. Fork=0to m+n do in parallel 4. Evaluate 6, = 4, 5.End parallel The Fourier Transforms can be effectively used here to evaluate the product of two polynomials in O(log(m + n)) time using only O{(m + n) log (m + n)) processors, C(O: m+n) circular list. The problem is known as the Josephus problat | and postulates a group of soldiers surrounded by ca overwhelming enemy force. There is no hope for victory without reinforcements, but there is only a single hor available for escape. The soldiers agree to determine wich of them is to escape and summon help. They form a circle and a number n is picked from a hat. One of their names is also picked from a hat, Beginning with the soldier whose name is picked, they begin to count clockwise around the circle | ‘When the count reaches n, that soldier is removed from the circle, and the count begins again with the next soldier. The| Process continues so that each time the count reaches n, Prob.16 Circular queue is to be implemented using a array of 10 elements. Write the pseudo code for implementation of inserting an element in queue and checking whether queue is empty or not. {RT.U. 2013) Sol. For inserting any clement into the circular queue first we check rear is at the (1 — 1)" position. If “rear =n — 1" then we set the value of rear to 0 and add the element at the 0 location of the array otherwise element will be added same as in simple queue. COINSERT (Q, data) a which soldiers are el jen soldier ESCAPES. ‘re input tothe program is the ‘which is the clockwise orderin soldier from whom the coi ii ine contains the string “end” j ‘The program should print th Fig: Algorithm to create circular list: CREATE (INFO, LINK, START, NULL, NEW, E) is algorithm creates a circular li TAN ANE a first position, ‘AVAILis for available memory. NULI iakT defines the starting pointer of cre ys INFO & LINK part. Step 1: [Check overflow] If AVAIL = NULL Then write OVERFLOW and Exit ‘by adding or inserting L, NEW are nodes. ular list. Each node Step2: Set NEW: = AVAIL Set AVAIL: = LINK [AVAIL] Step3: Set INFO [NEW]: = NAME Step4: Set LINK [NEW] Step 5: Deleting from a DELETE (INFO, LINK, START, NULL, LOC) This algorithm deletes node from first position of lis. Cis temporary memory node. Step 1: (Check Underflow] If START = NULL Then write UNDERFLOW and Exit Set LOC: = START Set START: = LINK [START] Set LINK [LOC] : =AVAIL Set AVAIL : = LOC Step4: Exit. 5.) Significance of Header in a Linked List: A header it isa special dummy mode found at the font of the list. ‘st of header node is an alternator to remove the first ina list, Header linked lists are frequently used for maintaining alsin memory. The header node plays an important Step2: Step3 ‘ated from the circle and ‘Number n and a list of Bof the circle, beginning unt is to start. The last indicating the end of the '€ names in the order in Part in this representation, since it is needed to represent the zero polynomial. This representation of polynomials will Presented in the context of a specific example. Representation of Polynomial: Polynomials can be Tepresented in the linked list. To understand this we take an example, iminated ° Exampl dey es cnn and enamel wits Late) denos ihe fllowing polynomial in one variable tor Linked (containing four nonzero terms) : p(x) = 2x®- 5x7 ~ 3x? + 4 se is one in which last node has the address of first |. 1h" P(%) may be represented by the header list pictured i yer isno NULL character in this link list™ | in fig(a), where each node corresponds to a nonzero term o (x). Specifically, the information part of the node is divided into two fields representing, respectively, the coefficient and the exponent of the corresponding term and the nodes are linked according to decreasing degree. Observe that the list pointer variable POLY points to the header node, whose exponent field is assigned a negative number, in this case the array representation of the list will require three linear arrays, which we will call COEF, EXP and LINK. One such representation appears in fig-(b). POLY Coefficient of term Exponent of term (alt @) COEF EXP LINK ifo] Ey] B] 2 5 Poy [i 3[2] [a] [a 4s] [7] [e AVAIL. ] = of] [2] [7 a4] fo] G 3 9 | | [eo (b), Fig. : p(s) = 28 S2— 302-44 Prob.18 Explain representation of link list in memory. Sol. Representation of Linked Lists in Memory Let LIST be a linked list. Then LIST will be maintained in memory, unless otherwise specified or implied as follows. First of all, LIST requires two linear arrays — we will call them here INFO and LINK-such that INFO(K) and LINK(K) contain, respectively, the information part and the nextpointer field of a node of LIST. LIST also requires a variable name- such as START-which contains the location of the beginning of the list, and a nextpointer sentinel-denoted by NULL-which, indicates the end of the list. Since th Ftho arays INFO and LINK will usually be positive, we will choose NULL = 0, unless otherwise stated. ‘The following examples of linked lists indicato that tho ‘nodes of list need not occupy adjacent aloments in the arrays INFO and LINK, and that moro than ono list may be maintained in the same linear arrays INFO and LINK. However, cach list must have its own pointor variable giving the location of its first node, INFOLINK ‘FE af]: stant [>] fel afr Prob.i9 Explain stack Implementation, Sol Stack Implementation : A stack can be implemen in memory in two ways. (a) Static implementation (using arrays). (b) Dynamic implementation (by linked list us pointers) 1. Static Implementation : Static implementation of uses arrays (0 represent stack in memory. Stu implementation of stack is very simple method but this meth} does not provide Nexibility because as the size of stack hy to be declared then there will no change in size afler progaa design. PusH op (austin) f (eiaon) oP 2 Fig. Examples Figure (1) pictures a linked list in memory where each the actual list of characters, or, in other words, the string, as follows: START = 9, so INFO[9] = N is the first character, LINK[9] = 3, so INFO[3] = O is the second character. LINK[3] = 6, so INFO[6] = O (blank) is the third character. LINK(6] 11, so INFO[11]=E is the fourth character. 7, 80 INFO[7] = X is the fifth character. LINK[7]= 10, so INFO[10] = Lis the sixth character. LINK[10]=4, so INFO[4] = Tis the seventh character. LINK[4] = 0, the NULL value, so the list ha ended, In other words, NO EXIT is the character string, Example Figure (2) pictures how two lists of test scores, here ALG and GEOM, may be maintained in memory where the nodes of both lists are stored in the same linear arrays TEST and LINK. Observe that the names of the lists are also used as the list pointer variables. Here ALG contains 1, the location of its first node, and GEOM contains 5, the location of its first node. Following the pointers, we see that ALG consists of the test scores. Prob.20 Explain Round Robin schedating. * Process of deleting an e PON kis called POP im ote : TOP is a pointer for stack F the top element in the stack. SUXSIZE 1: It refers to the foot forallcaion, Implementation : Dynami . pe list so it called linked tice ee 00 Of pH in this implementation we usec seqneee ot gt mh the stack. Dynamic rep ies ore eae for storing data, ane is never full as long as the systems a ic memory allocation, 4s enough io wwe have list of element L = < gatinked list representation of stack ig See ee Sol, Round-robin (RR) is one of the algorithms employed by process and network schedulers in computing As the term is generally used, time slices (also known as time quanta) are assigned to each process in equal portions and in circular from the Top Which is used to maximum size of the The name of the algorithm comes from the round-robin Principle known from other fields, where each person takes ‘an equal share of something in turn. Process Scheduling To schedule processes fairly, a round-robin scheduler ‘generally employs time-sharing, giving each job a time slot or ‘quantum (its allowance of CPU time), and interrupting the Job if it is not completed by then. The job is resumed next time a time slot is assigned to that process. If the process terminates or changes its state to waiting during its attributed ‘time quantum, the scheduler selects the first process in the ready queue to execute. In the absence of time-sharing, or if the quanta were large relative to the sizes of the jobs, a process that produced large jobs would be favoured over other Processes. Round-robin algorithm is a pre-emptive algorithm as the scheduler forces the process out of the CPU once the time quota expires. For example, ifthe time slot is 100 milliseconds, and Jobl takes a total time of 250 ms to complete, the round-robin scheduler will suspend the job after 100 ms and give other Jobs their time on the CPU. Once the other jobs have had their equal share (100 ms each), jobl will get another allocation of CPU time and the cycle will repeat. This process continues until the job finishes and need no more time on the CPU. Job = Total time to complete 250 ms (quantum 100 ms) 1. First allocation= 100 ms 2. Second allocation = 100 ms 3. Third allocation = 100 ms 4. Total PCU time of job1 = 250 ms Consider the following table with the arrival time and execute time of the process with the quantum time of 100ms to understand the round-robin scheduling. a,b,c,d_h> Bivenas: Fig. : Linked lis representation of stack INthe figure TOP holds the address of topmost node sock. Stack is initialized by setting variable “TOP” value NULL. The structure for the LIFO data structures stack is as bons in C-language. typedef struct and stack_link ( intelement; struct stack link *next; ) *stack; (G-Tech. ( Sem) C8. Solved Re my) PO gets comp rocess Arrival time Execute time 695 | ps[ Pa so PS gets “ted] Process name o 250 processed i / 170 PS gets ! 4 3 ~__15 745 [ea so Pa get = 2 190 100 processed i P4 gets complesy) Pa 210 a 5 gets compleigy PS. 350, Execute Py Se cael in || Prob.2i Explain advantages and disadvantages of time Se | () Singly Linked List ? PO arrives a ot gets processed (i) Doubly Linked List 30 |[ro[ Pr PI arrives and (iii) Circular Linked List waits for quantum a a Sol (i) Singly Linked List : Refer fo Prob.2, me 100ms expires, so | | (ji) Doubly Linked List PO is forced out of ‘Advantage : . [CPU and PI gets 1. We can traverse in both direction ie. from starting, processed end & as well as from end to starting. 130. |[riTro[r2 eames Itis easy to reverse the linked list. 150 PS arrives 3. If we are at a node, we can go at any node, But iy zi ater FT0 linked list, itis not possible to reach the previous node next 100ms °° |(eoTreTeoTr expires, so Pl is Disadvantage = forced out of CPU || 1, It requires more space per space per node because and PO gets extra field is required for pointer to previous node, essed 2. Insertion and deletion take more time than linear lnk 210 |[poTp2[P3| PI] Pa PA arrives: list because more pointer operations are required than linear linked lst. 300 Next 100ms_ po [rs| pif ra] PO expires, so PO is || (ili) Circular Linked List forced out of CPU ‘Advantages : and P2 gets 1. If'we are at a node, then we can go to any node, But processed, in linear linked list it is not possible to go to previous 350 | [P2[P3 [Pi] Pa | PO Ps] [PS arrives node. 375 |[pa[ri[Pa[Po]P5] [PZ getscompleted,|| 2. It saves time when we have to go to the fist node Fe] lop acts from the last node. It can be done in single step because processed there is no need to traverse the in between nodes. Bu 475_|Tr pa] POTS PS gets completed, in double linked list, we will have to go through in so Pl gets between nodes. cessed Disadvantages : 545° [pay po]Ps Pi gets completed, | 1, It is not easy to reverse the linked lis so P4 gets 2 P —_ Frocse * Proper cares not taken, then the problem of infinite 645 |Tpolps| pa (Quantum time loop can occur. 100ms expired, so |] 3 Iweat anode and go back tothe previous node then PA ts forced out of ‘We can not do it in single step. Instead we have to L ; ICPU and PO gets complete the entire circle by going through the in processed between nodes and then we will reach the required OOOO * reset inning * ae ome to the beginning */ Printf(“\n status of the linked lis is\n"), os (temp != 0) a ons over singly linked list, Printh(“Yed=>™, temp->num); (a) create count++; (p) Traversal 1 P= Emp > pe; ion of node at men Se sPecfed cation | print-nuLiay, RU, 2018) PrintfNo. of nodes in the list = %d\n", count); tea Linked Listana | Sol(c) uereerame for Insertion at Location in Linear Linked * Hinclude Hinelude #include yi struct Node y the Elements in the List intinfo struct Node *next; node; Void createsig(node** nt Void insertAtloc(node * Void display(node *); Yet uct node NODE; NODE thead, *first, *temp = 0; void main() intch, item, pos,loc,i; node *start start = NULL; stile (choice) clrsex(); print{(“Enter number of node:”), By} hed = (NODE *)malloc(sizeof(NODE)); scanfl"%ed”, &i); fous} Printf(“Enter the data item\n”); createsig( start, seanf(‘%d", &head-> num), printf(“\nThe listis:”); if fist = 0) display(start); printf(“\nEnter the loc :"); scanf(“%d”,&loc); printf(“\n\nEnter the item to be inserted at loc. se seanf(“%ed item); insertAtloo(&startjtem,loc,); printf(“\nNow the list is : "); display(start; etch); first= temp = head; ) fush(stdin); Fint{“Do you want to continue(Type 0 or 1) in"); seanf(“%d”, } Void createsig(node **start,int i) { intitem k=1; while(i) {ode *ptr,*las; printf(“\nEnter the info for node %d :k); seantt"%d", item); ptr=(node*)malloc(sizeof{node)); pin infomitem; ptr>next=NULL; Meret) } else {last = *start; while(last>next = NULL) {last=last>next; ) last >next = ptr; “start = ptr ; { il; ptr=(node*)malloc(sizeof{node)); ptr>info-item; loc = *start ; ‘if(*start=NULL) { ptr->next = NULL ; start = ptr ; ) else if{i<=k) { while(n != i) loc=loc->next; nt; } ptr->next = loc->next ; loc->next = ptr ; } else last = *start; while(last->next != NULL) {last=last>next; } Jast->next = ptr; } void display(node *start) i { printt(%t %d",start> info); start = start->next; } } Prob.23(a) Write the algorithm for Insertion and qe)! in doubly and circularly connected linear tine | MTU ays oR What is doubly linked list? Explain the algorithy, inserting a node and deleting a node froma doubly list (RTU, Dex any (0) Write down the following polynomial. Sx! — 2x? + Sx — I by a linked list. jay», ny = é: ‘Sol.(a) Doubly Linked List: A doubly linked lis is oe allows each node to have two pointers, one to the next node, the list and another to the preceding node. . ett a5 Insertion into a Doubly Linked List : Fig show] the schematic representation of various cases of insertion a node into a doubly linked list. Let us consider the alg rithms of various cases of insertion. Insertion of a node at the front:The algorithy : INSERT_DL_FRONT defines the insertion operation in doubly linked list. op for (a) Insertion at the front G0 HEADER OTS (b) Insertion at the end HEADER a} (ESGCI h > 00, HEADER NEW (0) Insertion at any intermediate position lg. Insertion of anode at various postions ina doubly ihn INSERT. DL_FRONT fen the data content of the ma be inserted wt: Adouble linked list sn oemgdata as X atthe front, | THe with w node Else Print "Unable toallocate memory: Insertion is not Possible” ta structure : Double linked fi 7, Endi | gets the Healer node is HEADER STN Whose | 8: Stop. °F ‘aes Tnsertion of Swans Ruin UPoint to th Algor INSERT DL ANY aoe ae ted New + GETNODE(NODE) //Availanen eat tode listat any position, memory banker? om the {iterithm INSERT_DL_ANY(X, KEY) “yen eNULL) then At nena arittut X be the data content ofthe node tobe inserted entLINK = HEADER (Newly inserted | node ben cans coment of the node afer which the new le inserted. fon ie header as } in Outp double linked list enriched with a node HEADER.RLINK = new //Head . conining ta as X after the node with data KEY, if any. ler now points tothe | _ Data structure: Double linked list structure whose . New node as 2in fig, Pointer tothe header node is HEADER. pen RLINK = PTR See the change in point Steps! . . shown as 3 in figure @®) wht PTR = HEADER pIRLLINK = new “See the change in pointer 2. While (PTR.DATA » KEY)//Move to the key node if shownasd intigac and (PTRRLINK » NULL) the current node is not the wenDATA X node /Copy thedatantegyly | PTR" PIRRLINK KEY node or list reaches inserted ¥ “ at the end q the 3. EndWhile Print“Unable to allocate memory: Insertion i not posible” 4. new = GETNODE(NODE) //Get a new node from the ifs. Endif loop 5 iffcsws pool of free storage _ 4 Sup. «(mew = NULL) then //When the memory is not Insertion of a node at the end: The algorithm nana? ps DL_END is to insert a node at the end into a double 6 a HQuit the program: Algorithm INSERT_DL_END(x) 7. I(PTRRLINK = NULL) //if the KEY node is at the Input : X, the data content of the node to be inserted, | fundiinthe list end or not Output : A double linked list enriched with a node | ‘ReN-LLINK = PTR seaaining data as X at the end of the list. mo See Miauert a ia ond Data structure : Double linked lis 4 a . pinerio the header node is HEADER. | BEDATA=X ‘0Copy the informationto ‘pe: the newly inserted node ps: 8. Else The KEY is available |. Pr= HEADER PTRI=PTRRLINK —_//Next node after the key 2 While (PTR.RLINK ¢ NULL) //Move to the last node node do PTR = PTR.RLINK newLLINK = PTR Change the pointer shown 1, EndWhile LINK - as 2 in figure (c) H |. New = GETNODE(NODE) //Avail a new node BLES TTR bri arrenlaniall 4. If(new * NULL) then //f the node is available PTRRLINK = new Change the pointer shown mewLLINK = PTR ‘//Change the pointer shown as | in figure (c) as lin figure (b) PTRILLLINK = new //Change the pointer shown FIRRLINK = new Change the pointer shown as3 in figure (c) as? in fig. (0) PTR = new (This becomes the current tewRLINK* = NULL //Make the new node as neds the last node new.DATA = X //Copy the content to the tew DATA = X //Copy the data into the newly inserted wode new node | The Igorithm is as under: Igorithm DELETE_DL_FRONT( ) Input: A doubly linked lst with data. ‘Output: A reduced doubly linked list. Data structure: Doubly linked list structure whose pointer to the header node is HEADER. Ste 1, PTR = HEADER.RLINK _//Pointer to the first node 2. If (PTR = NULL) then //f the list is empty Print “List is empty: No deletion is made” Exit Else PTRI = PTR.RLINK ‘/Pointer to the second node HEADER.RLINK = PTRI /Change the pointer shown ‘as | in figure (a) Mf the list contains a node after the first node of deletion PTRI .LLINK = HEADER //Change the pointer shown as 2 in figure (a) Tf , Ne ea FS emma (0) atone nat [Tk 4] (21am eo Fig. : Deletion at varlous positon In a double linked tst Endif RETURNNODE (PTR) //Return the deleted node to the memory bank 4. End If loop 5. Stop Note that the above algorithm will work even ifthe list isempty. Deletion of a node at the end of a double linked list: The algorithm is as under: Algorithm DELETE_DL_END( ) Input: A double linked list with data, Output: A reduced double linked lis. Data structure: Double linked list structure whose pointer to the header node is HEADER. Steps: 1. PTR = HEADER 2. While (PTR.RLINK + NULL) do //Move to the last node PTR = PTR.RLINK 3. EndWhile If (PTRI = NULL) Deletion of a node at the front of a doubly linked list : 7. Else 8 9. . IF(PTR = HEADER) then Ifthe Fists emp Print “List is empty: No deletion is made” Exit MQuit the program, 5. Else PTRI = PTR.LLINK ‘Pointer tothe lestbut, node PTRLRLINK = NULL change the pointe, as Lin figure (b) RETURNNODE(PTR) —_//Retum the node oy. ‘memory bank 6. Endif loop. 7. Stop. Deletion of a node at any position in a double list: The algorithm is as follows: Algorithm DELETE_DL_ANY(KEY) Input: A double linked list with data, and KEY, the gg, content of the key node to be deleted, Output: A double linked list without a node having day content KEY, if any. Data structure: Double linked list structure who pointer to the header node is HEADER. Step: 1. PTR = HEADER.RLINK 2. If (PTR = NULL) then Print “List is empty: No deletion is made” Exit 3. Endif Quit the program 4. While (PTR.DATA KEY) and (PTR.RLINK * NULL) do PTR = PTR.RLINK 5. EndWhile 6. If (PTRDATA = KEY) then //If the node is found PTRI = PTR.LLINK ITrack to the predecessat node UFTrack to the suecessor node JChange the pointer IMF the deleted node isthe last node //Change the pointer link Move tothe First node Move to the desired node PTR2 = PTRRLINK PTRLRLINK = PTR2 If(PTR2 » NULL) then PTR2.LLINK = PTRI Endif RETURN NODE(PTR) ‘Return the free node to the memory bank Print “The node does not exist in the given list” End If loop, Stop. Ez Linked Li “rhat means circular inked list jg sqsstexcept thatthe lst node points to Step 2: Stop 3: lar to the single : the first node in pest Step 4: Step 5: ina circular linked list, we perform the following tions ? ee insertion 2, Deletion 3. Display isertion Inacircular linked list, the insertion operation can be med in three ways. They are as follows : Step 6: Step 7: i) Inserting at Beginning of the list step 8 {@ Inserting at End of the list {@ Inserting at Specific location in thelist Step 8: Inserting at Beginning of the list Algorithm Create a newNode with given value, Check whether list is Empty (head = NULL) Ifitis Empty then, set head = newNode and newNode"Inext = head If it is Not Empty then, define a Node pointer ‘temp’ and initialize with ‘head’, eco ee Linked list, every nod (Ul) Insert ft pr insingle le points to its ing at Specific location in the list (After a senie and the last node points NULL. Bey thei © | Node) fia, ever node Pontos next nodoin he wontene Algortihm: ye last ode points ‘0 the first node in the list, Step 1: Create a newNode with given value. ‘Check whether list is Empty (head = NULL) If it is Empty then, set head = newNode and newNode -> next = head. Ifitis Not Empty then, define a node pointer temp and initialize with head. Keep moving the temp to its next node until it reaches to the node after which we want to insert the newNode (until temp —> data is equal to location, here location is the node value after which we want to insert the newNode). Every time check whether temp is reached to the last node or not. If itis reached to last node then display ‘Given node is not found in the list!!! Insertion not possible!!!” and terminate the function. Otherwise move the temp to next node. If temp is reached to the exact node after which we want to insert the newNode then check whether it is last node (temp —> next — head). If temp is last node then set temp —> next = newNode and mewNode -> next = head. If temp is not last node then set newNode —> next = temp > next and temp —> next = newNode. 2. Deletion In acircular linked list, the deletion operation can be performed (i) Deleting from Beginning of the list ii) Deleting from End of the list (iil) Deleting.a Specific Node three ways those are as follows : Sup 5: Keep moving the ‘temp’ to its next node until it | () Deleting from Beginning of the list reaches to the last node (until ‘temp -> next ‘Algorithm: Mead ne tahead’, ‘heaa = | StP 12 Check whether list is Empty (head == NULL) pens: Set Roa eee est ere Ma Step 2: If it is Empty then, display ‘List is Empty!!! new Node! .s00. emp Deletion is not possible’ and terminate the i) Inserting at End of the list Alogrithm: : Create a newNode with given value. Check whether list is Empty (head = NULL). If it is Empty then, set head = newNode and Step 3: Step 4: newNode —> next = head. > [Sep 4: If it is Not Empty then, define a node | crop 5; pointer temp and initialize with head. t [Sep S: Keep moving the temp to its next node until it | sy 6, reaches to the last node in the list (until temp > next == head). ; Sep 6: Set temp —> next = newNode and newNode —> Bisp 7 next = head. function, If it is Not Empty then, define two Node pointers ‘temp1” and ‘temp2? and initialize both ‘templ” and ‘temp2” with head. Check whether list is having only one node (temp1 > next == head) If it is TRUE then set head = NULL and delete temp] (Setting Empty list conditions) Ifitis FALSE move the temp] until it reaches to the last node. (until temp -» next = head ) Then set head = temp2 —> next, temp1 —> head and delete temp2. © rig shows a schematic diagram of a queue with 4 ont \anere AAA is the FRONT element and DDD is ment. Observe that the FRONT and rear elements : woe queve are: also, respectively the first and last elements wearer suppose an clement i deleted from the queue. . oy 5 m Suppose we wantto insert an element ITEM into a quet pen it must eres ns veld the queve in figure (b), | at the time the queue does occupy the last part of the array tamer ie HONT em es yon | hen REAR On 0 a cen "MONT queue. | ihc cntire queue tothe begining ofthe array, changing Pee as above. tnd REAR accordingly, and then inserting ITEM This procedure may be very expensive. Algorithm for Insertion QINSERT(QUEUE, N, FRONT, REAR, ITEM) ‘This procedure inserts an element ITEM into & queue. 1, (Queue already filled?) If FRONT = | and REA! REAR + 1, then: ‘Write: OVERFLOW, and Return. 2, [Find new value of REAR] IfFRONT:=NULL, then: [Queue initially empty] ‘Set FRONT:= | and REAR==1. ia ey must be added at the rear of the queue, as pictured Thea) Note that FFF is now thera element Now ifn other element ib deleted from the queue he it "228 BB, o yield the queue in igure (2) and on : n of Queues Representati Queues may be represented in the computer in two R =N, or if FRONT = ways ‘ 1. Array Representation 2 Linked List Representation Fach of our queues will be maintained by a linear array QUEUE and two pointer variable FRONT, containing the (ihion of the FRONT element of the queue; and REAR ithe location ofthe rear element ofthe queue.The A = | oa! s | endion FRONT ~ NULL will indicate that the queue is Else if REAR = N, then: ig eoPey- Set REAR:= I. Figure? shows the way the array in figure will be stored ae: yf omemory using an array QUEUE with N elements. Fig.2 iboindicates the way, elements will be deleted from the queue Set REAR := REAR + 1. tad the way new elements will be added to the queue. [End of If structure. 4 Observe that whenever an element! deleted from the queue, 3, Set QUEUE[REAR] := ITEM. [This inserts new feuslue of FRONT is increased by 1; this can be | clement] i} inplemiented by the assignment 4, Return. = = * . FRONT: = FRONT*] Algorithm for Deletion QDELETE(QUEUE, N, FRONT, REAR, ITEM) ‘This procedure deletes an element from a queue and assigns it to the variable ITEM. 1, (Queue already empty?) If FRONT :=NULL, then: Write: UNDERFLOW, and Return. 2. Set ITEM := QUEUE[FRONT]. Similarly, whenever an element is added to the qveve; evalu of REAR is increased by 1; this an be implemented ly the assignment REAR:=REAR+ This means that after N inse tte queue will occupy QUEUE| fveatually the queue will occupy the This occurs even though the queue its ements, tions, the rear element of [N} oF, in other words last part of the array. elf may not contain See AS [Find new value of FRONT: If FRONT = REAR, then: (Queue has only ‘one element to start.] Set FRONT := NULL and REAR := NULL. Else if FRONT =N, then; Set FRONT=1. Else: Set FRONT: = FRONT + 1, (End of If structure,] 4. Return, Prob.2S (a) Write an algorithm to insert an element Into a single linked list. IR-TU, 2013, RU. 2006) (b) A doubly linked list can be made circularly by setting ‘the values of links in the first and last nodes appropriately. Discuss the advantage and disadvantages of circular doubly linked list in doing the various list operations. (RIEU, 2013 Sol. (a) Insertion into Single Linked List be inserted into a linked list in 3 ways, First one isto insert a node at the beginning of the list. Second one is to insert a node after the node with a given Jocation and third one isto insert a node into a sorted lst. ‘We assume that the linked list is in memory in the form LIST(INFO, LINK, START, AVAIL) and that the variable ITEM contains the new informations to be added to the ist, | Soall of above 3 algorithms includes following steps: (2) Checking to see if space is available in the AVAIL list. If not, that is if AVAIL = NULL, then the algorithm will print the message OVERFLOW. (b) Removing the first node from the AVAIL list. Using the variable NEW to keep track of the location of the new node, means NEW: = AVAIL, AVAIL: = LINK [AVAIL] (©) Copy the new information into the new node: INFO [NEW]: = ITEM Diagramatically 2A node may py Lo Ceo Ze tion at the boginnt o 1) Case 1 1 fn in a i we repronent itay "8g cop ofr |} Fig. 2: Insertion at tho begtnig of «ty, Algorithm INSFIRST (INFO, LINK, START, AVAIL, rrpyy (This algorithm inserts a node athe begining oy) 1, (OVERFLOW?) If AVAIL = NUj Write: OVERFLOW and Exit. [Remove first node from AVAIL list) SetNEW:= AVAILand AVAIL: = LINK fay Set INFO [NEW]: = ITEM (Copies new day! mew node) Set LINK [NEW]: original first node) 2, 3 = START (New node poig, 5. Sot START: = NEW (Changes START so jt po, to the new node) 6. Exit (2) Case II : Insertion after Suppose we are given the locat inserted, If LOC = NULL then new node N is inserted as ty first node in the LIST elso node N points to a node wha as originally followed by node of location LOC. We a | LINK [NEW]: = LINK [LOC] LINK [LOC]: = NEW Algorithm : INSLOC (INFO, LINK, START, AVAIL, LOC, ITE4 [This Algorithm inserts ITEM so that ITEM follows node with the location LOC or inserts ITEM as the frst na when LOC = NULL,] 1, (OVERFLOW?) If AVAIL = NULL, then: Wri OVERFLOW and Exit [Remove first node from AVAIL list) ‘Set NEW: = AVAIL and AVAIL: = LINK (AVAII ‘Set INFO [NEW]: = ITEM [Copies new data ini new node] IfLOC = NULL, then: [Insert as first node] Set LINK [NEW]: = START and START: = NEW. Else : (Insert afler node with location LOC] Set LINK [NEW]: = LINK [LOC] and LINK [LOC]: = NEW, [End of If structure] Exit, siven node : mh, where ITEM i 2 Te ‘Thus ‘The >{TEM, contain This = NULL. UST whose value is Tes ip IS) Nerse LIST by using a pointer variable PTR and - ep ‘track of the location of the preceding node by sing PO ‘0 [PTR]. a Eioeation of the node A. FIND A (INFO, LINKS, START, ITEM, LOC) inasorted list such that INFO (LOC] < ITEM, or sets LOC (011M © INFO [PEER th and Return, ! fl z tro) r 6 Qsavitn = PTE and PTR: = LINK (PF [Update pointers} [tind of Step 4 loop): 7, Sot LOC;= SAVE 8, Return 4 : u INSU CN, LINK, AVAIL» START Bho (Chis algorithm inserts ITEM into mnerEE TAT OC) rie J Sinan oS ania nae Fe CAILFIND A (INFO, LINK, START, TOM i y) Case HIT + Insertion into a sorted linked lst : 2) Call INS LOC (INFO, LINK, § ' pose ITEM isto be inverted into n sorted linked list, L0G ITEM). ist be inserted between nodes A and B so that 3, Bit. ough | ve EO (A) # doting MAX 20 Unc ataok [MAN]; At aire | MAN}, Thy us 7 sot nt) net Wf fetning the wpper Hit an ower Hi fey ay sane stuoh Apt the ilo, whieh intlontes the staok number Output jong, sets the upper! lower bone the stiok Calle Ny atermpty, still lisp ligplay: at Calls none Paramotor passing method: Hy value vt vod vot, ato (int ilo) ( lintsuin, Aino ( We ubynize(ilon) ; ) lve ( sum 05 for(i FeCinden; 1) te vlvo [Is Hy tubeaun alzolindox] ; }, full Function checks whether the stack is full lp inde chins te ack output: 1 ifstack is Full otherwise gS MDE By: main Calls : set_stack parameter passing method : By value *) jot stfull nt index) 4 cima; fet stack (inde) ; for (top= 1b; top<-ub; top+ +) | aot [top] ) teeak J op-1 0b) recur I; else return 0; a stempty Function Inchecks whether the stack is empty or not Inpat : the index, which indicates the stack number Output : | if stack is empty otherwise 0 Called By :main Calls : set_stack Parameter passing method : By value + jntstempty (int index) “{ inttop; set_stack (index) ; for (top=Ib; top<=ub; top++) { if (stack [top] ! =~ 1) return 0; return 1; } } /* push Function Input : the item which is to be pushed onto the stack Output : none Called By : main Parameter passing method : By value " for (top = Ib; top<=ub; top + +) if (stack (top) = = — 1) Stack [top] = item; retum; ) /* pop Function It pops the element from desired stack Input : none Output: item, popped element Called By : main Calls: none w int pop() { inttop, item; for (top = Ib; top<= ub; top + +) if (ack {top] ==— 1) break top-—3 item=stack [top] ; stack [top] =—1; return item ; } * display Function It displays only desired stack Input : the index, which indicates the stack umber Output : none Called By : main Calls : set_stack Parameter passing method : By value uv void display (int index) { inttop ; set_stack (index) ; for (top= Ib; top<=ub; top + +) { if (stack [top] ! = - 1) printf (“% d”, stack {top]) ; } } /* display_all Function 1t displays all the stacks in the array Input: the n, which indicates total number of stacks Output : none Called By : main Calls: set_stack Parameter passing method : By value * (oid display_all (int a) t int top, index; for (index = { pint £(* \nstack number 9% d is", index) ; set_stack (index) ; for (top=Ib; top <=ub; top ++) { if (stack [top] !=-1) printf (“% d”, stack{top]) ; } } ) |; indexc=n; index ++) 7* main Function Input: none Output: none Called By : 0.8. Calls : stfull, push, stempty, pop, display, display_all Parameter passing method : 7 void main (void) { int, index, i, item, choice; char ans; elrser () ans=‘y’; for (i= 1; i <-MAX; i stack [i] =~ 1 ;/* for of stacks * / printf (“\n\t Program For multiple stacks using single array”) ; printf (“\n Enter how many stacks are there” scanf (“%d", &n) ; printf (“\n Enter the size for each stack”) ; for (i= 1; 1 <=n;i++4) { printf (‘"n size for stack Yd is”, i) ; 4) lization of the entire array ‘case 2 : printf (“\n From Which stack?) ; index); ‘case 3 : printf‘ Which stack has to be displayede? default: printf (4 ) while (ans == ‘y’ || ans==*Y"); [4000909884 End of Program *Heeeereneee®/ printf (“\n\tt Main Menu”) ; printf (“wn 1. Push 2, Pop \n3. Display gg case I printf (\n Enter the item tobe pushes else sean (“%d”, item) ; printf (“\n In Which stacks?”) ; seanf ("%d", &index) 5 if (stfull (index) ) printf (‘in Stack %d is Full, an n0t Pushing else push (item) ; break ; seanf (“%d”, &index) ; if (stempty (inxed) ) printf (“in Stack number %d is empty! nds) { item=pop(); printf (“In %d is popped from stack %é, jen } scanf (“%d”, &index) ; display (index) ; break ; play_all(n) ; sitting") ; printf (“\n Do you wish to continues?”) ; ‘ans=getch (); } getch (); } em to be pushed10 it ge sgack?1 Wa ish continues? pron Main Menu tpisplay all peyour choices suerte iter to be pushed 20 ip Which stack?3 ou wish to continues? 2. Pop 3. Display 4. Display all Enter Your choicel Enter the item to be pushed30 In Which stack?3 Do you wish to continues? ‘Main Menu 3. Display 4. Display all Enter Your choices stack number 1 is 10 stack number 2 is, stack number 3 is 20 stack number 4 is, Do you wish to continue? stack number 1 is, 10 stack number 2 is stack number 3 is 20 stack number 4 is Do you wish to continues? Main Menu 1. Push 2. Pop 3.Display From Which stack?3 30 is popped from stack 3 Do you wish to continue? 30 30 aaa OQ Sortinas Sorting is the process of arranging the elements in some logical order. This logical order may be ascending or descending in case of numeric values or dictionary order in case of alphanumeric values. Classification of Sorting: Sorting is classified into following categories: Sorting Internal sorting Extemal sorting ‘Selection sort Bubble sort Insertion sort Mow ox Quick sor Radix sort Internal Sorting : Deals with sorting the data held in memory of the computer. External Sorting : Deals with sorting the data stored in data files. This method is used when the volume of the data is very large and cannot be held in computer’s main memory. Bubble Sort : The bubble sort is the easiest and frequently used sorting algorithm among all the sorting algorithm. The algorithm has got its name as after every pass, the largest element bubbles up and move to end of the array. In every pass of the algorithm, we have number of steps which decreases as the number of pass increases. ‘The bubble sort method requires (n — 1) pass to sort an array. In each pass every element ai) is compared with afi +1), for i=0 to (n-k), where k is the pass number and if they are out of order ie. if afi] > a{i+!], they are swapped. This will cause the largest element to move or bubble up. Thus after the end of first pass the largest element in the array will be placed in n' position, and on each successive pass, the next largest element is placed at position (n -1), (M~ 2), 2, respectively, and swap wit list. Merge sort is a sorting algorithm that uses the divide and conquer. This algorithm divides the array in two halves, sorts them separately, and then merges This procedure is recursive with the base criteria - ‘number of elements in the array are not more than 1 ith af}, and so on. (tially first element) is selected from the array of ele ‘and compared with rest of all the elements, then clement is selected and compared with rest other ele like wise this all element one at a time is compared other elements. The selection sort method also (a1) pass to sort an array. Inthe first pass, find thes element from elements a[0}, afl], af2], with the first element, ie, a[0]. In the second pass, find g smallest element from elements afl}, a(2}. a(3), Insertion Sort : This algorithm is very popular bridge players when they first sort their cards. In di procedure, we pick up a particular value and then insen ita the appropriate place in the sorted sub list, ie., during i iteration the element afk] is inserted in its proper place sorted sub array af}, a[2}, af3), accomplished by comparing afk] with afk-1}, afk-2 fk and so on until the first element aj] such that afj] < afk found. Then each of the elements afk-I), afk-2], are moved one position up, and then element afk] isin in (+1 )th position in the array. » afk-1]. This alm} and CG joTi2yi8] [4 1719 [ar Lista a0 Toren Merged List Fig Al «aff as ting algorithm that also, wi sor, uses the idea of divide and conquer. This ‘inds the element, called pivot, that partitions the ih wo halves in such a way tat the elements inthe ito My are less than and the elements in the right sub ter than the partitioning element, Then these He Srrrays are sorted separately. This procedure is Hoa nature with the base criteria - the number of the array are not more than 1, rt : A heap is type of data structure that is sto abinary tree. Heap is of two types: max heap and in max heap the parent node is greater than from g le child nodes and in min heap the parent node is of han from any of its child node. Because of the order the maximum Value of max heap is in the root me can take advantage of this situation by using a * ohelp us sort the given array having n elements. Maximum Fig.2 Algorithm for Binary Search = UST : Repregents the list of element N: Represents the no. of element in the list. ; ELEMENT : Represents the value to be search in the list. Step 1: {Initialization} set LOW HIGH FLAG Repeat through step 4 while LOW < HIGH Sep 2s and external sorting? eet Fig.3 ‘Max and min heap ‘The general approach of heap sort is as follows: From the given array, build the initial max heap. Interchange the root (maximum) element with the last element. Use reheapify downward operation from root node to rebuild the heap of size one less than the starting. Repeat steps 1 and 2 until there are no more elements. . Shell Sort : This algorithm is similar to bubble sort in the sense that it also moves the elements by exchanges. However, it begins by comparing elements that are at a distance d. With this the elements thatare quite away from their place will move more rapidly than the simple bubble sort. Further, in each pass, the value of d is reduced to half, ie. atin bn In each pass, each element is compared with element that is located d position away from it, and exchange is made if required. The next iteration starts with a new value of d. The algorithm terminates when d= 1. Step 3: Set MID : = vem nes Step 4: If ELEMENT < LIST [MID], then : set HIGH : = MID - 1 ELSE if ELEMENT > LIST [MID], then : set LOW : = MID +1 LIST : FLA write: “ELEMENT found at location’ MID. [End of if structure) [End of step 2 loop] Step 5: IfFLAG = 1, then write : ‘Element not found? Step 6: Exit. Tob.2 What ts dference between an internal sorting [REU. Jan, 2016] OR Compare Internal sorting and External sorting. (RLU. 2017] External sort tion 1 is small than 2 exchange the po eee Step2 : Now check left 10 right for bigger value ed in main memory. secondary memory. Sup send oe 2.]Ie takes input only which —/Extemal sorting ean takes put. Jean be fit into its memory fas much as larg Jeg. it takes small input. 3.]For internal sort we need [But in ease of external sort| to code a program by —_| there is no need of coding specifying the sort criteria |the program. Moreover we /and that the program need |can change the sort criteria to be compiled & linked. |just by changing sort parameters. 4 ]Less efficient. [More efficient. Step 3: No smell value found then pivot value noy stop and array divided in two part: 1 2. 9 [6 15 z Step 4 : Now take 9 as a pivot value for array 2 ang searching. The final solution of quick sorts: fai Tz 6 [97 1 [a Prob3 Apply binary search to find 123 in a list. 49, 98, 101, 123, 149, 194, 199, ‘211, 240, 286, 840, 930 (12 data) (RIEU. 2014, Prob Prove that Heap sor Merge 00) Gogh Takes Q(n log n ) tie in the worst case. Sol. Complexity of Heap Sort : To analyze the hesy ey note that complete binary tree with n nodes (where nigel less than the power of two) has log (n*1) levels. Tha each element in the array were a leaf, requiring itto be: through the entire tree, both while c heap, the sort would be O(n log n), Inthe average case, the heap sort is not a efficient the quick sort. However, heap sort is far superior to qui sort in the worst case, in fac, heap sort complexity remain O(n log n) in the worst case. Merge Sort : One natural method of sorting isto sont by repeated merging. Our analysis of mergesortis as follows, 1, The time to merge a pair of lists to get an n eleme list in O(n) is since each recursive call "retires" anf 101 and scan towards right of 101 wherefore next element between the mid [value] and END [value ie., 101 and 149 is found to be 123) Result : item = 123 search, | rar Prob.A Sort the following elements using quick sorting algorithm. <2, 10, 9, 6 1, 15, 5, > /RTU. 2018] Sol. Quick sort : C2 Te Ts Tei Ts ys to Take 2 as a pivot value: Step 1: search right to left for small value compare to pivot value if value is found then swipe the element: gE; “The most popular divide-and-conquer quick Quick caite Uisuioroouniiys H5erd cor Sorting die anon Hijea circumstances the divi ate ements into (wo eth farce q tbe log. levels of recursive calls to quicksort. 52% rch OH ‘must be done to split the array So the ing ie 1 of the order of O(n log n). Unfortunately mony i eal circumstances, although by a probabilistic or also represents an were case performance under nable ‘aysumptions, The worst case performance, , causes tH array to be split unevenly, resulting in a running time of (7), which is the worst case for 10, LIST [J + 1] = LIST (J) IIE J = 1 THEN 12, FOUND = TRUE 13. UNTIL (FOUND = TRUE) 14, LIST [1] =T erumgorithms, Ina worst-case sete, uicksort is | 1S: END een ay Mriningagaiin one 16. END mers rorling? Welle an algorlis to sort the 17. END at sing insertion sort and selection sort, What meme compres ‘for both selection and Insertion [RTU. Jen. 2016) selection sort ~ Algorithm to sort real numbers using Step 1 ~ Set MIN to location 4 ming refers to the operation of arranging sequence /.. increasing order or decreasing mie be a lat of m element P, Py in memory. es paeansarangingie contents of P either in increasing sing order. P, 2P, SP, SPs Prove P fire are m elements i thelist therefore there are m spierange them. Sorting is categorized as: 1 Internal sorting. 2. External sorting to sort real numbers usi ‘Step 2 — Search the minimum element it the list ‘step 3 Swap with value at location MIN Step 4 — Increment MIN to point to next element ‘Step 5~ Repeat until list is sorted n and Selection Sort Insertior | ion sort have the same time ‘Time Complexity for \d inserti Both selection an complexities are : 1 Wrost Case Time Coplexity : (02) 2, Best Case Time Complexity : O(0) 3, Average Time Complexity 4, Space Complexity : O11) gorithm ertion s0r0 IST{ J of N items in random order. pur: LI PUT: LIST] of N items in sorted order. to sort a Fron? Which sorting algorithms can be used ‘random linked list with min' Both Merge so! 'd lists. The slow random-access ‘makes other algorithms (such as fquicksort) perform poorly, and others (such as heapsort) aenpletely impossible. Since worst case tine complexity of Merge Sot js O(aLogn) and Insertion sort is ‘0(n72), so merge Meas preferred to sort a random linked list with minimum time complexity. “The implementation of merge sortusingrandom Linked List given below. Sol. Explan: be used for a random linke performance of a linked list | T= LIST [1] /*STORE LIST (1) */ | REPEAT /* MOVE OTHER ITEMS DOWN THE LIST.

You might also like