Presentation is loading. Please wait.

Presentation is loading. Please wait.

CIRCULAR LINKED LIST. Circular Linked List- A circular linked list is a linked list in which last element or node of the list points to first node. For.

Similar presentations


Presentation on theme: "CIRCULAR LINKED LIST. Circular Linked List- A circular linked list is a linked list in which last element or node of the list points to first node. For."— Presentation transcript:

1 CIRCULAR LINKED LIST

2 Circular Linked List- A circular linked list is a linked list in which last element or node of the list points to first node. For non-empty circular linked list, there are no NULL pointers. The memory declarations for representing the circular linked lists are the same as for linear linked lists. All operations performed on linear linked lists can be easily extended to circular linked lists with following exceptions: While inserting new node at the end of the list, its next pointer field is made to point to the first node. While testing for end of list, we compare the next pointer field with address of the first node Circular linked list is usually implemented using header linked list. Header linked list is a linked list which always contains a special node called the header node, at the beginning of the list. This header node usually contains vital information about the linked list such as number of nodes in lists, whether list is sorted or not etc. Circular header lists are frequently used instead of ordinary linked lists as many operations are much easier to state and implement using header lists

3 This comes from the following two properties of circular header linked lists: The null pointer is not used, and hence all pointers contain valid addresses Every (ordinary ) node has a predecessor, so the first node may not require a special case.

4 Algorithm: (Traversing a circular header linked list) This algorithm traverses a circular header linked list with START pointer storing the address of the header node. Step 1: Set PTR:=LINK[START] Step 2: Repeat while PTR≠START: Apply PROCESS to INFO[PTR] Set PTR:=LINK[PTR] [End of Loop] Step 3: Return

5 Searching a circular header linked list Algorithm: SRCHHL(INFO,LINK,START,ITEM,LOC) This algorithm searches a circular header linked list Step 1: Set PTR:=LINK[START] Step 2: Repeat while INFO[PTR]≠ITEM and PTR≠START: Set PTR:=LINK[PTR] [End of Loop] Step 3: If INFO[PTR]=ITEM, then: Set LOC:=PTR Else: Set LOC:=NULL [End of If structure] Step 4: Return

6 Deletion from a circular header linked list Algorithm: DELLOCHL(INFO,LINK,START,AVAIL,ITEM) This algorithm deletes an item from a circular header linked list. Step 1: CALL FINDBHL(INFO,LINK,START,ITEM,LOC,LOCP) Step 2: If LOC=NULL, then: Write: ‘item not in the list’ Exit Step 3: Set LINK[LOCP]:=LINK[LOC] [Node deleted] Step 4: Set LINK[LOC]:=AVAIL and AVAIL:=LOC [Memory retuned to Avail list] Step 5: Return

7 Algorithm: FINDBHL(NFO,LINK,START,ITEM,LOC,LOCP) This algorithm finds the location of the node to be deleted and the location of the node preceding the node to be deleted Step 1: Set SAVE:=START and PTR:=LINK[START] Step 2: Repeat while INFO[PTR]≠ITEM and PTR≠START Set SAVE:=PTR and PTR:=LINK[PTR] [End of Loop] Step 3: If INFO[PTR]=ITEM, then: Set LOC:=PTR and LOCP:=SAVE Else: Set LOC:=NULL and LOCP:=SAVE [End of If Structure] Step 4: Return

8 Insertion in a circular header linked list Algorithm: INSRT(INFO,LINK,START,AVAIL,ITEM,LOC) This algorithm inserts item in a circular header linked list after the location LOC Step 1:If AVAIL=NULL, then Write: ‘OVERFLOW’ Exit Step 2: Set NEW:=AVAIL and AVAIL:=LINK[AVAIL] Step 3: Set INFO[NEW]:=ITEM Step 4: Set LINK[NEW]:=LINK[LOC] Set LINK[LOC]:=NEW Step 5: Return

9 Insertion in a sorted circular header linked list Algorithm: INSSRT(INFO,LINK,START,AVAIL,ITEM) This algorithm inserts an element in a sorted circular header linked list Step 1: CALL FINDA(INFO,LINK,START,ITEM,LOC) Step 2: If AVAIL=NULL, then Write: ‘OVERFLOW’ Return Step 3: Set NEW:=AVAIL and AVAIL:=LINK[AVAIL] Step 4: Set INFO[NEW]:=ITEM Step 5: Set LINK[NEW]:=LINK[LOC] Set LINK[LOC]:=NEW Step 6: Return

10 Algorithm: FINDA(INFO,LINK,ITEM,LOC,START) This algorithm finds the location LOC after which to insert Step 1: Set PTR:=START Step 2: Set SAVE:=PTR and PTR:=LINK[PTR] Step 3: Repeat while PTR≠START If INFO[PTR]>ITEM, then Set LOC:=SAVE Return Set SAVE:=PTR and PTR:=LINK[PTR] [End of Loop] Step 4: Set LOC:=SAVE Step 5: Return

11 One of the most important application of Linked List is representation of a polynomial in memory. Although, polynomial can be represented using a linear linked list but common and preferred way of representing polynomial is using circular linked list with a header node. Polynomial Representation: Header linked list are frequently used for maintaining polynomials in memory. The header node plays an important part in this representation since it is needed to represent the zero polynomial. Specifically, the information part of node is divided into two fields representing respectively, the coefficient and the exponent of corresponding polynomial term and nodes are linked according to decreasing degree. List pointer variable POLY points to header node whose exponent field is assigned a negative number, in this case -1. The array representation of List will require three linear arrays as COEFF, EXP and LINK. For example: P(x)= 2x 8 -5x 7 -3x 2 +4 can be represented as:

12 POLY 028-57-3240 CIRCULAR HEADER LINEKD LIST REPRESENTATION OF 2x 8 -5x 7 -3x 2 +4 HEADER NODE WITH EXP -1 AND COEFF 0

13 Addition of polynomials using linear linked list representation for a polynomial

14 Algorithm: ADDPOLY ( COEFF, POWER, LINK, POLY1, POLY2, SUMPOLY, AVAIL ) This algorithm adds the two polynomials implemented using linear linked list and stores the sum in another linear linked list. POLY1 and POLY2 are the two variables that point to the starting nodes of the two polynomials. Step 1: Set SUMPOLY:=AVAIL and AVAIL:=LINK[AVAIL] Step 2: Repeat while POLY1 ≠ NULL and POLY2≠NULL: If POWER[POLY1]>POWER[POLY2],then: Set COEFF[SUMPOLY]:=COEFF[POLY1] Set POWER[SUMPOLY]:=POWER[POLY1] Set POLY1:=LINK[POLY1] Set LINK[SUMPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set SUMPOLY:=LINK[SUMPOLY] Else If POWER[POLY2]>POWER[POLY1], then: Set COEFF[SUMPOLY]:=COEFF[POLY2] Set POWER[SUMPOLY]:=POWER[POLY2] Set POLY2:=LINK[POLY2] Set LINK[SUMPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set SUMPOLY:=LINK[SUMPOLY]

15 Else: Set COEFF[SUMPOLY]:=COEFF[POLY1]+COEFF[POLY2] Set POWER[SUMPOLY]:=POWER[POLY1] Set POLY1:=LINK[POLY1] Set POLY2=LINK[POLY2] Set LINK[SUMPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set SUMPOLY:=LINK[SUMPOLY] [End of If structure] [End of Loop] Step3: If POLY1=NULL, then: Repeat while POLY2≠NULL Set COEFF[SUMPOLY]:=COEFF[POLY2] Set POWER[SUMPOLY]:=POWER[POLY2] Set POLY2:=LINK[POLY2] Set LINK[SUMPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set SUMPOLY:=LINK[SUMPOLY] [End of Loop] [End of If Structure]

16 Step 4: If POLY2=NULL, then: Repeat while POLY1≠NULL Set COEFF[SUMPOLY]:=COEFF[POLY1] Set POWER[SUMPOLY]:=POWER[POLY1] Set POLY1:=LINK[POLY1] Set LINK[SUMPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set SUMPOLY:=LINK[SUMPOLY] [End of Loop] [End of If Structure] Step 5: Set LINK[SUMPOLY]:=NULL Set SUMPOLY:=LINK[SUMPOLY] Step 6: Return

17 Addition of polynomials using circular header linked list representation for polynomials

18 Algorithm: ADDPOLY( COEFF, POWER, LINK, POLY1,POLY2, SUMPOLY, AVAIL) This algorithm finds the sum of two polynomials implemented using header circular linked lists. POLY1 and POLY2 contain the addresses of header nodes of two polynomials and SUMPOLY is the circular header linked list storing the terms of sum of two polynomials Step 1: Set HEADER:=AVAIL and AVAIL:=LINK[AVAIL] Step 2: Set SUMPOLY:=HEADER Set LINK[SUMPOLY ]:=AVAIL and AVAIL:=LINK[AVAIL] Set SUMPOLY:=LINK[SUMPOLY] Step 3: Set START1:=POLY1 and START2:=POLY2 Set POLY1:=LINK[START1] and POLY2:=LINK[START2] Step 4: Repeat while POLY1 ≠ START1 and POLY2≠START2: If POWER[POLY1]>POWER[POLY2],then: Set COEFF[SUMPOLY]:=COEFF[POLY1] Set POWER[SUMPOLY]:=POWER[POLY1] Set POLY1:=LINK[POLY1] Set LINK[SUMPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set SUMPOLY:=LINK[SUMPOLY] Else If POWER[POLY2]>POWER[POLY1], then: Set COEFF[SUMPOLY]:=COEFF[POLY2] Set POWER[SUMPOLY]:=POWER[POLY2] Set POLY2:=LINK[POLY2] Set LINK[SUMPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set SUMPOLY:=LINK[SUMPOLY]

19 Else: Set COEFF[SUMPOLY]:=COEFF[POLY1]+COEFF[POLY2] Set POWER[SUMPOLY]:=POWER[POLY1] Set POLY1:=LINK[POLY1] Set POLY2=LINK[POLY2] Set LINK[SUMPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set SUMPOLY:=LINK[SUMPOLY] [End of If structure] [End of Loop] Step5: If POLY1=START1, then: Repeat while POLY2≠ START2 Set COEFF[SUMPOLY]:=COEFF[POLY2] Set POWER[SUMPOLY]:=POWER[POLY2] Set POLY2:=LINK[POLY2] Set LINK[SUMPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set SUMPOLY:=LINK[SUMPOLY] [End of Loop] [End of If Structure]

20 Step 6: If POLY2=START2, then: Repeat while POLY1≠START1 Set COEFF[SUMPOLY]:=COEFF[POLY1] Set POWER[SUMPOLY]:=POWER[POLY1] Set POLY1:=LINK[POLY1] Set LINK[SUMPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set SUMPOLY:=LINK[SUMPOLY] [End of Loop] [End of If Structure] Step 7: Set LINK[SUMPOLY]:=HEADER and SUMPOLY:=LINK[SUMPOLY] Step 8: Return

21 Multiplication of Polynomials using linear linked list representation for polynomials

22 Algorithm: MUL POLY ( COEFF, POWER, LINK, POLY1, POLY2, PRODPOLY, AVAIL ) This algorithm multiplies two polynomials implemented using linear linked list. POLY1 and POLY2 contain the addresses of starting nodes of two polynomials. The result of multiplication is stored in another linked list whose starting node is PRODPOLY Step 1: Set PRODPOLY:=AVAIL and AVAIL:=LINK[AVAIL] Set START:=PRODPOLY Step 2: Repeat while POLY1 ≠ NULL Step 3:Repeat while POLY2≠NULL: Set COEFF[PRODPOLY]:=COEFF[POLY1]*COEFF[POLY2] Set POWER[PRODPOLY]:=POWER[POLY1]+POWER[POLY2] Set POLY2:=LINK[POLY2] Set LINK[PRODPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set PRODPOLY:=LINK[PRODPOLY] [End of step 4 loop] Set POLY1:=LINK[POLY1] [End of step 3 loop] Step 4 Set LINK[PRODPOLY]:=NULL and PRODPOLY:=LINK[PRODPOLY] Step 5: Return

23 Algorithm: MULPOLY( COEFF, POWER, LINK, POLY1, POLY2, PRODPOLY, AVAIL) This algorithm finds the product of two polynomials implemented using header circular linked list. POLY1 and POLY2 contain addresses of header nodes of two polynomials. The result of multiplication is stored in another header circular linked list. Step 1: Set HEADER:=AVAIL and AVAIL:=LINK[AVAIL] Step 2: Set PRODPOLY :=HEADER Set LINK[PRODPOLY ]:=AVAIL and AVAIL:=LINK[AVAIL] Set PRODPOLY:=LINK[PRODPOLY] Step 3: Set START1:=POLY1 and START2:=POLY2 Set POLY1:=LINK[START1] and POLY2:=LINK[START2] Step 4: Repeat while POLY1 ≠ START1 Step 5: Repeat while POLY2≠ START2 Set COEFF[PRODPOLY]:=COEFF[POLY1]*COEFF[POLY2] Set POWER[PRODPOLY]:=POWER[POLY1]+POWER[POLY2] Set POLY2:=LINK[POLY2] Set LINK[PRODPOLY]:=AVAIL and AVAIL:=LINK[AVAIL] Set PRODPOLY:=LINK[PRODPOLY] [End of Step 5 Loop] Set POLY1:=LINK[POLY1] [End of Step 4 Loop] Step 6: Set LINK[PRODPOLY]:=HEADER and PRODPOLY:=LINK[PRODPOLY] Step 7: Return

24 Doubly Linked List: Two-way List A two-way list is a linear linked list which can be traversed in two directions: in usual forward direction from beginning of the list to end and in backward direction from end of list to the beginning. Thus, given the location LOC of a node N in list, one has immediate access to both the next node and the preceding node in the list. Each node of a two-way list is divided into three parts: –An information field INFO which contains data of N –A pointer field FORW which contains the location of next node in the list –A pointer field BACK which contains the location of preceding node. The list also requires two list pointer variables FIRST which points to first node in the list and LAST which points to the last node in the list. Thus null pointer will appear in FORW field of last node in list and also in BACK field of first node in list.

25 Two way lists are maintained in memory by means of linear arrays in same way as one way list except that two pointer arrays, FORW and BACK, are required instead of one list pointer variable. The list AVAIL will still be maintained as a one-way list. FIRST LAST FORW[PTR] BACK[PTR]

26 Operations on a Two-way list Traversal Algorithm: Traversal This algorithm traverses a two-way list. FORW and BACK are the two address parts of each node containing the address of next node and previous node respectively. INFO is the information part of each node. START contains the address of the first node Step 1: Set PTR:=START Step 2: Repeat while PTR≠ NULL Apply PROCESS to INFO[PTR] Step 3: Set PTR:=FORW[PTR] [End of Step 2 Loop] Step 4: Exit

27 Algorithm: SEARCH(INFO,FORW,BACK,ITEM,START,LOC) This algorithm searches the location LOC of ITEM in a two- way list and sets LOC=NULL if ITEM is not found in the list Step 1: Set PTR:=START Step 2: Repeat while PTR≠NULL and INFO[PTR]≠ITEM Set PTR:=FORW[PTR] [End of Loop] Step 3: If INFO[PTR]=ITEM, then: Set LOC:=PTR Else: Set LOC:=NULL Step 4: Return

28 Algorithm: DELETE(INFO,FROW,BACK,START,AVAIL,LOC) This algorithm deletes a node from a two-way list Step 1: If LOC=START, then: START:=FORW[START] BACK[START]:=NULL Return Step 2: [Delete node] Set FORW[BACK[LOC]]:=FORW[LOC] Set BACK[FORW[LOC]]:=BACK[LOC] Step 3: [Returning node to AVAIL] Set FORW[LOC]:=AVAIL and AVAIL:=LOC Step 4: Return

29 Algorithm:INSRT ( INFO,FORW,BACK,START,AVAIL,LOCA, LOCB, ITEM) This algorithm inserts an item in a doubly linked list. LOCA and LOCB location of adjacent nodes A and B Step 1: [OVERFLOW] If AVAIL=NULL, then: Write: OVERFLOW Return Step 2: Set NEW:=AVAIL and AVAIL:=LINK[AVAIL] Set INFO[NEW]:=ITEM Step 3: Set FORW[LOCA]:=NEW and BACK[NEW]:=LOCA Set FORW[NEW]:=LOCB and BACK[LOCB]:=NEW Step 4: Return

30 BACK[PTR] FORW[PTR] NEW

31 TEST QUESTIONS

32 Algorithm to copy the contents of one linked list to another Algorithm: Copy (INFO,LINK,START,AVAIL) This algorithm copies the contents of one linked list to another. Step 1: If AVAIL=NULL,then Write: ‘Overflow’ Return Step 2: Set PTR:=START Step 3: Set NEW:=AVAIL, START1:=NEW and AVAIL:=LINK[AVAIL] Step 4: Repeat while PTR≠ NULL INFO[NEW]:=INFO[PTR] LINK[NEW]:=AVAIL and AVAIL:=LINK[AVAIL] NEW:=LINK[NEW] [End of Loop] Step 5: Set LINK[NEW]:=NULL Step 6: Return

33 Algorithm: Copy (INFO,LINK,START,START1) This algorithm copies the contents of one linked list to another. START AND START1 are the start pointers of two lists Step 1: Set PTR:=START and PTR1:=START1 Step 2: Repeat while PTR≠ NULL and PTR1 ≠ NULL INFO[PTR1]:=INFO[PTR] PTR1:=LINK[PTR1] PTR:=LINK[PTR] [End of Loop] Step 3: If PTR=NULL and PTR1=NULL Return Step 4:[Case when the list to be copied is still left] If PTR1=NULL,then PTR1: =AVAIL and AVAIL:=LINK[AVAIL] Repeat while PTR ≠ NULL INFO[PTR1]:=INFO[PTR] LINK[PTR1]:=AVAIL and AVAIL:=LINK[AVAIL] PTR1:=LINK[PTR1] [End of Loop] Step 5: [Case when list to be copied is finished, Truncate the extra nodes] If PTR1 ≠NULL, then Set PTR1:=NULL [End of If structure] Step 6: Return

34 Algorithm to insert a node after the k th node in the circular linked list Algorithm: INSRT (INFO,LINK,START,AVAIL,K,ITEM) This algorithm inserts in a circular linked list after the kth node Step 1: If AVAIL:=NULL, then Write: ‘OVERFLOW’ Return Step 2: Set NEW:=AVAIL and AVAIL:=LINK[AVAIL] Set INFO[NEW]:=ITEM Step 3: Set PTR:=START and N:=1 Step 4: If N=K, then Set LINK[NEW]:=LINK[PTR] Set LINK[PTR]:=NEW Return Step 5: Set PTR:=LINK[PTR] and Step 6: Repeat while N ≠ K Set PTR:=LINK[PTR] and N:=N+1 [End of if structure] Step 7: Set LINK[NEW]:=LINK[PTR] Set LINK[PTR]:=NEW Step 8: Return

35 Algorithm to delete the k th node from a doubly linked list Algorithm: Del (INFO,FORW,BACK,FIRST,LAST,AVAIL,K) This algorithm deletes the kth node Step 1: Set N:=1 and PTR:=FIRST Step 2: Set SAVE:=PTR and PTR:=FORW[PTR] Step 3: Repeat while N≠ K Set SAVE:=PTR and PTR:=FORW[PTR] Set N:=N+1 [End of If structure] Step 4: If N=K, then FORW[SAVE]:=FORW[PTR] BACK[FORW[PTR]]:=BACK[PTR] FORW[PTR]:=AVAIL and AVAIL:=PTR [End of If structure] Step 5: Return

36 GARBAGE COLLECTION

37 In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory used by objects that will never be accessed or mutated again by the application. Garbage collection is often portrayed as the opposite of manual memory management, which requires the programmer to specify which objects to deallocate and return to the memory system. The basic principle of how a garbage collector works is: Determine what data objects in a program will not be accessed in the future Reclaim the resources used by those objects. Reachability of an object Informally, a reachable object can be defined as an object for which there exists some variable in the program environment that leads to it, either directly or through references from other reachable objects. More precisely, objects can be reachable in only two ways: A distinguished set of objects are assumed to be reachable—these are known as the roots. Typically, these include all the objects referenced from anywhere in the call stack (that is, all local variables and parameters in the functions currently being invoked), and any global variables. Anything referenced from a reachable object is itself reachable; more formally, reachability is a transitive closure.

38 The memory is traced for garbage collection using Tracing collectors OR SIMPLY COLLECTORS. Tracing collectors are called that way because they trace through the working set of memory. These garbage collectors perform collection in cycles. A cycle is started when the collector decides (or is notified) that it needs to reclaim storage, which in particular happens when the system is low on memory. The original method involves a naive mark-and-sweep in which the entire memory set is touched several times In this method, each object in memory has a flag (typically a single bit) reserved for garbage collection use only. This flag is always cleared (counter-intuitively), except during the collection cycle. The first stage of collection sweeps the entire 'root set', marking each accessible object as being 'in-use'. All objects transitively accessible from the root set are marked, as well. Finally, each object in memory is again examined; those with the in-use flag still cleared are not reachable by any program or data, and their memory is freed. (For objects which are marked in-use, the in-use flag is cleared again, preparing for the next cycle.).

39 Moving vs. non-moving garbage Collection Once the unreachable set has been determined, the garbage collector may simply release the unreachable objects and leave everything else as it is, or it may copy some or all of the reachable objects into a new area of memory, updating all references to those objects as needed. These are called "non-moving" and "moving" garbage collectors, respectively. At first, a moving GC strategy may seem inefficient and costly compared to the non-moving approach, since much more work would appear to be required on each cycle. In fact, however, the moving garbage collection strategy leads to several performance advantages, both during the garbage collection cycle itself and during actual program execution

40 STACKS

41 Stack- A stack is a linear data structure in which items may be added or removed only at one end. Accordingly, stacks are also called last- in-first-out or LIFO lists. The end at which element is added or removed is called the top of the stack. Two basic operations associated with stacks are : Push- Term used to denote insertion of an element onto a stack. Pop- Term used to describe deletion of an element from a stack. The order in which elements are pushed onto a stack is reverse of the order in which elements are popped from a stack

42 Representation of stacks Stacks may be represented in memory in various ways usually by means of one-way list or a linear array In array representation of stack, stack is maintained by an array named STACK, a variable TOP which contains the location/index of top element of stack and a variable MAXSTK giving the maximum number of elements that can be held by the stack. The condition TOP=0 or TOP=NULL indicates that stack is empty. The operation of addition of an item on stack and operation of removing an item from a stack may be implemented respectively by sub algorithms, called PUSH and POP. Before executing operation PUSH on to a stack, one must first test whether there is room in the stack for the new item. If not, then we have the condition known as overflow. Analogously, in executing the POP operation, one must first test where there is an element in stack to be deleted. If not, then we have condition known as underflow.

43 ARRAY IMPLEMENTATION OF STACK

44 Algorithm: PUSH (STACK,TOP,MAXSTK,ITEM) This algorithm pushes an item onto the stack array. TOP stores the index of top element of the stack and MAXSTK stores the maximum size of the stack. Step 1: [Stack already filled] If TOP=MAXSTK, then: Write: ‘OVERFLOW’ Return Step 2: Set TOP:=TOP+1 Step 3: Set STACK[TOP]:=ITEM Step 4: Return

45 Algorithm: POP(STACK,TOP,ITEM) This procedure deletes the top element of STACK array and assign it to variable ITEM Step 1: If TOP=0,then: Write: ‘UNDERFLOW’ Return Step 2: Set ITEM:=STACK[TOP] Step 3: Set TOP:=TOP-1 Step 4: Return

46 A stack represented using a linked list is also known as linked stack. The array based representation of stack suffers from following limitations: Size of stack must be known in advance Representing stack as an array prohibits the growth of stack beyond finite number of elements. In a linked list implementation of stack, each memory cell will contain the data part of the current element of stack and pointer that stores the address of its bottom element and the memory cell containing the bottom most element will have a NULL pointer

47 Push operation on linked list representation of stack Algorithm: PUSH(INFO, LINK, TOP, ITEM, AVAIL) This algorithm pushes an element to the top of the stack Step 1: If AVAIL=NULL, then Write: ‘OVERFLOW’ Return Step 2: Set NEW:=AVAIL and AVAIL:=LINK[AVAIL] Step 3: Set INFO[NEW]:=ITEM Step 4: If TOP=NULL, then Set LINK[NEW]:=NULL Set TOP:=NEW Return Else: Set LINK[NEW]:=TOP Set TOP:=NEW Step 5: Return

48 POP operation on linked list representation of stack Algorithm: POP(INFO, LINK, TOP, AVAIL) This algorithm deletes an element from the top of the stack Step 1: If TOP=NULL, then: Write: ‘UNDERFLOLW’ Return Step 2: Set PTR:=TOP Set TOP:=LINK[TOP] Write: INFO[PTR] Step 3: Set LINK[PTR]:=AVAIL and AVAIL:=PTR Step 4: Return

49 Application of stack Evaluation of arithmetic expression. For most common arithmetic operations, operator symbol is placed between its operands. This is called infix notation of an expression. To use stack to evaluate an arithmetic expression, we have to convert the expression into its prefix or postfix notation. Polish notation, refers to the notation in which operator symbol is placed before its two operands. This is also called prefix notation of an arithmetic expression. The fundamental property of polish notation is that the order in which operations are to be performed is completely determined by positions of operators and operands in expression. Accordingly, one never needs parentheses when writing expression in polish notation. Reverse Polish notation refers to notation in which operator is placed after its two operands. This notation is frequently called postfix notation. Examples of three notations are:

50 INFIX NOTATION: A+B PREFIX OR POLISH NOTATION: +AB POSTFIX OR REVERSE POLISH NOATATION: AB+ Convert the following infix expressions to prefix and postfix forms A+(B*C) (A+B)/(C+D) Prefix: +A*BC Postfix: A BC*+ Prefix: / +AB+CD Postfix: AB+CD+/

51 The computer usually evaluates an arithmetic expression written in infix notation in two steps. Converts expression to postfix notation Evaluates the postfix notation. Evaluation of postfix expression Suppose P is an arithmetic expression written in postfix notation. The following algorithm which uses a STACK to hold operands and evaluates P

52 Algorithm: This algorithm finds the VALUE of an arithmetic expression P written in Postfix notation. Step 1: Add a right parentheses “ )” at the end of P Step 2: Scan P from left to right and repeat step 3 and 4 for each element of P until “)” is encountered Step 3: If an operand is encountered, put the operand on the stack Step 4: If an operator is encountered, then: (a) Remove the two top elements of stack, where A is top element and B is next-top-element. (b) Evaluate B A (c ) Place the result of (b) back on stack [End of if structure] [End of step 2 loop] Step 5: Set VALUE equal to the top element of stack Step 6: Exit

53 Transforming Infix Expression into Postfix Expression The algorithm uses a stack to temporarily hold operators and left parentheses. The postfix expression P will be constructed from left to right using operands from Q and operators which are removed from STACK. The algorithm begins by pushing a left parentheses onto stack and adding a right parentheses at the end of Q Algorithm: POSTFIX (Q, P) Suppose Q is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression P Step 1: Push “(“ on to the STACK and add “)” to the end of Q Step 2: Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK is empty Step 3: If an operand is encountered, add it to P Step 4: If left parentheses is encountered, add it to STACK

54 Step 5: If an operator is encountered, then: (a) Repeatedly pop from STACK and add to P each operator which has same precedence or higher precedence than (b) Add to STACK Step 6: If a right parentheses is encountered, then: (a) Repeatedly pop from STACK and add to P each operator until a left parentheses is encountered (b) Remove the left parentheses [End of Step 2 Loop] Step 7: Exit

55 Example: Convert Q=A+(B*C) / D) to its corresponding postfix form Solution: put “)” at the end of Q and put “(“ on stack Starting from left: Operand A, put it on P Operator + move to stack as no operator there ( move on stack Operand B, put it on P Operator *, move to stack as no operator Operand C, move to P ), pop from stack and put on P until “ (“ is encountered. Pop “(“ also operator /, as precedence of / is higher than + on stack, no pop possible. Push / on stack Operand D, put it on P Right parentheses ), Pop all the elements and add the P until ( is encountered. Also remove ( from stack P= A B C* D / + + ( ( * + ( + ( /

56 Transforming Infix Expression into Prefix Expression Algorithm: [Polish Notation] PREFIX (Q, P) Suppose Q is an arithmetic expression written in infix notation. This algorithm finds the equivalent prefix expression P Step 1: Reverse the input string Step 2: Examine the next element in the input Step 3: If it is operand, add it to output string Step 4: If it is closing parentheses, push it on stack Step 5: If it is operator, then: (i) if stack is empty, push operator on stack (ii) if top of stack is closing parentheses, push operator on the stack (iii) If it has same or higher priority than top of stack, push operator on stack Else pop the operator from the stack and add it to output string, repeat step 5

57 Step 6: If it is an opening parentheses, pop operators from stack and add them to output string until a closing parentheses is encountered, pop and discard the closing parentheses. Step 7: If there is more input go to step 2 Step 8: If there is no more input, unstack the remaining operators and add them to output string Step 9: Reverse the output string

58 Consider the following arithmetic expression P written in postfix notation P: 12, 7, 3 -, /, 2, 1, 5, +, *, + (a) Translate P, by inspection and hand, into its equivalent infix expression (b) Evaluate the infix expression Sol: (a) Scanning from left to right, translate each operator from postfix to infix notation P = 12, [7-3], /, 2, 1, 5, +, *, + = [12/[7-3]],2, [1+5],*,+ = 12/(7-3)+2*(1+5) (b) 12/(7-3)+2*(1+5) = [3],[2*6],+ = 3+12 = 15

59 Practical applications of stack Stacks are used for implementing function calls in a program Used for implementing recursion. Used for conversion of infix expression to its postfix or prefix form Used for evaluation of postfix expression. Used in sorting of arrays (quicksort and mergesort technique)

60 QUEUE

61 Queue- A queue is a linear list of elements in which insertions can take place at one end called the rear of the queue, and deletion can take place only at other end, called the font of the queue. Queues are also called the FIFO lists (First In First Out) since first element in queue is the first element out of the queue. An important example of a queue in computer science occurs in time sharing systems in which programs with same priority form a queue while waiting to be executed. Queues may be represented in computer in various ways, usually by means of one-way lists or linear arrays

62 Representing a Queue Using an Array A Queue is maintained by a linear array queue and two pointer variables: FRONT, containing the location of front element of the queue and REAR, containing the location of rear element of the queue. The condition FRONT=NULL indicates that queue is empty. Whenever an element is deleted from the queue, the value of FRONT is increased by 1. Similarly, whenever an element is added to queue, the value of REAR is increased by 1. Queue as a circular queue It can be seen that after N insertions in a Queue represented by an array of N elements, the rear element of Queue will occupy last part of array. This occurs even though the queue itself may not contain many elements. Now, if we want to insert an element ITEM into a queue, we have to move or rearrange the elements of entire queue to the beginning of the queue. This procedure may be very expensive. Another method to do so is to represent a queue as a circular queue i,e QUEUE[1] comes after QUEUE[N] in array. With this assumption, we insert ITEM into queue by assigning ITEM to QUEUE[1]. Thus instead of increasing REAR to N+1, we reset REAR=1 and then assign QUEUE[REAR]=ITEM Similarly, If FRONT=N and an element of QUEUE is deleted, we reset FRONT=1 instead of increasing FRONT to N+1

63 Algorithm for Inserting in a QUEUE Algorithm: QINSERT(QUEUE, N, FRONT, REAR,ITEM) This algorithm inserts an element in a linear queue Step 1:[Queue already filled] If REAR=N, then: Write: ‘OVERFLOW’ Exit Step 2: If FRONT=NULL, then: [Queue initially empty] Set FRONT:=1 and REAR:=1 Else: Set REAR:=REAR+1 [End of If structure] Step 3: Set QUEUE[REAR]:=ITEM Step 4: Return

64 Algorithm: QDELETE(QUEUE,N,FRONT,REAR,ITEM) This algorithm deletes an element from a queue Step 1: If FRONT=NULL, then: Write: ‘UNDERFLOW’ Exit Step 2: Set ITEM:=QUEUE[FRONT] Step 3: If FRONT=REAR, then: [Empty Queue] Set FRONT:=NULL and REAR:=NULL Else: Set FRONT:=FRONT+1 [End of If structure] Step 4: Return

65 Algorithm: QINSERT(QUEUE, N, FRONT, REAR,ITEM) This algorithm inserts an element in a circular queue Step 1:[Queue already filled] If FRONT=1 and REAR=N or FRONT=REAR+1, then: Write: ‘OVERFLOW’ Exit Step 2: If FRONT=NULL, then: [Queue initially empty] Set FRONT:=1 and REAR:=1 Else If REAR=N, then: Set REAR:=1 Else: Set REAR:=REAR+1 [End of If structure] Step 3: Set QUEUE[REAR]:=ITEM Step 4: Return

66 Algorithm: QDELETE(QUEUE,N,FRONT,REAR,ITEM) This algorithm deletes an element from a circular queue Step 1: If FRONT=NULL, then: Write: ‘UNDERFLOW’ Exit Step 2: Set ITEM:=QUEUE[FRONT] Step 3: If FRONT=REAR, then: [Empty Queue] Set FRONT:=NULL and REAR:=NULL Else If FRONT=N, then: Set FRONT:=1 Else: Set FRONT:=FRONT+1 [End of If structure] Step 4: Return

67 Consider the following queue of characters where QUEUE is a circular array which is allocated six memory cells FRONT=2, REAR=4 QUEUE: _ A C D _ _ Describe the queue as following operations take place: (a)F is added to queue (b)Two letters are deleted (c)K, L and M are added (d)Two letters are deleted (e)R is added to queue (f)Two letters are deleted (g)S is added to queue (h)Two letters are deleted (i)One letter is deleted (j)One letter is deleted

68 Solution: (a)FRONT=2, REAR=5 QUEUE: _ A C D F_ (b)FRONT=4, REAR=5 QUEUE: _ _ _ D F _ (c)REAR=2, FRONT=4 QUEUE: L M _ D F K (d)FRONT=6, REAR=2 QUEUE: L M _ _ _ K (e)FRONT=6, REAR=3 QUEUE: L M R_ _ K (f)FRONT=2, REAR=3 QUEUE: _M R _ _ _ (g)REAR=4, FRONT=2 QUEUE: _ M R S _ _ (h)FRONT=4, REAR=4 QUEUE: _ _ _ S _ _ (i)FRONT=REAR=0 [ As FRONT=REAR, queue is empty] (j)Since FRONT=NULL, no deletion can take place. Underflow occurred

69 DEQUE(Double ended Queue)- A deque is a queue in which elements can be added or removed at either end but not in the middle. A deque is usually maintained by a circular array DEQUE with pointers LEFT and RIGHT, which point to two ends of deque. The elements extend from LEFT end to RIGHT end of deque. The term circular comes from the fact that DEQUE[1] comes after DEQUE [N].The condition LEFT=NULL will be used to indicate that a deque is empty. There are two variations of a deque Input-restricted deque- It is a deque which allows insertions at only one end of list but allows deletions at both ends of the list Output-restricted deque- It is a deque which allows deletions at only one end of list but allows insertions at both ends of list

70 Consider the following deque of characters where DEQUE is a circular array which is allocated six memory cells. LEFT=2, RIGHT=4 DEQUE: _ A,C,D, _, _ Describe deque while the following operation take place (a)F is added to right of deque LFET=2, RIGHT=5 _A C D F _ _ (b) Two letters on right are deleted LEFT=2 RIGHT=3 _A C _ _ _ _ (c) K,L and M are added to the left of the deque LEFT=5 RIGHT=3 K A C _ M L (d) One letter on left is deleted. LEFT=6 RIGHT=3 K A C _ _ L (e) R is added to the left of deque. LEFT=5 RIGHT= 3 K A C _ R L (f) S is added to right of deque LEFT=5 RIGHT= 4 K A C S R L (g) T is added to the right of deque Since LEFT= RIGHT+1, the array is full and hence T cannot be added to the deque

71 Linked representation of the Queue A linked queue is a queue implemented as a linked list with two pointer variables FRONT and REAR pointing to the nodes in the front and rear of the queue. The INFO field of list hold the elements of the queue and LINK field holds pointer to neighboring element of queue. In case of insertion in linked queue, a node borrowed from AVAIL list and carrying the item to be inserted is added as the last node of linked list representing the queue. Rear pointer is updated to point to last node just added to the list In case of deletion, first node of list pointed to by FRONT is deleted and FRONT pointer is updated to point to next node in the list. Unlike the array representation, linked queue functions as a linear queue and there is no need to view it as circular for efficient management of space.

72 Algorithm:LINKQINSRT(INFO,LINK,FRONT,REAR,AVAIL,ITEM) This algorithm inserts an item in linked list implementation of the queue Step 1: If AVAIL=NULL,then: Write: ‘OVERFLOW’ Exit Step 2: Set NEW:=AVAIL and AVAIL:=LINK[AVAIL] Step 3: Set INFO[NEW]:=ITEM and LINK[NEW]:=NULL Step 4: If FRONT=NULL, then: Set FRONT=REAR=NEW Else: Set LINK[REAR]:=NEW and REAR:=NEW Step 5: Return

73 Algorithm: LINKQDEL(INFO,LINK,FRONT,AVAIL,ITEM) This algorithm deletes an element from the front of the queue Step 1: If FRONT=NULL,then: Write:’UNDERFLOW’ Exit Step 2: Set TEMP:=FRONT Step 3: Set ITEM:=INFO[FRONT] Step 4: Set FRONT:=LINK[FRONT] Step 5: Set LINK[TEMP]:=AVAIL and AVAIL:=TEMP Step 6: Return

74 Priority Queue- A priority queue is a collection of elements such that each element has been assigned a priority and such that the order in which elements are deleted and processed comes from following rules: An element of higher priority is processed before any element of lower priority Two elements of same priority are processed according to the order in which they were added to queue An example of a priority queue is a time sharing system. Programs of higher priority are processed first and programs with same priority form a standard queue

75 One-way list representation of a priority queue One way to maintain a priority queue in memory is by means of a one-way list Each node in list will contain three items of information: an information field INFO, a priority number PRN and a link field LINK A node X precedes a node Y in list –If X has higher priority than Y –Or when both have same priority but X was added to list before Y

76 Algorithm:LKQINS(INFO,LINK,FRONT,PRN,AVAIL,ITEM, P) This algorithm inserts an item in linked list implementation of priority queue Step 1: If AVAIL=NULL,then: Write: ‘OVERFLOW’ Exit Step 2: Set NEW:=AVAIL and AVAIL:=LINK[AVAIL] Step 3: [Enter the data and priority of new node] Set INFO[NEW]:=ITEM and PRN[NEW]:=P Step 4: Set PTR:=FRONT Step 5: If PRN[PTR]>PRN[NEW], then LINK[NEW]:=FRONT FRONT:=NEW Return [End of If Structure] Step 5: Repeat while PTR≠NULL and PRN[PTR]<=PRN[NEW] Set SAVE:=PTR Set PTR:=LINK[PTR] [End of If Structure] Step 6: If PRN[PTR]>PRN[NEW] Set LINK[SAVE]:=NEW Set LINK[NEW]:=PTR Else: Set LINK[SAVE]:=NEW Set LINK[NEW]=NULL [End of If Structure] Step 7: Return

77 Another way to maintain a priority queue in memory is to use a separate queue for each level of priority. Each such queue will appear in its own circular array and must have its own pair of pointers, FRONT and REAR. If each queue is allocated the same amount of space, a two dimensional array QUEUE can be used instead of the linear arrays for representing a priority queue. If K represents the row K of the queue, FRONT[K] and REAR[K] are the front and rear indexes of the K th row. 1 2 3 4 5 6 1 AAA 2 BBB CCC XXX 3 4 FFF DDD EEE 5 GGG Priority

78 Algorithm: QINSERT( QUEUE,N, FRONT, REAR,ITEM,K) This algorithm inserts an element in a priority queue in a row with priority K. N is the size of the K th row. Step 1:[Queue already filled] If FRONT[K]=1 and REAR[K]=N or FRONT[K]=REAR[K]+1, then: Write: ‘OVERFLOW’ Exit Step 2: If FRONT[K]=NULL, then: [Queue initially empty] Set FRONT[K]:=1 and REAR[K]:=1 Else If REAR[K]=N, then: Set REAR[K]:=1 Else: Set REAR[K]:=REAR[K]+1 [End of If structure] Step 3: Set QUEUE[K][REAR[K]]:=ITEM Step 4: Return

79 Algorithm: QDELETE(QUEUE,N,FRONT,REAR,ITEM, START, MAXP) This algorithm deletes an element from a priority queue. MAXP is the maximum priority in the array Step 1: Set K=1 [Priority number] Step 2: Repeat while K<=MAXP and FRONT[K]=NULL Set K=K+1 [End of Loop] Step 3: If K>MAXP, then: Write:’UNDERFLOW’ Exit [End of If structure] Step 4: Set ITEM:=QUEUE[K][FRONT[K]] Step 5: If FRONT[K]=REAR[K], then: [Empty Queue] Set FRONT[K]:=NULL and REAR[K]:=NULL Else If FRONT[K]=N, then: Set FRONT[K]:=1 Else: Set FRONT[K]:=FRONT[K]+1 [End of If structure] Step 5: Return

80 TREE

81 A tree is a non-linear data structure mainly used to represent data containing hierarchical relationship between elements. In hierarchical data we have ancestor-descendent, superior-subordinate, whole-part, or similar relationship among data elements. A (general) tree T is defined as a finite nonempty set of elements such that There is a special node at the highest level of hierarchy called the root, and the remaining elements, if any, are partitioned into disjoint sets T 1,T 2,T 3 ---T n where each of these sets is a tree, called the sub tree of T. In other words, one may define a tree as a collection of nodes and each node is connected to another node through a branch. The nodes are connected in such a way that there are no loops in the tree and there is a distinguished node called the root of the tree.

82

83 Tree Terminology Parent node- If N is a node in T with left successor S 1 and right successor S 2, then N is called father or parent of S 1 and S 2. Similarly, S 1 is called left child of N and S 2 is called the right child of N. The child node is also called the descendant of a node N Siblings- The child nodes with same parent are called siblings Level of element- Each node in tree is assigned a level number. By definition, root of the tree is at level 0;its children, if any, are at level 1; their children, if any, are at level 2; and so on. Thus a node is assigned a level number one more than the level number of its parent Depth/Height of Tree- The height or depth of tree is maximum number of nodes in a branch. It is one more than the maximum level number of the tree. Degree of an element- The degree of a node in a tree is number of children it has. The degree of leaf node is zero. Degree of Tree- The degree of a tree is the maximum degree of its nodes. Edge- Line drawn from a node N of T to a successor is called an edge. Path- A sequence of edges is called an path Leaf- A terminal node of a tree is called leaf node Branch- Path ending in a leaf is called branch of the tree

84 The most common form of tree maintained in computer is binary tree. Binary Tree- A binary tree T is defined as a finite set of elements, called nodes, such that either: –T is empty (called null tree or empty tree) or, –T contains a distinguished node, R, called root of T and remaining nodes of T form an ordered pair of disjoint binary trees T1 and T2 Two trees T1 and T2 are called respectively left and right subtree of R (root node of T). If T1 is nonempty, then its root is called left successor of R. Similarly, If T2 is nonempty, then its root is called right successor of R A B C D E G H F J K L The nodes D,F,G,L,K are the terminal or leaf nodes Root Node (Right Successor of A)(Left Successor of A)

85 Binary trees are used to represent algebraic expressions involving only binary operations, such as E= (a-b)/((c*d)+e) Each variable or constant in E appears as an internal node in T whose left and right subtree correspond to operands of the expression / - + a b * e c d

86 Before constructing a tree for an algebraic expression, we have to see the precedence of the operators involved in the expression.

87 Difference between binary tree and a general tree A binary tree can be empty whereas a tree cannot be empty Each element in binary tree has at most two sub trees whereas each element in a tree can have any number of sub trees The sub trees of each element in a binary tree are ordered. That is we can distinguish between left and right sub trees. The sub trees in a tree are unordered.

88 Properties of Binary Trees Each node of a binary tree T can have at most two children. Thus at level r of t, there can be atmost 2 r nodes. The number of nodes in a tree for given number of levels in a tree is 2 n -1 Depth of a tree T with n nodes is given by D n = log 2 n + 1 D n ≈ log 2 n Complete Binary tree- A binary tree T is said to be complete if all its levels, except possibly the last, have maximum number of possible nodes, and if all the nodes at last level appear as far left as possible. Thus there is a unique complete tree T with exactly n nodes. Extended Binary Trees: 2-Trees- A binary tree is said to be a 2-tree or an extended binary tree if each node N has either 0 or 2 children. In such a case, nodes with 2 children are called internal nodes, and nodes with 0 child are called external nodes. The external and internal nodes are distinguished diagrammatically by using circles for internal nodes and squares for external nodes

89 Representing Binary Trees in memory Binary trees can be represented using linked list using a single array called the sequential representation of tree Sequential representation of Binary Trees- This representation uses only a single linear array Tree as follows: The root R of T is stored in TREE[1] If a node N occupies TREE[K], then its left child is stored in TREE[2*K] and its right child is stored in TREE[2*K+1] 45 22 77 11 30 90 15 25 88

90 45 22 77 11 30 0 90 0 15 25 0 0 0 NULL 88

91 It can be seen that a sequential representation of a binary tree requires numbering of nodes; starting with nodes on level 1, then on level 2 and so on. The nodes are numbered from left to right. It is an ideal case for representation of a complete binary tree and in this case no space is wasted. However for other binary trees, most of the space remains unutilized. As can be seen in the figure, we require 14 locations in array even though the tree has only 9 nodes. If null entries for successors of the terminal nodes are included, we would actually require 29 locations instead of 14.Thus sequential representation is usually inefficient unless binary tree is complete or nearly complete

92 Linked representation of Binary Tree In linked representation, Tree is maintained in memory by means of three parallel arrays, INFO, LEFT and RIGHT and a pointer variable ROOT. Each node N of T will correspond to a location K such that INFO[K] contains data at node N. LEFT[K] contains the location of left child of node N and RIGHT[K] contains the location of right child of node N. ROOT will contain location of root R of Tree. If any subtree is empty, corresponding pointer will contain null value. If the tree T itself is empty, then ROOT will contain null value A B C D E F G H I J ROOT

93 Traversing Binary Trees There are three standard ways of traversing a binary tree T with root R. These are preorder, inorder and postorder traversals Preorder PROCESS the root R Traverse the left sub tree of R in preorder Traverse the right sub tree of R in preorder Inorder Traverse the left sub tree of R in inorder Process the root R Traverse the right sub tree of R in inorder Postorder Traverse the left sub tree of R in postorder Traverse the right sub tree of R in postorder Process the root R

94 The difference between the algorithms is the time at which the root R is processed. In pre algorithm, root R is processed before sub trees are traversed; in the in algorithm, root R is processed between traversals of sub trees and in post algorithm, the root is processed after the sub trees are traversed. A B C D E F Preorder Traversal: A B D E C F Inorder Traversal: D B E A C F Postorder Traversal : D E B F C A

95 All the traversal algorithms assume a binary tree T maintained in memory by linked representation TREE(INFO,LEFT,RIGHT,ROOT) All algorithms use a variable PTR(pointer) which will contain the location of the node N currently being scanned. LEFT[N] denotes the left child of node N and RIGHT[N] denotes the right child of N. All algorithms use an array STACK which will hold the addresses of nodes for further processing.

96 Algorithm: PREORD(INFO, LEFT, RIGHT, ROOT) This algorithm traverses the tree in preorder Step 1: Set TOP:=1, STACK[1]:=NULL and PTR:= ROOT Step 2: Repeat Step 3 to 5 while PTR≠NULL Step 3: Apply PROCESS to INFO[PTR] Step 4: [Right Child ?] If RIGHT[PTR] ≠ NULL, then: Set TOP:=TOP + 1 Set STACK[TOP]:= RIGHT[PTR] [End of If structure] Step 5: [Left Child ?] If LEFT[PTR] ≠ NULL, then: Set PTR:=LEFT[PTR] Else: Set PTR:=STACK[TOP] Set TOP:=TOP-1 [End of If structure] [End of Step 2 Loop] Step 6: Return

97 Algorithm: INORD (INFO, LEFT,RIGHT, ROOT) Step 1: Set TOP:=1, STACK[1]:=NULL and PTR:=ROOT Step 2: Repeat while PTR ≠ NULL: (A) Set TOP:=TOP + 1 and STACK[TOP]:= PTR (B) Set PTR:=LEFT[PTR] [End of Loop] Step 3: Set PTR:=STACK[TOP] and TOP:=TOP -1 Step 4: Repeat Step 5 to 7 while PTR ≠ NULL Step 5: Apply PROCESS to INFO[PTR] Step 6: If RIGHT[PTR] ≠ NULL, then: (A) Set PTR := RIGHT[PTR] (B) GO TO step 2 [End of If structure] Step 7: Set PTR:=STACK[TOP] and TOP:=TOP -1 [End of Step 4 Loop] Step 8: Return

98 Algorithm : POSTORD( INFO, LEFT, RIGHT, ROOT) Step 1: Set TOP:=1, STACK[1]:=NULL and PTR:=ROOT Step 2: Repeat Step 3 to 5 while PTR≠ NULL Step 3: Set TOP:=TOP +1 and STACK[TOP]:=PTR Step 4: If RIGHT[PTR]≠ NULL, then: Set TOP:=TOP +1 and STACK[TOP]:= - RIGHT[PTR] [End of If structure] Step 5: Set PTR:=LEFT[PTR] [End of Step 2 loop] Step 6: Set PTR:=STACK[TOP] and TOP:=TOP -1 Step 7: Repeat while PTR>0: (A) Apply PROCESS to INFO[PTR] (B) Set PTR:=STACK[TOP] and TOP:=TOP -1 [End of Loop] Step 8: If PTR<0, then: (a) Set PTR:=-PTR (b) Go to Step 2 [End of If structure] Step 9: Exit

99 Problem: Create a tree from the given traversals preorder: F A E K C D H G B inorder: E A C K F H D B G Solution: The tree is drawn from the root as follows: (a)The root of tree is obtained by choosing the first node of preorder. Thus F is the root of the proposed tree (b)The left child of the tree is obtained as follows: (a)Use the inorder traversal to find the nodes to the left and right of the root node selected from preorder. All nodes to the left of root node(in this case F) in inorder form the left subtree of the root(in this case E A C K ) (b)All nodes to the right of root node (in this case F ) in inorder form the right subtree of the root (H D B G) (c)Follow the above procedure again to find the subsequent roots and their subtrees on left and right.

100 F is the root Nodes on left subtree( left of F):E A C K (from inorder) Nodes on right subtree(right of F):H D B G(from inorder) The root of left subtree: From preorder: A E K C, Thus the root of left subtree is A D H G B, Thus the root of right subtree is D Creating left subtree first: From inorder: elements of left subtree of A are: E (root of left) elements of right subtree of A are: C K (root of right) Thus tree till now is: F A D E K C As K is to the left of C in preorder

101 Creating the right subtree of F The root node is D From inorder, the nodes on the left of D are: H (left root of D) the nodes on the right of D are: B G (right root of D) Thus the tree is: F A D E K H G C B

102 F A D E K H G C B

103 Threads: Inorder Threading Considering linked list representation of a binary tree, it can be seen that half of the entries in pointer fields LEFT and RIGHT will contain null entries. This space may be more efficiently used by replacing the null entries by special pointers called Threads which point to nodes higher in tree. Such trees are called Threaded trees. The threads in a threaded tree are usually indicated by dotted lines. In computer memory, threads may be represented by negative integers when ordinary pointers are denoted by positive integers. There are many ways to thread a binary tree T but each threading will correspond to a particular traversal of T. Trees can be threaded using one-way threading or two-way threading. Unless otherwise stated, threading will correspond to inorder traversal of T. Accordingly, in one-way threading, a thread will appear in right null field of a node and will point to the next node in inorder traversal of T In two-way threading of T, a thread will also appear in the LEFT field of a node and will point to the preceding node in inorder traversal of T

104 A B C D E G H F J K L One-way inorder Threading Inorder traversal: D B F E A G C L J H K

105 A B C D E G H F J K L Two-way inorder Threading

106 Binary Search Tree- If T is a binary tree, then T is called a binary search tree or binary sorted tree if each node N of T has the following property: –The Value of N is greater than every value in left sub tree of N –The value at N is less than or equal to every value in right sub tree of N The inorder traversal of BST gives sorted numbers For example: The following numbers create a BST as: 3 5 9 1 2 6 8 10 3 1 5 2 9 6 10 8

107 Binary search tree is one of the most important data structures in computer science. This structure enables one to search for and find an element with an average running time f(n)=O(log 2 n ) It also enables one to easily insert and delete elements. This structure contrasts with following structures: Sorted linear array- here one can find the element with a running time of O(log 2 n ) but it is expensive to insert and delete Linked list- Here one can easily insert and delete but searching is expensive with running time of O(n)

108 Searching and Inserting in a BST Algorithm: This algorithm searches for ITEM in a tree and inserts it if not present in tree Step 1: Compare ITEM with root node N of Tree (i) If ITEM < N, proceed to left child of N (ii) If ITEM >= N, proceed to right child of N Step 2: Repeat step 1 until one of the following occurs: (i) If ITEM = N, then: Write: ‘Search successful’ (ii) Empty sub tree found indicating search unsuccessful. Insert item in place of empty sub tree

109 Algorithm: INSBT(INFO, LEFT, RIGHT, AVAIL, ITEM, LOC) This algorithm finds the location LOC of an ITEM in T or adds ITEM as a new node in T at location LOC Step 1: Call FIND(INFO, LEFT, RIGHT, ROOT, ITEM, LOC, PAR) Step 2: If LOC ≠ NULL, then Return Step 3: [Copy item into new node in AVAIL list] (a) If AVAIL=NULL, then: Write: ‘OVERFLOW’ Return (b) Set NEW:=AVAIL, AVAIL:=LINK[AVAIL] and INFO[NEW]:=ITEM (c) Set LEFT[NEW]:=NULL and RIGHT[NEW]:=NULL Step 4:[Add ITEM to tree] If PAR=NULL, then: Set ROOT:=NEW Else If ITEM<INFO[PAR], then: Set LEFT[PAR]:=NEW Else: Set RIGHT[PAR]:=NEW [End of If structure] Step 5: Return

110 Algorithm: FIND(INFO,LEFT,RIGHT,ROOT,ITEM,LOC,PAR) This algorithm finds the location LOC of ITEM in T and also the location PAR of the parent of ITEM. There are three special cases (a) LOC=NULL and PAR=NULL will indicate tree is empty (b) LOC≠ NULL and PAR=NULL will indicate that ITEM is the root of T ( c) LOC=NULL and PAR ≠ NULL will indicate that ITEM is not in T and can be added to T as a child of node N with location PAR Step 1: If ROOT= NULL, then: Set LOC:=NULL and PAR:=NULL Return Step 2: If ITEM=INFO[ROOT], then: Set LOC:=ROOT and PAR:=NULL Write: ’Item is the root of the tree’ Return Step3: If ITEM < INFO[ROOT], then: Set PTR:=LEFT[ROOT] and SAVE:=ROOT Else: Set PTR:=RIGHT[ROOT] and SAVE:= ROOT [End of If structure] Step 4: Repeat while PTR ≠ NULL: If ITEM=INFO[PTR],then: Set LOC:=PTR and PAR:=SAVE Write: ‘ the location of the node in tree is’, LOC Return If ITEM< INFO[PTR], then: Set SAVE:=PTR and PTR:=LEFT[PTR] Else: Set SAVE:=PTR and PTR:=RIGHT[PTR] [End of If structure] [End of Step 4 Loop] Step 5: [Search unsuccessful] Set LOC:=NULL and PAR:=SAVE Step 6: Return

111 Deletion in a Binary Search Tree- Deletion in a BST uses a procedure FIND to find the location of node N which contains ITEM and also the location of parent node P(N). The way N is deleted from the tree depends primarily on the number of children of node N. There are three cases: Case 1: N has no children. Then N is deleted from T by simply replacing the location P(N) by null pointer Case 2: N has exactly one child. Then N is deleted from T by simply replacing the location of N by location of the only child of N Case 3: N has two children. Let S(N) denote the inorder successor of N. Then N is deleted from T by first deleting S(N) from T(by using Case 1 or Case 2) and then replacing node N in T by node S(N)

112 Case 1: When node to be deleted does not have two children Algorithm: DELA( INFO, LEFT,RIGHT,ROOT,LOC,PAR) This procedure deletes node N at location LOC where N does not have two children. PAR gives the location of parent node of N or else PAR=NULL indicating N is the root node. Pointer CHILD gives the location of only child of N Step 1: If LEFT[LOC]=NULL and RIGHT[LOC]=NULL, then: Set CHILD=NULL Else If LEFT[LOC]≠NULL, then: Set CHILD:=LEFT[LOC] Else Set CHILD:=RIGHT[LOC] Step 2: If PAR ≠ NULL, then: If LOC=LEFT[PAR], then: Set LEFT[PAR]:=CHILD Else: Set RIGHT[PAR]:=CHILD Else: Set ROOT:=CHILD Step 3: Return

113 Case 2: When node to be deleted has two children Algorithm: DELB( INFO, LEFT, RIGHT, ROOT, LOC, PAR, SUC, PARSUC) This procedure deletes node N at location LOC where N have two children. PAR gives the location of parent node of N or else PAR=NULL indicating N is the root node. Pointer SUC gives the location of in order successor of N and PARSUC gives the location of parent of in order successor Step 1: (a) Set PTR:=RIGHT[LOC] and SAVE:=LOC (b) Repeat while LEFT[PTR]≠NULL Set SAVE:=PTR and PTR:=LEFT[PTR] [End of Loop] (c ) Set SUC:=PTR and PARSUC:=SAVE Step 2: CALL DELA(INFO,LEFT,RIGHT, ROOT,SUC,PARSUC) Step 3: (a) If PAR ≠ NULL, then: If LOC = LEFT [PAR], then: Set LEFT[PAR]:=SUC Else: Set RIGHT[PAR]:=SUC [End of If structure] Else: Set ROOT:=SUC [End of If structure]

114 (b) Set LEFT[SUC]:=LEFT[LOC] and Set RIGHT[SUC]:=RIGHT[LOC] Step 4: Return

115 Heap Suppose H is a complete binary tree with n elements. Then H is called a heap or a maxheap if each node N of H has the property that value of N is greater than or equal to value at each of the children of N. 97 88 95 66 55 95 48 66 35 48 55 62 77 25 38 18 40 30 26 24

116 Analogously, a minheap is a heap such that value at N is less than or equal to the value of each of its children. Heap is more efficiently implemented through array rather than linked list. In a heap, the location of parent of a node PTR is given by PTR/2 Inserting an element in a Heap Suppose H is a heap with N elements, and suppose an ITEM of information is given. We insert ITEM into the heap H as follows: First adjoin the ITEM at the end of H so that H is still a complete tree but not necessarily a heap Then let the ITEM rise to its appropriate place in H so that H is finally a heap

117 Algorithm: INSHEAP( TREE, N, ITEM) A heap H with N elements is stored in the array TREE and an ITEM of information is given. This procedure inserts the ITEM as the new element of H. PTR gives the location of ITEM as it rises in the tree and PAR denotes the parent of ITEM Step 1: Set N:= N +1 and PTR:=N Step 2: Repeat Step 3 to 6 while PTR > 1 Set PAR:=PTR/2 If ITEM ≤ TREE[PAR], then: Set TREE[PTR]:=ITEM Return Set TREE[PTR]:=TREE[PAR] [End of If structure] Set PTR:=PAR [End of Loop] Step 3: Set TREE[1]:=ITEM Step 4: Return

118 Deleting the root node in a heap Suppose H is a heap with N elements and suppose we want to delete the root R of H. This is accomplished as follows: Assign the root R to some variable ITEM Replace the deleted node R by last node L of H so that H is still a complete tree but not necessarily a heap Let L sink to its appropriate place in H so that H is finally a heap

119 Algorithm: DELHEAP( TREE, N, ITEM ) A heap H with N elements is stored in the array TREE. This algorithm assigns the root TREE[1] of H to the variable ITEM and then reheaps the remaining elements. The variable LAST stores the value of the original last node of H. The pointers PTR, LEFT and RIGHT give the location of LAST and its left and right children as LAST sinks into the tree. Step 1: Set ITEM:=TREE[1] Step 2: Set LAST:=TREE[N] and N:=N-1 Step 3: Set PTR:=1, LEFT:=2 and RIGHT:=3 Step 4: Repeat step 5 to 7 while RIGHT ≤ N: Step 5: If LAST ≥ TREE[LEFT] and LAST ≥ TREE [RIGHT], then: Set TREE[PTR]:=LAST Return

120 Step 6: If TREE[RIGHT]≤ TREE[LEFT], then: Set TREE[PTR]:=TREE[LEFT] Set PTR:=LEFT Else: Set TREE[PTR]:=TREE[RIGHT] and PTR:=RIGHT [End of If structure] Set LEFT:= 2* PTR and RIGHT:=LEFT + 1 [End of Loop] Step 7: If LEFT=N and If LAST < TREE[LEFT], then: Set TREE[PTR]:=TREE[LEFT] and Set PTR:=LEFT Step 8: Set TREE[PTR]:=LAST Return

121 90 80 85 60 50 75 70

122 Application of Heap HeapSort- One of the important applications of heap is sorting of an array using heapsort method. Suppose an array A with N elements is to be sorted. The heapsort algorithm sorts the array in two phases: Phase A: Build a heap H out of the elements of A Phase B: Repeatedly delete the root element of H Since the root element of heap contains the largest element of the heap, phase B deletes the elements in decreasing order. Similarly, using heapsort in minheap sorts the elements in increasing order as then the root represents the smallest element of the heap.

123 Algorithm: HEAPSORT(A,N) An array A with N elements is given. This algorithm sorts the elements of the array Step 1: [Build a heap H] Repeat for J=1 to N-1: Call INSHEAP(A, J, A[J+1]) [End of Loop] Step 2: [Sort A repeatedly deleting the root of H] Repeat while N > 1: (a) Call DELHEAP( A, N, ITEM) (b) Set A[N + 1] := ITEM [Store the elements deleted from the heap] [End of loop] Step 3: Exit

124 Problem: Create a Heap out of the following data: jan feb mar apr may jun jul aug sept oct nov dec Solution: sep oct jun mar nov jan jul apr aug feb may dec

125 AVL TREE

126 The efficiency of many important operations on trees is related to the height of the tree –for example searching, insertion and deletion in a BST are all O(height). In general, the relation between the height of the tree and the number of nodes of the tree is O (log 2 n) except in the case of right skewed or left skewed BST in which height is O(n). The right skewed or left skewed BST is one in which the elements in the tree are either on the left or right side of the root node. A A B B C C D D E E Right-skewedLeft-skewed

127 For efficiency sake, we would like to guarantee that h remains O(log 2 n). One way to do this is to force our trees to be height- balanced. Method to check whether a tree is height balanced or not is as follows: –Start at the leaves and work towards the root of the tree. –Check the height of the subtrees(left and right) of the node. –A tree is said to be height balanced if the difference of heights of its left and right subtrees of each node is equal to 0, 1 or -1 Example: Check whether the shown tree is balanced or not

128 A B C D Sol: Starting from the leaf nodes D and C, the height of left and right subtrees of C and D are each 0. Thus their difference is also 0 Check the height of subtrees of B Height of left subtree of B is 1 and height of right subtree of B is 0. Thus the difference of two is 1 Thus B is not perfectly balanced but the tree is still considered to be height balanced. Check the height of subtrees of A Height of left subtree of A is 2 while the height of its right subtree is 1. The difference of two heights still lies within 1. Thus for all nodes the tree is a balanced binary tree.

129 Check whether the shown tree is balanced or not A B F C D E Ans No as node B is not balanced as difference of heights of left and right subtrees is 3-0 i.e more than 1.

130 Height-balanced Binary tree (AVL Tree) The disadvantage of a skewed binary search tree is that the worst case time complexity of a search is O(n). In order to overcome this disadvantage, it is necessray to maintain the binary search tree to be of balanced height. Two Russian mathematicians, G.M. Adel and E.M. Landis gave a technique to balance the height of a binary tree and the resulting tree is called AVL tree. Definition: An empty binary tree is an AVL tree. A non empty binary tree T is an AVL tree iff given T L and T R to be the left and right subtrees of T and h(T L ) and h(T R ) be the heights of subtrees T L and T R respectively, T L and T R are AVL trees and |h(T L )-h(T R )| ≤ 1. |h(T L )-h(T R )| is also called the balance factor (BF) and for an AVL tree the balance factor of a node can be either -1, 0 or 1 An AVL search tree is a binary search tree which is an AVL tree.

131 A node in a binary tree that does not contain the BF of 0, 1 or -1, it is said to be unbalanced. If one inserts a new node into a balanced binary tree at the leaf, then the possible changes in the status of the node are as follows: The node was either left or right heavy and has now become balanced. A node is said to be left heavy if number of nodes in its left subtree are one more than the number of nodes in its right subtree.. In other words, the difference in heights is 1. Similar is the case with right heavy node where number of nodes in right subtree are one more than the number of nodes in left subtree The node was balanced and has now become left or right heavy The node was heavy and the new node has been inserted in the heavy subtree, thus creating an unbalanced subtree. Such a node is called a critical node.

132 Rotations- Inserting an element in an AVL search tree in its first phase is similar to that of the one used in a binary search tree. However, if after insertion of the element, the balance factor of any node in a binary search tree is affected so as to render the binary search tree unbalanced, we resort to techniques called Rotations to restore the balance of the search tree. To perform rotations, it is necessary to identify the specific node A whose BF (balance factor) is neither 0,1 or -1 and which is nearest ancestor to the inserted node on the path from inserted node to the root. The rebalancing rotations are classified as LL, LR, RR and RL based on the position of the inserted node with reference to A LL rotation: Inserted node in the left subtree of the left subtree of A RR rotation: Inserted node in the right subtree of the right subtree of A LR rotation: Inserted node in the right subtree of the left subtree of A RL rotation: Inserted node in the left subtree of the right subtree of A

133 LL Rotation- This rotation is done when the element is inserted in the left subtree of the left subtree of A. To rebalance the tree, it is rotated so as to allow B to be the root with B L and A to be its left subtree and right child and B R and A R to be the left and right subtrees of A. The rotation results in a balanced tree.

134

135 RR Rotation -This rotation is applied if the new element is inserted right subtree of right subtree of A. The rebalancing rotation pushes B upto the root with A as its left child and B R as its right subtree and A L and B L as the left and right subtrees of A

136

137 LR and RL rotations- The balancing methodology of LR and RL rotations are similar in nature but are mirror images of one another. Amongst the rotations, LL and RR rotations are called as single rotations and LR and RL are known as double rotations since LR is accomplished by RR followed by LL rotation and RL can be accomplished by LL followed by RR rotation. LR rotation is applied when the new element is inserted in right subtree of the left subtree of A. RL rotation is applied when the new element is inserted in the left subtree of right subtree of A

138 LR Rotation- this rotation is a combination of RR rotation followed by LL rotation. A A C B AR C AR B A BL C B CR BL CL CR AR CL CR BL CL x x x RRLL

139 RL Rotation-This rotation occurs when the new node is inserted in left subtree of right subtree of A. It’s a combination of LL followed by RR A C T 1 B A B C T 4 T 1 T 2 T 3 T 4 T 2 T 3 NEW NEW RL

140 RL Rotation- This rotation occurs when the new node is inserted in right subtree of left subtree of A. A A T 1 B T 1 C C T 4 T 2 B T 2 T 3 NEW T 3 T 4 NEW RR C A B T1 T2 T3 T4 NEW LL

141

142 Problem: Construct an AVL search tree by inserting the following elements in the order of their occurrence 64, 1, 14, 26, 13, 110, 98, 85 Sol:

143

144 Deletion in an AVL search Tree The deletion of element in AVL search tree leads to imbalance in the tree which is corrected using different rotations. The rotations are classified according to the place of the deleted node in the tree. On deletion of a node X from AVL tree, let A be the closest ancestor node on the path from X to the root node with balance factor of +2 or -2.To restore the balance, the deletion is classified as L or R depending on whether the deletion occurred on the left or right sub tree of A. Depending on value of BF(B) where B is the root of left or right sub tree of A, the R or L rotation is further classified as R0, R1 and R-1 or L0, L1 and L-1. The L rotations are the mirror images of their corresponding R rotations.

145 R0 Rotation- This rotation is applied when the BF of B is 0 after deletion of the node

146

147 R1 Rotation- This rotation is applied when the BF of B is 1

148

149 R-1 Rotation- This rotation is applied when the BF of B is -1

150

151 L rotations are the mirror images of R rotations. Thus L0 will be applied when the node is deleted from the left subtree of A and the BF of B in the right subtree is 0 Similarly, L1and L-1 will be applied on deleting a node from left subtree of A and if the BF of root node of right subtree of A is either 1 or -1 respectively.

152 GRAPH

153 Graph - A graph G consists of : –A set V of elements called the nodes (or points or vertices) –A set E of edges such that each edge e in E is identified with a unique (unordered) pair [u,v] of nodes in V, denoted by e=[u,v] The nodes u and v are called the end points of e or adjacent nodes or neighbors. The edge in a graph can be directed or undirected depending on whether the direction of the edge is specified or not. A graph in which each edge is directed is called a directed graph or digraph. A graph in which each edge is undirected is called undirected graph. A graph which contains both directed and undirected edges is called mixed graph. Let G=(V,E) be a graph and e є E be a directed edge associated with ordered pair of vertices (v 1,v 2 ). Then the edge e is said to be initiating from v 1 to v 2. v 1 is the starting and v 2 is the termination of the edge e.

154

155 An edge in a graph that joins a vertex to itself is called a sling or a loop The degree of a node or vertex u is written deg(u) is the number of edges containing u. The degree of a loop is 2 In a directed graph for any vertex v the number of edges which have v as their initial vertex is called the out-degree of v. The number of edges which have v as their terminal vertex is called the in-degree of v. The sum of in-degree and out-degree of a vertex is called the degree of that vertex. If deg(u)=0, then u is called an isolated node and a graph containing only isolated node is called a null graph The maximum degree of a graph G, denoted by Δ(G), is the maximum degree of its vertices, and the minimum degree of a graph, denoted by δ(G), is the minimum degree of its vertices. A sequence of edges of a digraph such that the terminal vertex of the edge sequences in the initial vertex of the next edge, if exist, is called a path E={(v 1,v 2 ),(v 2,v 3 ),(v 3,v 4 )} A path P of length n from a vertex u to vertex v is defined as sequence of n+1 nodes P=(v 0,v 1,v 2 --------------v n ) such that u=v 0 ; v i-1 is adjacent to v i for i=1,2,3----------n; and v=v n. The path is said to be closed or a circular path if v 0 =v n.

156 The path is said to be simple if all nodes are distinct, with the exception that v 0 may equal v n ; that is P is simple if the nodes v 0,v 1,v 2 --------v n-1 are distinct and the nodes v 1,v 2 ------------v n are distinct. A cycle is closed simple path with length 2 or more. A cycle of length k is called a k-cycle. A graph G is said to be connected if and only if there is a simple path between any two nodes in G. In other words, a graph is connected if it does not contain any isolated vertices. A graph that is not connected can be divided into connected components (disjoint connected subgraphs). For example, this graph is made of three connected components A graph G is said to be complete if every node u in G is adjacent to every node v in G. A complete graph with n vertices (denoted Kn) is a graph with n vertices in which each vertex is connected to each of the others (with one edge between each pair of vertices). In other words, there is path from every vertex to every other vertex. Clearly such a graph is also a connected graph. A complete graph with n nodes will have n(n-1)/2 edges A connected graph without any cycles is called a tree graph or free graph or simply a tree.

157 Here are the five complete graphs:

158 A graph is said to be labeled if its edges are assigned data. G is said to be weighted if each edge e in G is assigned a non negative numerical value w (e) called the weight or length of e. In such a case, each path P in G is assigned a weight or length which is the sum of the weights of the edges along the path P. If no weight is specified, it is assumed that each edge has the weight w (e) =1 Multiple edges- Distinct edges e and e’ are called multiple edges if they connect the same endpoints, that is, if e=[u, v] and e’=[u, v]. Such edges are also called parallel edges and a graph that contains these multiple or parallel edges is called a multigraph. Also a graph containing loops is also not a simple graph but a multigraph.

159 Directed Multi Graph

160 Weighted Graph

161 Representation of a graph-There are two main ways of representing a graph in memory. These are: Sequential Linked List Sequential Representation- The graphs can be represented as matrices in sequential representation. There are two most common matrices. These are: Adjacency Matrix Incidence Matrix The adjacency matrix is a sequence matrix with one row and one column devoted to each vertex. The values of the matrix are 0 or 1. A value of 1 for row i and column j implies that edge e ij exists between v i and v j vertices. A value of 0 implies that there is no edge between the vertex v i and v j. Thus, for a graph with v 1,v 2,v 3 ………..v n vertices, the adjacency matrix A=[a ij ] of the graph G is the n x n matrix and can be defined as:

162 1 if v i is adjacent to v j (if there is an edge between v i and v j ) a ij = 0 if there is no edge between v i and v j Such a matrix that contains entries of only 0 or 1 is called a bit matrix or Boolean matrix. The adjacency matrix of the graph G does depend on the ordering of the nodes in G that is different ordering of the nodes may result in a different adjacency matrix. However the matrices resulting from different orderings are closely related in that one can be obtained from another by simply interchanging rows and columns

163 Suppose G is an undirected graph. Then the adjacency matrix A of G will be a symmetric matrix i.e one in which a ij =a ji for every i and j. If G is a multigraph, then the adjacency matrix of G is the m x m matrix A=(a ij ) defined by setting a ij equal to the number of edges from v i to v j. Consider an Adjacency matrix A representing a graph. Then A 2, A 3 ……..A k of Adjacency matrix A represent the matrices with path lengths 2,3……… k respectively. In other words, if a k (i,j)= the ijth entry of matrix A k then this entry represents the number of paths of length k from node v i to v j.. If now we represent a matrix B r as B r =A+A 2 +A 3 ………A k then each entry of B r represent the number of paths of lengths r or less than r from node v i to v j

164 Example :Consider the graph G. Suppose the nodes are stored in memory in a linear array DATA as follows: DATA: X,Y,Z,W Then we assume that the ordering of the nodes in G as as v1=X, v2=Y,v3=Z, v4=W. The adjacency matrix A of G is 0 0 0 1 A= 1 0 1 1 1 0 0 1 0 0 1 0

165 Path Matrix- Let G be a simple directed graph with m nodes, v 1,v 2,v 3 ………..v m. The path matrix or reachability matrix of G is the m-square matrix P=(p ij ) defined as: 1 if there is a path from v i to v j P ij = 0 Otherwise Suppose there is a path from v i to v j. Then there must be a simple path from v i to v j when v i ≠ v j or there must be a cycle from v i to v j when v i = v j. Since G has only m nodes such a simple path must be of length m-1 or less or such a cycle must have length m or less.

166 Proposition: Let A be the adjacency matrix and let P=(p ij ) be the path matrix of a digraph G. Then P ij =1 if and only if there is a nonzero number in the Adjacency matrix in the ijth entry of the matrix. B m = A+ A 2 + A 3 +……. + A m

167 Linked representation of the graph- The sequential representation of the graph in memory i.e the representation of graph by adjacency matrix has a number of major drawbacks It may be difficult to insert and delete nodes in Graph. This is because the size of array may need to be changed and the nodes may need to reordered which can lead to many changes in the matrix. Also if the number of edges are very less, then, the matrix will be sparse and there will be wastage of memory. Accordingly, graph is usually represented in memory by a linked representation also called an adjacency structure. Specifically, the linked representation of graph contains two lists (or files), a node list NODE and an edge list EDGE, as follows: Node list- Each element in the list NODE will correspond to a node in G(Graph) and it will be a record of the form:

168 Here NODE will be the name or key value of the node, NEXT will be a pointer to the next node in the list NODE and ADJ will be a pointer to the first element in the adjacency list of the node, which is maintained in the list EDGE. The last rectangle indicates that there may be other information in the record such as indegree of the node, the outdegree of the node, status of the node during execution etc. The nodes themselves will be maintained as a linked list and hence will have a pointer variable START for the beginning of the list and a pointer variable AVAILN for the list of available space Edge List- Each element in the list EDGE will correspond to an edge of graph and will be a record of the form: NODENEXTADJ DESTLINK

169 The field DEST will point to the location in the list NODE of the destination or terminal node of the edge. The field LINK will link together the edges with the same initial node, that is, the nodes in the same adjacency list. The third area indicates that there may be other information in the record corresponding to the edge, such as a field EDGE containing the labeled data of the edge when graph is a labeled graph, a field weight WEIGHT containing the weight of the edge when graph is a weighted graph and so on. A D E B C NodeAdjacency List A B C D E B,C,D C C,E C

170

171

172 Traversing a Graph- There are two standard ways of traversing a graph Breadth-first search Depth-First Search The breadth-first search will use a queue as an auxiliary structure to hold nodes for future processing, and analogously, the depth-first search will use a stack During the execution of algorithm, each node N of G (Graph) will be in one of the three states, called the status of N as follows: STATUS=1: (Ready state) The initial state of the node N STATUS=2: (Waiting state) The node N is one the queue or stack, waiting to be processed STATUS=3: (Processed state). The node N has been processed

173 The general idea behind a breadth-first search beginning at a starting node A as follows: Examine the starting node A Examine all neighbors of A Then examine all neighbors of neighbors of A and so on. Keep track of neighbors of node and guarantee that no node is processed more than once. This is accomplished by using a queue to hold nodes that are waiting to be processed and by using a field STATUS which tells the status of any node. The breadth-first search algorithm helps in finding the minimum path from source to destination node

174 Algorithm: This algorithm executes a breadth-first search on a graph G beginning at a starting node A. This algorithm can process only those nodes that are reachable from A. To examine all the nodes in graph G, the algorithm must be modified so that it begins again with another node that is still in the ready state Step 1: Initialize all nodes to the ready state (STATUS=1) Step 2: Put the starting node A in Queue and change its status to the waiting state (STATUS=2) Step 3: Repeat Steps 4 and 5 until Queue is empty: Step 4: Remove the front node N of Queue. Process N and change the status of N to the processed state (STATUS=3) Step 5: Add to the rear of Queue all the neighbors of N that are in the ready state ( STATUS=1), and change their status to the waiting state (STATUS=2) [End of Step 3 Loop] Step 6: Exit

175

176

177 Algorithm: This algorithm executes a depth-first search on a graph G beginning at a starting node A. This algorithm can process only those nodes that are reachable from A. To examine all the nodes in graph G, the algorithm must be modified so that it begins again with another node that is still in the ready state Step 1: Initialize all nodes to the ready state (STATUS=1) Step 2: Push the starting node A onto STACK and change its status to the waiting state (STATUS=2) Step 3: Repeat steps 4 and 5 until STACK is empty Step 4: Pop the top node N of STACK. Process N and change its status to the processed state (STATUS=3) Step 5: Push onto the STACK all the neighbors of N that are still in the ready state (STATUS=1) and change their status to the waiting state (STATUS=2) [End of Step 3 Loop] Step 6: Exit

178 Difference between BFS and DFS The BFS uses a queue for its implementation whereas DFS uses a stack BFS is mostly used for finding the shortest distance between the two nodes in a graph whereas DFS is mostly used to find the nodes that are reachable from a particular node. BFS is called breadth first search as first it processes a node then its immediate neighbors and so on. In other words, FIFO queue puts all its newly generated nodes at the end of a queue which means that shallow nodes are expanded before the deeper nodes. BFS traverses a graph breadth- wise. DFS first traverses the graph till the last reachable node then back tracks the nodes for processing. In other words, DFS expands deepest unexpanded node first first traverses the depth of the graph. BFS ensures that all the nearest possibilities are explored first whereas DFS keeps going as far as it can then goes back to look at other options

179 Dijkstra’s Algorithm- This technique is used to determine the shortest path between two arbitrary vertices in a graph. Let weight w(vi,vj) is associated with every edge (vi,vj) in a given graph. Furthermore, the weights are such that the total weight from vertex vi to vertex vk through vertex vj is w(vi,vj) + w(vj,vk). Using this technique, the weight from a vertex vs (starting of the path) to the vertex vt( the end of the path) in the graph G for a given path (vs,v1),(v1,v2),(v2,v3)…..(vi,vt) is given by w(vs,v1) + w(v1,v2) +w(v2,v3)+….+w(vi,vt) Dijkstra’s method is a very popular and efficient one to find every path from starting to terminal vertices. If there is an edge between two vertices, then the weight of this edge is its length. If several edges exist, use the shortest length edge. If no edge actually exists, set the length to infinity. Edge(vi,vj) does not necessarily have same length as edge (vj,vi). This allows different routes between two vertices that take different paths depending on the direction of travel

180 Dijkstra’s technique is based on assigning labels to each vertex. The label is equal to the distance (weight) from the starting vertex to that vertex. The starting vertex has the label 0 A label can be in one of the two states-temporary or permanent. A permanent label that lies along the shortest path while a temporary label is one that has uncertainty whether the label is along the shortest path. Algorithm: Step 1: Assign a temporary label l(v i )=  to all vertices except v s (the starting vertex) Step 2: [Mark v s as permanent by assigning 0 label to it] l(v s )=0 Step 3: [Assign value of v s to v k where v k is the last vertex to be made permanent] v k =v s Step 4: If l(v i ) > l(v k ) + w(v k,v i ) [weight of the edge from v k to v i ] l(v i )= l(v k ) +w(v k,v i ) Step 5: v k =v i Step 6: If v t has temporary label, repeat step 4 to step 5 otherwise the value of v t is permanent label and is equal to the shortest path v s to v t Step 7: Exit

181 Dijkstra’s Algorithm

182 An Example 1 2 3 4 5 6 2 4 2 1 3 4 2 3 2 Initialize 1 0      Select the node with the minimum temporary distance label.

183 Update Step 2 3 4 5 6 2 4 2 1 3 4 2 3 2 2 4 0      1

184 Choose Minimum Temporary Label 1 3 4 5 6 2 4 2 1 3 4 2 3 2 2 4 0 2   

185 Update Step 1 2 3 4 5 6 2 4 2 1 3 4 2 3 2 2 4 6 4 3 0    The predecessor of node 3 is now node 2

186 Choose Minimum Temporary Label 1 24 5 6 2 4 2 1 3 4 2 3 2 2 3 6 4 0  3

187 Update 1 24 5 6 2 4 2 1 3 4 2 3 2 0 d(5) is not changed. 3 2 3 6 4 

188 Choose Minimum Temporary Label 1 24 6 2 4 2 1 3 4 2 3 2 0 3 2 3 6 4  5

189 Update 1 24 6 2 4 2 1 3 4 2 3 2 0 3 2 3 6 4  5 d(4) is not changed 6

190 Choose Minimum Temporary Label 1 2 6 2 4 2 1 3 4 2 3 2 0 3 2 3 6 4 5 6 4

191 Update 1 2 6 2 4 2 1 3 4 2 3 2 0 3 2 3 6 4 5 6 4 d(6) is not updated

192 Choose Minimum Temporary Label 1 2 2 4 2 1 3 4 2 3 2 0 3 2 3 6 4 5 6 4 6 There is nothing to update

193 End of Algorithm 1 2 2 4 2 1 3 4 2 3 2 0 3 2 3 6 4 5 6 4 6 All nodes are now permanent The predecessors form a tree The shortest path from node 1 to node 6 can be found by tracing back predecessors

194 Recursion- Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. The process is used for repetitive computations in which each action is stated in terms of the previous result. Many iterative (or repetitive) problems can be written in this form. In order to solve a problem recursively, two conditions must be satisfied Problem must be written in a recursive form Problem statement must include a stopping condition.

195 Program to calculate the factorial of a number using recursion #include void main() { int n,f; printf("enter the number"); scanf("%d",&n); f=fact(n); printf("factorial of the number is %d",f); getch(); } fact(int n) { if(n==1) return n; return n* fact(n-1); }

196 When a recursive program is executed, the recursive function calls are not executed immediately. Rather they are placed on a stack until the condition that terminates the recursion is encountered. The stack is a last-in first out data structure in which the successive data items are pushed down upon the preceding items. The data are later removed from the stack in reverse order. The function calls are then executed in reverse order as they are popped off the stack. Thus when evaluating the factorial recursively, the function calls will proceed in the following order

197 n!= n * (n-1)! (n-1)!=n-1 * (n-2)! (n-2)!=n-2 * (n-2)! ……………… ……………………… 2!=2 * 1! The actual values returned will be in the reverse order 1!=1 2!= 2 * 1!= 2*1=2 3!= 3 * 2!= 3*2=6 4!= 4 * 3!=4*6=24 ----------------- n!=n* (n-1)!=……… This reversal in the order of execution is a characteristic of all functions that are executed recursively.

198

199 The use of recursion is not necessarily the best way to approach a problem, even though the problem definition may be recursive in nature. A non recursive implementation may be more efficient in terms of memory utilization and execution speed. Thus use of recursion may involve a tradeoff between the simplicity and performance.

200 Program to print fibonacci series using recursion #include #include void main() { int fibbo(); int i; clrscr(); for(i=1;i<50;i++) printf("%d",fibbo(i)); getch(); } int fibbo(int i) { if(i==1) { return(0); } else if(i==2) { return(1); } else { return(fibbo(i-2)+fibbo(i-1)); } } }

201 Program to find the x to the power of y using recursion void main() { int i, j, res; printf(“enter the two numbers as x to the power y”); scanf(“%d%d”,&i,&j); res=Power(i,j); printf(“ x to the power of y is %d”,res); getch(); } int Power(int x, int y ) { if(y == 0) return 1; y--; return x* Power(x,y); }

202 Towers of Hanoi- Towers of Hanoi is a practical application of recursion. The problem is as follows: Suppose three pegs, labeled A, B and C are given and suppose on peg A there are placed a finite number n of disks with decreasing size. The object of the game is to move the disks from peg A to peg C using peg B as an auxillary. The rules of the game are: Only one disk may be moved one at a time. At no time can a larger disc be placed on a smaller disk ABC

203 Solution for towers of hanoi problem for n=3 is done in seven moves as: Move top disk from peg A to peg C Move top disk from peg A to peg B Move top disk from peg C to peg B Move top disk from peg A to peg C Move top disk from peg B to peg A Move top disk from peg B to peg C Move top disk from peg A to peg C

204 initialA->CA->B C->B A->C B -> A B -> C A -> C

205 Rather than finding a separate solution for each n, we use the technique of recursion to develop a general solution Move top n-1 disks from peg A to peg B Move top disk from peg A to peg C: A->C Move the top n-1 disks from peg B to peg C. Let us introduce a general notation TOWER(N, BEG, AUX, END) to denote a procedure which moves the top n disks from initial peg BEG to final peg END using the peg AUX as a auxillary. For n=1, TOWER(1, BEG, AUX, END) consist of single instruction BEG->END For n>1, solution may be reduced to the solution of following three subproblems:

206 TOWER(N-1, BEG, END, AUX) TOWER(1,BEG, AUX, END) BEG->END TOWER(N-1, AUX, BEG, END) Each of the three sub problems can be solved directly or is essentially the same as the original problem using fewer disks. Accordingly, this reduction process does yield a recursive solution to the towers of Hanoi problem. In general the recursive solution requires 2 n – 1 moves for n disks.

207 Algorithm: TOWER(N, BEG, AUX, END) This procedure produces a recursive solution to the Towers of Hanoi problem for N disks Step 1: If N=1, then: Write: BEG->END Return Step 2: [Move N -1 disks from peg BEG to peg AUX] Call TOWER(N-1, BEG, END, AUX) Write: BEG->END Step 3: [Move N-1 disks from peg AUX to peg END] Call TOWER(N-1, AUX, BEG, END) Step 4: Return

208 TOWER(1,A,C,B)—---A->B TOWER(2,A,B,C) -----A->C TOWER(1,B,A,C) ----------B->C TOWER(3,A,C,B)--------------------------------------------------------------------A->B TOWER(1,C,B,A)---------------- C->A TOWER(2,C,A,B) --------------------------------C->B TOWER(1,A,C,B)----------------A->B TOWER(4,A,B,C)------------------------------------------------------------------A->C TOWER(1,B,A,C) -------------------B->C TOWER(2,B,C,A) ----------------------------------B->A TOWER(1,C,B,A) --------------------C->A TOWER(3,B,A,C)---------------------------------------------------------B->C TOWER(1,A,C,B) ------------------- A-> B TOWER(2,A,B,C) ------------------------------------A->C TOWER(1,B,A,C) --------------------B->C

209 Operations on Graph Suppose a graph G is maintained in memory by the linked list representation GRAPH(NODE,NEXT,ADJ,START,AVAILN,DEST,LINK,AVAIL E) The various operations possible on graph are insertion, deletion and searching a node in a graph.

210 Algorithm: INSNODE( NODE, NEXT, ADJ, START, AVAIL, N ) This algorithm inserts a node N in a graph G Step 1: If AVAIL:=NULL, then Write: ‘OVERFLOW’ Return Step 2: [Remove node from AVAIL List] Set NEW:=AVAIL and AVAIL:=LINK[AVAIL] Step 4: [Insert node in the NODE list] Set NODE[NEW]:=N, ADJ[NEW]:=NULL, NEXT[NEW]:=START and START:=NEW Step 5: Return

211 Algorithm: INSEDGE(NODE, NEXT, ADJ, START, DEST, LINK, AVAIL, A,B) This algorithm inserts an edge in a graph (A,B) where A and B are the two nodes in the graph Step 1: CALL FIND(NODE,NEXT,START,A,LOCA) Step 2: CALL FIND(NODE, NEXT, START, B, LOCB) Step 3: If AVAIL:=NULL, then Write: ‘OVERFLOW’ Return Step 4: [Remove node from AVAIL List] Set NEW:=AVAIL and AVAIL:=LINK[AVAIL] Step 5: [Insert LOCB in the list of successor of A] Set DEST[NEW]:=LOCB, LINK[NEW]:=ADJ[LOCA] and ADJ[LOCA]:=NEW Step 6: Return

212 Algorithm: FIND (INFO,LINK,START,ITEM,LOC) Find the first node containing the ITEM else sets the LOC to NULL Step 1: Set PTR:=START Step 2: Repeat while PTR NULL If ITEM=INFO[PTR], then Set LOC:=PTR Return Else PTR=LINK[PTR] [End of Loop] Step 3: Set LOC:=NULL Step 4: Return

213 Algorithm: Algorithm to delete a node from a graph Step 1: Find the location LOC of the node N in G Step 2: Delete all edges ending at N; that is delete LOC from the list of successors of each node M in G Step 3: Delete all edges beginning at N. This is accomplished by finding the location BEG of the first successor and the location END of the last successor of N and then adding the successor list of N to the free AVAIL list Step 4: Delete N itself from the list NODE

214 Last year question paper selected questions

215 Program to implement Breadth First search in a graph We are using linked list implementation of the graph struct node { int info; struct node* next; struct edge* adj; int status; }; struct edge struct queue { { struct node* dest; struct node* n1; struct node* link; struct queue* link; } ; }; struct queue* front, rear; front=rear=NULL; This is assumed that we have a graph in which we want to apply breadth first search to find the path from node1 to node2

216 // This module breadth first searches the graph void bfs ( struct node* node1, struct node* node2, struct node* start) { struct node* ptr,*item; struct edge* edge1; ptr=start; while(ptr!=NULL) { ptr->status=1; ptr=ptr->next; } ptr=start; ptr->status=2; insert(ptr); while(front!=NULL) { item=del(); item->status=3; printf(“%d”,item->info); edge1=item->adj; while(edge1-dest!=NULL) { if(edge1->dest->status==1) { edge1->dest->status=2; insert(edge1->dest); } edge1=edge1->link; }

217 void insert(struct node* ptr) { struct queue* new1; new1=(struct queue*)malloc(sizeof(struct queue)); new1->n1=ptr; new1->link=NULL; if(front==NULL) { front=rear=new1; return; } rear->link=new; new=rear; return; } struct node* del() { struct node* n2; n2=front->n1; if(front==NULL) { printf(“underflow”); return; } else if(front==rear) { front=rear=NULL; } else front=front->link; return n2; }


Download ppt "CIRCULAR LINKED LIST. Circular Linked List- A circular linked list is a linked list in which last element or node of the list points to first node. For."

Similar presentations


Ads by Google