Attribution Non-Commercial (BY-NC)

651 visualizações

Attribution Non-Commercial (BY-NC)

- CS2405 Computer Graphics Lab Manual
- Cse Lab Manual
- DSA Lab Manual -RMDEC
- Ds Lab Manual
- Oops Lab Cs2209
- CSC 251 - Final Study Guide
- (2) CS2209-Oops Lab Manual
- datastructures lab programs
- Rolling the Dice Faster
- Multi Way
- CS2401 Computer Graphics UNIT I Notes
- CS2358 Lab Manual
- Digital Lab Manual for CSE & IT - Anna Univeristy Chennai Syllabus - 2012
- CSI2132 - Assignment 3 Answers
- AnyBody Tutorials
- Data Structures
- 073_2018__set_a
- B
- InfoGlue - User Manual for Version 2.5.0
- Phast7.0 ReleaseLetter&Note

Você está na página 1de 33

CS 2208 DATA STRUCTURES LAB LIST OF PROGRAMS To develop programming skills in design and implementation of data structures and their applications. 1. Implement singly and doubly linked lists. 2. Represent a polynomial as a linked list and write functions for polynomial addition. 3. Implement stack and use it to convert infix to postfix expression 4. Implement a double-ended queue (dequeue) where insertion and deletion operations are possible at both the ends. 5. Implement an expression tree. Produce its pre-order, in-order, and postorder traversals. 6. Implement binary search tree. 7. Implement insertion in AVL trees. 8. Implement priority queue using binary heaps 9. Implement hashing with open addressing. 10. Implement Prim's algorithm using priority queues to find MST of an Undirected graph.

1 DS LAB MANUAL

Implementation of stack 1. Write a C program to demonstrate the working of a stack of size N usingan array. The elements of the stack may be assumed to be of typeinteger. The operations to be supported are: (a) Push (b) Pop (c) Display The program should print appropriate messages for stack overflow, stackunderflow, and stack empty.

Description of Stack A stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have any abstract data type as an element, but is characterized by only three fundamental operations: push, pop and stack top. The push operation adds a new item to the top of the stack, or initializing the stack if it is empty, but if the stack is full and does not contain more space to accept the given item it is considered as an Overflow state (It means that the stack is overloaded or no more space for new item). The pop operation removes an item from the top of the stack. A pop either reveals previously concealed items, or results in an empty stack, but if the stack is empty then it goes under underflow state (It means no items are present in stack to be removed). The stack top operation removes the data from top most position without deleting it and returns it to user, the same underflow state can also occur in stack top operation if stack is empty.

Algorithm Push(S, N, top, e) // S is a static array S [0...N - 1] // N is the maximum size of the stack // top is the stack pointer // e is the element to be pushed if top = N - 1 then Write "Stack Overflow" else top top + 1 S[top] e end Push. Algorithm Pop(S, N, top) // S is a static array S [0...N - 1] // N is the maximum size of the stack // top is the stack pointer // temp is a local variable to return the popped element if top = -1 then return -1

2 DS LAB MANUAL

else temp S[top] top top - 1 return temp end Pop. Sample Input Stack size N = 6 Menu 1.Push 2.Pop 3.Display 4.Exit Enter the choice : 1 10 Enter the choice : 1 20 Enter the choice : 1 30 Enter the choice : 3 10 20 30 Enter the choice : 2 Item has been popped Enter the choice : 3 10 20

2. Write a C program to simulate the working of a queue of integers using an array. Provide the following operations: (a) Insert (b) Delete (c) Display Description of Queue The queue data structure is characterized by the fact that additions are made at the end,or tail, of the queue while removals are made from the front, or head, of the queue. Queue is a data structure that maintain "First In First Out" (FIFO) order. And canbe viewed as people queueing up to buy a ticket. In programming, queue isusually used as a data structure for BFS (Breadth First Search).

3 DS LAB MANUAL

Suppose we have a queue represented by an array queue [10], which is empty to start with. The values of front and rear variable upon different actions are mentioned in {}. queue [10]=EMPTY {front=-1, rear=0} add (5) Now, queue [10] = 5 {front=0, rear=1} add (10) Now, queue [10] = 5, 10 {front=0, rear=2} retrieve () [It returns 5] Now, queue [10] = 10 {front=1, rear=2} retrieve () [now it returns 10] Now, queue [10] is again empty {front=-1, rear=-1}

Algorithm Algorithm enqueue(Q, N, r, e) // Q is a static array Q[0..N - 1] // N is the maximum size of the Queue // r - rear pointer // e - element to be added

4 DS LAB MANUAL

if r = N - 1 then Write "Queue is Full" else r r + 1 Q[r] e end enqueue. Algorithm dequeue(Q, N, f, r) // Q is a static array Q[0..N - 1] // N is the maximum size of the Queue // f and r - front and rear pointers if f >r then Write "Queue Underflow" else temp Q[f] if f = r // only one element in queue f r 0 // re-initialize queue pointers else f f + 1 return temp end enqueue. Sample Input and Output Queue Size n =5 Menu 1. Enqueue 2. Dequeue 3. Display 4. Exit Enter the choice : 1 10 Enter the choice : 1 20 Enter the choice : 1 30 Enter the choice : 3 10 20 30 Enter the choice : 2 Item has been dequeued Enter the choice : 3 20 30

5 DS LAB MANUAL

Write a C program using dynamic variables and pointers to construct a singly linked list consisting of the following information in each node: student id (integer), student name (character string), and semester (integer). The operations to be supported are: a) The insertion operation (i) At the front of the list (ii) At the back of the list (iii) At any position in the list b) Deleting a node based on student id. If the specified node is not present in the list an error message should be displayed. Both the options must be demonstrated. c) Searching a node based on student id and update the information content. If the specified node is not present in the list an error message should be displayed. Both the options must be demonstrated. Displaying all nodes in the list. (Note: The question may be asked as one of a/b/c with d).

A linked list is a data structure that consists of a sequence of nodes each of which contains a reference (i.e., a link) to the next node in the sequence.

The following code inserts a node after an existing node in a singly linked list. The diagram shows how it works. Inserting a node before an existing one cannot be done directly; instead, you have to keep track of the previous node and insert a node after it.

we have functions for removing the node after a given node, and for removing a node from the beginning of the list. The diagram demonstrates the former. To find and remove a particular node, one must again keep track of the previous element.

6 DS LAB MANUAL

Algorithm Algorithm InsertFirst(p, e) // p - pointer to a linked list // e - element to be added // Getnode() returns a new node q Getnode() info(q) e next(q) p p q return p end InsertFirst. Algorithm InsertAfter(p, x, e) // p - pointer to a linked list // Getnode() returns a new node // x - key node after which e is inserted // e - element to be added k p while k NIL and info(k) x do // find the key node k next(k) if k = NIL then Write "Node not found" return p q Getnode() info(q) e next(q) next(k) next(k) q return p end InsertAfter. Algorithm InsertLast(p, e) // p - pointer to a linked list // Getnode() returns a new node // e - element to be added if p = NIL then

7 DS LAB MANUAL

return p k p while next(k) NIL do // find the last node k next(k) q Getnode() info(q) e next(k) q next(q) NIL return p end InsertLast. Algorithm DeleteNode(p, x) // p - pointer to linked list // x - key node to be deleted // k and pred temporary variables k p; pred while k info(k x do // find the key node pred k k next(k) if k = NIL then Write "Node not found" else if pred = NIL // only one node in the list then p next(p) else next(pred next(k) return p end DeleteNode. Algorithm SearchNode(p, x) // p - pointer to a linked list // x - key node to be searched // k - temporary variable k p while k info(k x do // find the key node k next(k) if k = NIL then return false // key not found else return true // key found end SearchNode.

8 DS LAB MANUAL

Sample Input and Output Main Menu 1. Creation of linked list. 2. Insertion 3. Deletion 4. Display 5. Search 6. Exit Enter the choice: 1 Enter the nodes info: Enter stud id : 1 Enter Student name : Alice Enter Semester: 3 Node has been created . Enter the choice: 2 Sub Menu 1. Insertion at beg 2. Insertion at Middle 3. Insertion at end 4. Display 5. Return to Main menu Enter the choice: 1 Enter the nodes info: Enter stud id: 2 Enter Student name: Arun Enter Semester: 4 Node has been inserted Enter the choice : 4 1---- Alice3 - 2---Arun4 -

3 B. Write a C program to support the following operations on a doubly linked list where each node consists of integers. (a) Create a doubly linked list by adding each node at the front. (b) Insert a new node to the left of the node whose key value is read as an input. (c) Delete the node of a given data, it is found, otherwise display appropriate message. (d) Display the contents of the list. Description of Doubly linked list Adoubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields, called links, that are references to the previous and to the next node in the sequence of nodes. The beginning and ending nodes' previous and next links, respectively, point to some kind of terminator, typically a sentinel node or null, to facilitate traversal of the list. If there is only one sentinel node, then the list is circularly linked via the sentinel node. It can be conceptualized as two singly linked lists formed from the same data items, but in opposite sequential orders.

9 DS LAB MANUAL

Inserting a node These symmetric functions insert a node either after or before a given node, with the diagram demonstrating after:

Algorithm InsertFront(p, e) // p list pointer // e - element to be pushed q info(q e prev(q next(q p if p then prev(p q p q return p end InsertFront. Algorithm InsertAfter(p, x, e) // p - pointer to a linked list // x - key node after which e is inserted // e - element to be added k p while k info(k x do // find the key node k next(k) if k = NIL then Write "Node not found" return p q info(q e if next(k then

10 DS LAB MANUAL

next(q next(k) prev(q k next(k q prev(next(k q else // key node is at the end next(q next(k q prev(q k end InsertAfter. Algorithm DeleteNode(p, x) // p - pointer to a linked list // x - key node to be deleted // k address of key node k p while k info(k x do // find the key node k next(k) if k = NIL then Write "Node not found" return p // key found if k = p and next(k) = NIL // only one node in the list then p return p if next(k) = NIL // last node is key then next(prev(k next(k) else if prev(k) = NIL // first node is key then p next(p) prev(p) else next(prev(k next(k) prev(next(k prev(k) return p end DeleteNode.

Sample Input and Output Main Menu 1 Creation of linked list. 2 Insertion 3 Deletion

11 DS LAB MANUAL

4 Display 5 Search 6 Exit Enter the choice: 1 Enter the element : 10 Enter the choice 1 Enter the element : 20 Enter the choice 2: Enter the element : 30 Enter the choice : 4 10- ---20 --- -> 30

4.Represent a polynomial as a linked list and write functions for polynomial addition. Each node will need to store the variable x,the exponent and the coefficient for each term.Let phead1, phead2 and phead3 represent the pointers ofthe three lists under consideration. Let each node contain two integers exp and coff . Let us assume that the two linked lists already contain relevant data about the two polynomials. Also assume that we have got a function append to insert a new node at the end of the given list.

A Polynomial has mainly two fields. exponent and coefficient. Node of a Polynomial:

Algorithm p1 = phead1; p2 = phead2; Let us call malloc to create a new node p3 to build thethird list p3 = phead3; /* now traverse the lists till one list gets exhausted */ while ((p1 != NULL) || (p2 != NULL))

12 DS LAB MANUAL

{ / * if the exponent of p1 is higher than that of p2 thenthe next term in final list is going to be the node of p1* / while (p1 ->exp > p2 -> exp ) { p3 -> exp = p1 -> exp; p3 -> coff = p1 -> coff ; append (p3, phead3); /* now move to the next term in list 1*/ p1 = p1 -> next; } / * if p2 exponent turns out to be higher then make p3same as p2 and append to final list * / /* now consider the possibility that both exponents aresame , then we must add the coefficients to get the term forthe final list */ while (p1 ->exp = p2 -> exp ) { p3-> exp = p1-> exp; p3->coff = p1->coff + p2-> coff ; append (p3, phead3) ; p1 = p1->next ; p2 = p2->next ; } } /* now consider the possibility that list2 gets exhausted,and there are terms remaining only in list1. So all thoseterms have to be appended to end of list3. However, you donot have to do it term by term, as p1 is already pointing toremaining terms, so simply append the pointer p1 to phead3*/ Sample Input Output Enter the first polynomial Enter the Exp,Co-eff and exponential term : 10 2 Enter the Exp,Co-eff and exponential term : 15 1 Enter the Exp,Co-eff and exponential term : 2 Enter the second polynomial Enter the Exp,Co-eff and exponential term : 10 2 Enter the Exp,Co-eff and exponential term : 15 1 Enter the Exp,Co-eff and exponential term : 2 Third polynomial 20 x 2 30 x 1 4.

5. Program to convert infix to postfix using stack. Applications of stack 1. Expression evaluation 2. Backtracking (game playing, finding paths, exhaustive searching)

13 DS LAB MANUAL

3. Memory management, run-time environment for nested language features. Infix, Prefix and Postfix Notation Arithmetic expressions are written with the operation between the two operands: a+b or c/d. If we write a+b*c, however, we have to apply precedence rules to avoid the ambiguous evaluation (add first or multiply first?). There's no real reason to put the operation between the variables or values.

Postfix

Postfix expressions are easily evaluated with the aid of a stack. Infix transformation to Postfix This process uses a stack as well. We have to hold information that's expressed inside parentheses while scanning to find the closing ')'. We also have to hold information on operations that are of lower precedence on the stack. The algorithm is: 1. Create an empty stack and an empty postfix output string/stream 2. Scan the infix input string/stream left to right 3. If the current input token is an operand, simply append it to the output string (note the examples above that the operands remain in the same order) 4. If the current input token is an operator, pop off all operators that have equal or higher precedence and append them to the output string; push the operator onto the stack. The order of popping is the order in the output. 5. If the current input token is '(', push it onto the stack 6. If the current input token is ')', pop off all operators and append them to the output string until a '(' is popped; discard the '('. 7. If the end of the input string is found, pop all operators and append them to the output string.

14 DS LAB MANUAL

This algorithm doesn't handle errors in the input, although careful analysis of parenthesis or lack of parenthesis could point to such error determination. Apply the algorithm to the above expressions. Infix expression: a+b*c-d/e*f

Rules for converting the infix string: Starting from the left hand end, inspect each character of the string 1. if its an operand append it to the postfix string 2. if its a ( push it on the stack. 3. if its an operator if the stack is empty, push it on the stack else pop operators of greater or equal precedence and append them to the postfix string, stopping when a ( is reached, an operator of lower precedence is reached, or the stack is empty; then push the operator on the stack 4. if its a ) pop operators off the stack, appending them to the postfix string, until a ( is encountered and pop the ( off the stack. 5. When the end of the infix string is reached pop any remaining operators off the stack and append them to the postfix string Sample Input Output An Example: 7-(2*3+5)*(8-4/2) 723*5+842/-*Remaining Infix String 7-(2*3+5)*(8-4/2) -(2*3+5)*(8-4/2) (2*3+5)*(8-4/2) 2*3+5)*(8-4/2) *3+5)*(8-4/2) 3+5)*(8-4/2) +5)*(8-4/2) 5)*(8-4/2) *(8-4/2) 8-4/2) 8-4/2)

DS LAB MANUAL

15

Rule Used

1 3 2 1 3 3 3 4 3

1 3 3 1 4&5

6. Implement a double-ended queue (dequeue) where insertion and deletionoperations are possible at both the ends.(USE ARRAY) A double-ended queue, or deque, supports insertion and deletion from the front and back The deque supports six fundamental methods InsertFirst(S:ADT, o:element):ADT - Inserts e at the beginning of deque InsertLast(S:ADT, o:element):ADT - Inserts e at end of deque RemoveFirst(S:ADT):ADT Removes the first element RemoveLast(S:ADT):ADT Removes the last element First(S:ADT):element and Last(S:ADT):element Returns the first and the last elements Dequeue is also known as Remove or Serve. It is used when elements are taken off the front of the queue - the person at the grocery till has paid and left. Another type of queue called double-ended queue also called Deque is discussed in this section. Deque is a special type of data structure in which insertions and deletions will be done either at the front end or at the rear end of the queue. The operations that can be performed on deques are Insert an item from front end Insert an item from rear end Delete an item from front end Delete an item from rear end Display the contents of queue

16 DS LAB MANUAL

The three operations insert rear, delete front and display and the associated operations to check for an underflow and overflow of queue have already been discussed in ordinary queue. In this section, other two operations i.e., insert an item at the front end and delete an item from the rear end are discussed.

a) Insert at the front end Consider queue shown in above fig (a). Observe that, the front end identified by f is 0 and rear end identified by r is -1. Here, an item can be inserted first by incrementing r by 1 and then insert an item. If the front pointer f is not equal to 0 as shown in above fig. (b), an item can be inserted by decrementing the front pointer .f by 1 and then inserting an item at that position. Except for these conditions, it is not possible to insert an item at the front end. For example, consider the queue shown in above figure (c). Here, an item 10 is already present in the first position identified by f and so, it is not possible to insert an item.

Algorithm 1. Create a data structure for double ended queue (Array) 2. Create a menu for choosing various options like a. add at front b. add at rear c. Delete from front d. delete from rear. 3. Initialize 2 pointers front and rear as queue max size by 2. 4. If an item is to be inserted at the front end , decrement the front pointer by 1 and insert an item. 5. If front reaches -1 then no more items can be added. 6. If an item is inserted at the rear end , increment rear by 1 and insert an item

17 DS LAB MANUAL

7. If an item is to be deleted from front increment the front pointer by 1 and remove the item 8. If an item is to be deleted from rear remove the item and decrement the pointer by 1. 9. Display all items 10. End.

1. 2. 3. 4. 5. 6.

Creation of queue add at front add at rear Delete from front Delete from rear. Display Enter the choice : 1 10 Enter the choice : 3 20 Enter the choice : 3 30 Enter the choice : 6 10 20 30 Enter the choice : 2 15 Enter the choice : 2 17 Enter the choice : 6 17 15 10 20 30 Enter the choice : 4 Enter the choice : 2 Enter the choice : 5 17 15 10 20

18 DS LAB MANUAL

7.

A tree-traversal refers to the process of visiting (examining and/or updating) each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited. To traverse a non-empty binary tree in preorder, perform the following operations recursively at each node, starting with the root node: Visit the root. Traverse the left subtree. Traverse the right subtree. To traverse a non-empty binary tree in inorder (symmetric), perform the following operations recursively at each node: Traverse the left subtree. Visit the root. Traverse the right subtree. To traverse a non-empty binary tree in postorder, perform the following operations recursively at each node: Traverse the left subtree. Traverse the right subtree. Visit the root.

Preorder traversal sequence: F, B, A, D, C, E, G, I, H (root, left, right) Inorder traversal sequence: A, B, C, D, E, F, G, H, I (left, root, right); note how this produces a sorted sequence Postorder traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root)

19 DS LAB MANUAL

int data; node * left; node* right; } 2. Construct a tree as per procedure N is node to insert. 3. If n is new node it will be treated as root node. 4. If not by checking the node value it will be inserted 5. If less than root node it will be inserted as left node 6. If greater than root node it will be inserted as right node. 7. Create a menu for choosing between traversal. 8. If pre order traversal then if(p==null) return; { visit(p->data); preOrder(p->left); preOrder(p->right); } 9. If post order traversal then If(p==null) return; { posttrav(p->leftlink) posttrav(p->rightlink) visit(p->data) } 10. If in order traversal then If (p not null) intrav(p->leftlink) print (p->data) intrav(p->rightlink) endif 11. To return the number of elements in the binary tree int size(p) if (p == null) return 0 else return (size (p->left) + size(p->right) + 1) end if

20 DS LAB MANUAL

Sample Input output Main menu 1. Creation 2. Insertion 3. Preorder 4. Postorder 5. Inorder 6. Exit Enter the choice : 1 Enter the data : A Enter the choice : 2 Enter the data : B Enter the choice : 2 Enter the data : C Enter the choice : 2 Enter the data : D Enter the choice : 2 Enter the data : E Enter the choice : 2 Enter the data : F Enter the choice : 2 Enter the data : G Enter the choice : 2 Enter the data : H Enter the choice : 2 Enter the data : I Enter the choice : 3 F, B, A, D, C, E, G, I, H (root, left, right) Enter the choice : 4 A, B, C, D, E, F, G, H, I (left, root, right) Enter the choice : 5 A, C, E, D, B, H, I, G, F (left, right, root)

21 DS LAB MANUAL

8. Implement binary search tree and do the following operations a. Find the minimum node b. Insertion c. Deletion A binary search tree (BST), which may sometimes also be called an ordered or sorted binary tree, is a node-based binary tree data structure which has the following properties 1. The left sub tree of a node contains only nodes with keys less than the node's key. 2. The right sub tree of a node contains only nodes with keys greater than the node's key. 3. Both the left and right sub trees must also be binary search trees.

Algorithm 1. Declare the structure of node for tree as struct node { int key_value; node *left; node *right; }; 2. Get the value for key. 3. if root is empty then root else

22 DS LAB MANUAL

v;

node

root; loop {an infinite loop; we will explicitly exit the loop after v is inserted}

4. if v is less than or equal to value stored in node then if the left child of node exists then node else insert v as the left child of node; exit the loop; end if else if the right child of node exists then node else insert v as the right child of node; exit the loop; end if end if end loop end if 5. Routine for finding an element in the tree right child of node; left child of node;

//Purpose: find Item X in the Tree //Inputs: data object X (object to be found), binary-search-tree node node // Output: bst-node n containing X, if it exists; NULL otherwise. find(X, node)f if(node = NULL) return NULL if(X = node:data) return node

23 DS LAB MANUAL

else if(X < node:data) return find(X,node:leftChild) else // X > node:data return find(X,node:rightChild) 6. Deleting a node Case 1 : if the node is a leaf Delete it immediately Case 2 :if the node has one child Adjust a pointer from the parent to bypass that node

Case 3: if the node has 2 children replace the key of that node with the minimum element at the right subtree delete the minimum element Has either no child or only right child because if it has a left child, that left child would be smaller and would have been chosen. So invoke case 1 or 2. 7. Routine to find the minimum and maximum node in a binary search tree The binary-search-tree property guarantees that: a. The minimum is located at the left-most node. b. The maximum is located at the right-most node. Tree-Minimum(x) Tree-Maximum(x) 1. whileleft[x] NIL 1. whileright[x] NIL 2. dox left[x] 2. dox right[x] 3. returnx 3. returnx

24 DS LAB MANUAL

Main Menu 1. Creattion 2. Deletion 3. Display 4. Minimum Node 5. Searching for node Enter the choice: 1 Do u want to continue (Y/N) : Y Enter the element : 8 Do u want to continue (Y/N) : Y Enter the element : 10 Do u want to continue (Y/N) : Y Enter the element : 6 Do u want to continue (Y/N) : Y Enter the element : 13 Do u want to continue (Y/N) : Y Enter the element : 7 Do u want to continue (Y/N) : Y Enter the element : 3 Do u want to continue (Y/N) : Y Enter the element : 1 Do u want to continue (Y/N) : Y Enter the element : 4 Do u want to continue (Y/N) : Y Enter the element : 13 Do u want to continue (Y/N) : N Main Menu 1. Creation 2. Deletion

25 DS LAB MANUAL

3. Display 4. Minimum Node 5. Searching for node Enter the choice : 2 8. Deleting a node with single child 9. Deleting a node with 2 childs. Enter the choice : 8 Enter the element value :14 1 -- 3 4 -6 7 -8-10--13

9. Implement insertion in AVL trees. Insert the numbers in Binary Search Tree (BST)pattern. 2. Before the next number is inserted, perform thefollowing operations :a) Find out the balance factor of each node. b) Balance Factor of a node = (Maximum numberof levels that can be reached in right sub-tree ) ( Maximum number of levels that can bereached in left sub tree ) [WE TAKE LEVEL OF THE STARTING NODEAS 0] c) If any of the Balance Factor is (-2) or (2),perform required rotation according to the algorithm given below. If two nodes have (2/-2)then select the lowest node in level. d) The tree now become balanced, i.e. no nodehas Balance Factor (-2) or (2). Continue fromstep 1. Rotation Algorithm [Right heavy (B.F. = 2), Left heavy (B.F. = -2)] IF tree is right heavy (B.F. = 2) { IF tree's right sub tree is left heavy (B.F. = -2 / -1) { Perform Left-Right (LR) rotation } ELSE { Perform Left rotation } } ELSE IF tree is left heavy (B.F. = -2) { IF tree's left sub tree is right heavy (B.F. = 2 / 1) {

26 DS LAB MANUAL

Perform Right-Left Rotation (RL) rotation } ELSE { Perform Right rotation } } Steps for deletion:1. Delete the number in Binary Search Tree (BST)pattern. This can be done by the following operations:a) If the node has no leaf node, just remove it from thetree. b) If the node has only one sub-tree (left/right), justremove the node and replace it by its immediatechild node. c) If the node has two sub-trees (left/right), remove thenode and replace it by its immediate inordertraversal node (i.e. the node that will be written justafter the deleted node in inorder traversal). When the deletion of node and reordering of the treeis done, continue from the next step. 2. Perform the following operations:a) Find out the balance factor of each node. b) Balance Factor of a node = (Maximum number oflevels that can be reached in right sub-tree ) (Maximum number of levels that can be reached inleft sub tree) [WE TAKE LEVEL OF THE STARTINGNODE AS 0] c) If any of the Balance Factor is (-2) or (2), performs required rotation according to the algorithm given above. If two nodes have (2/-2) then select the lowest node in level. Sample Input and Output Enter the element : 3 Enter the element : 2 Enter the element : 1 3-21 Single rotation : 1-2-3 10. Implement priority queue using binary heaps A priority queue is an abstract data type in computer programming. It is exactly like a regular queue or stack data structure, but additionally, each element is associated with a "priority".

stack: elements are pulled in last-in first-out-order (e.g. a stack of papers) queue: elements are pulled in first-come first-served-order (e.g. a line in a cafeteria)

27

DS LAB MANUAL

priority queue: elements are pulled highest-priority-first (e.g. cutting in line, or VIP service).

Priority queue A priority queue is a queue where each element has a priority and the element with the highest priority is at the front of the queue and will be the first element to be removed. To be contrasted with the stack and queue data structures which use LIFO and FIFO respectively. A heap is another way to implement a priority queue. It has the logical structure of a complete binary tree which satisfies the heap condition. A heap can be implemented using pointers (each node 3 pointers parent, left child and right child) or much more simply using a partially ordered array. In the array implementation where the highest priority key is in array position 1 we have: parent(i) = i/2 lchild(i) = 2i rchild(i) = 2i+1 Here parent(i) is the array index of the parent of node i. A heap is partially ordered by satisfying the heap condition. Heap array

Search Key 10 7 9 5 6 8 1 4 2 3

Item Tom Pam Sue Mary Mike Sam Ann Joe Bob Jane

28

DS LAB MANUAL

the only constraint is that any parent node must have a search key that is the search key of both of itschildren. Note that this is sufficient to ensure that the item with the greatest search key in the heap is stored at the root. In the array-based representation we have discussed, the item with the greatest search key will always be at position 0 of the array. Heap Operations in Pseudocode Key // a type, usually int, describes type of values in heap int N // number of elements in array or heap Key h[ ] // heap array of size N containing items of type Key. The heap array h[] and N will be encapsulated inside the heap object. insert(Key x) h[++N] = x siftUp( N) // siftUp from position k. The key or node value at position k // may be greater that that of its parent at k/2 // k is a position in the heap array h siftUp( int k) v = h[k] h[0] = while( v > h[k/2] ) h[k] = h[k/2]

29 DS LAB MANUAL

k = k/2 h[k] = v // Key of node at position k may be less than that of its // children and may need to be moved down some levels // k is a position in the heap array h siftDown(int k) v = h[k] while( k N/2 ) // while node at pos k has a left child node j = 2k if( j < N h[j] < h[j+1]) ++j if( v h[j] ) break h[k] = h[j]; k = j h[k] = v Key remove( ) v = h[1] h[1] = h[N--] siftDown( 1) return v

11. Implement hashing with open addressing. In open addressing, the hash function h(k; i) has two parameters. The parameter k is the key to be hashed and the parameter i represents the probe number. Hash_Insert (T, k) // Insert key k into T. If successful, returns the index // where k was inserted. i=0 repeat j = h(k,i) if (T[j] = NULL) T[j] = k // Key successfully inserted. return j else i=i+1 until (i = m) Print "Hash table overflow" and stop. Hash_Search (T, k) // Return the index of the table entry containing the key k // if it is in T; return NULL otherwise. 1. i = 0 2. repeat j = h(k,i) if (T[j] = k) return j // Successful search. else

30 DS LAB MANUAL

i=i+1 until ( (T[j] = NULL) or (i = m) ). return NULL. 12. Implement Prim's algorithm using priority queues to find MST of an undirected graph. Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a connectedweightedundirected graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. Designate one node as the start node Add the start node to the priority queue of open nodes. WHILE (there are still nodes to be added to the closed list)

Remove a node from priority queue of open nodes, designate it as current node. IF (the current node is not already in the closed list) { IF the node is not the first node removed from the priority queue, add the minimal edge connecting it with a closed node to the minimal spanningtree. Add the current node to the closed list. FOR each successor of current node IF (the successor is not already in the closed list OR the successor isnow connected to a closed node by an edge of lesser weight thanbefore) Add that successor to the priority queue of open nodes; 1. for each u V 2. doD [u ] 3. D[ r ] 0 4. PQ make-heap(D,V, {})//No edges 5. T 6. 7. whilePQ do 8. (u,e ) PQ.extractMin() 9. add (u,e) to T 10. for each v Adjacent (u )

31 DS LAB MANUAL

do if v PQ&&w( u, v ) <D [ v ] then D [ v ] w (u, v) PQ.decreasePriorityValue ( D[v], v, (u,v )) 14. return T // T is a must. Lines 1-5 initialize the priority queue PQ to contain all Vertices. Ds for all vertices except r, are set to infinity. r is the starting vertex of the T The T so far is empty Add closest vertex and edge to current T Get all adjacent vertices, update D of each adjacent non-tree vertex, save the current minimum weight edge, and restore the heap property. Note that handle[v] can be used to check v PQ

32 DS LAB MANUAL

- CS2405 Computer Graphics Lab ManualEnviado porDhilip Prabakaran
- Cse Lab ManualEnviado poreffffffff
- DSA Lab Manual -RMDECEnviado porSai Prashanth
- Ds Lab ManualEnviado porAyyanu Chelliah
- Oops Lab Cs2209Enviado porJothimani
- CSC 251 - Final Study GuideEnviado porFVCproductions
- (2) CS2209-Oops Lab ManualEnviado porMaha June
- datastructures lab programsEnviado porsuresh
- Rolling the Dice FasterEnviado pordignor.sign3941
- Multi WayEnviado porArosh Lakshan
- CS2401 Computer Graphics UNIT I NotesEnviado porGanga Dharan
- CS2358 Lab ManualEnviado porDevi Ram
- Digital Lab Manual for CSE & IT - Anna Univeristy Chennai Syllabus - 2012Enviado porsundarkmp5325
- CSI2132 - Assignment 3 AnswersEnviado porjreev086
- AnyBody TutorialsEnviado porromulozg
- Data StructuresEnviado porankurlala
- 073_2018__set_aEnviado porBiju Angalees
- BEnviado porAnonymous V7P5fNQI
- InfoGlue - User Manual for Version 2.5.0Enviado porTeodofilus Kumalo
- Phast7.0 ReleaseLetter&NoteEnviado porgirish19
- 67976648 Complete Oracle PaperEnviado porsanjay95
- DSA Some Useful StatementsEnviado porSanjeev Praja
- An Introduction to Binary Search Trees and Balanced TreesEnviado porDimitris Stathopoulos
- Linked Lists QuestionsEnviado porNeeraj Chaudhary
- Data Structures Assignment 4Enviado porPriyanshu Jain
- STACKS, QUEUES, AND LINKED LISTS.pdfEnviado porganeshgtp
- q Tree NotesEnviado porfallthislol
- Appendix bEnviado porVasantha Kumari
- OOPS With Java- V1Enviado porhdvsf
- Java AssignmentEnviado poraboubakr3000

- edu555 cni week 7 iEnviado porapi-304225088
- Johari WindowEnviado porCarla Blanca Maiso
- SI UNITSEnviado porCy Consular
- Introduction to StarEnviado porsaikatbesu
- Resistive Circuit PracticeEnviado porBrandon Barndt
- Steel Module11Enviado pordash1991
- Apple Brand ExperienceEnviado porFreon Tapican
- Hexacube @ Changi Singapore Floorplans - Level 1,2,3Enviado porDave Teu
- Dosing Equipments PDF Document Aqua Middle East FZCEnviado porAdolfsmith69
- Unit-19Enviado porRosemary Maisnam
- 1710 Side Mounted Level Switch Cat864Enviado porBasil M. Ikhleif
- market-leader-elementary-scope-and-sequence.pdfEnviado porDavid Robledo
- redox titrationEnviado porapi-249552544
- Construno Brick CatalogEnviado porMeteHan Atlıhan
- SEM-9521E Vibrating ScreenEnviado porRexx Mexx
- SLS GUIDEEnviado porYuvraj Verma
- antennasEnviado porNekr01
- Adsorption CapacityEnviado porSumit Srivastava
- quick calculation coldroomEnviado por15690
- International Journal of Mathematics and Statistics Invention (IJMSI)Enviado porinventionjournals
- Airloads_WkshpFinalEnviado porEmily Barnett
- Mika Rottenberg interviewed by Ross SimoniniEnviado porNefertari J. Aguilar
- PROSODIC FEATURES.docxEnviado porMaryknol Alvarez
- csh33_Talk_090507Enviado porKai Yuan Teo
- Lifting Plan and designEnviado porJurie_sk3608
- Cement Storage TankEnviado porJoel Cristobal
- revtox.23.2-3.2006Enviado porArmando Chiclla Salazar
- Probook 650 G1.pdfEnviado porGabriel-Ştefan Necoară
- 7373v1.0(G52-73731X1)Enviado portatasrba
- Key to Word Quiz for Solution SellingEnviado poraniket