Cs 2208 Data Structures Lab 0 0 3 2 (Repaired)

41
RVS College of Engineering and Technology Data Structures Lab Manual Manual Consists of description of all experiments ,aim and Algorithms . III SEM /II B.E CSE

Transcript of Cs 2208 Data Structures Lab 0 0 3 2 (Repaired)

RVS College of Engineering and Technology

Data Structures Lab Manual

Manual Consists of description of all experiments ,aim and Algorithms . III SEM /II B.E CSE

CS 2208 DATA STRUCTURES LAB

LIST OF PROGRAMS

To develop programming skills in design and implementation of data structures andtheir applications.1. Implement singly and doubly linked lists.2. Represent a polynomial as a linked list and write functions for polynomialaddition.3. Implement stack and use it to convert infix to postfix expression4. Implement a double-ended queue (dequeue) where insertion and deletionoperations are possible at both the ends.5. Implement an expression tree. Produce its pre-order, in-order, and postordertraversals.6. Implement binary search tree.7. Implement insertion in AVL trees.8. Implement priority queue using binary heaps9. Implement hashing with open addressing.10. Implement Prim's algorithm using priority queues to find MST of an Undirected graph.

1DS 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) DisplayThe program should print appropriate messages for stack overflow, stackunderflow, and stack empty.

Description of StackA 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 pushedif top = N - 1 thenWrite "Stack Overflow"elsetop ← top + 1S[top] ←eend 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 elementif top = -1thenreturn -1

2DS LAB MANUAL

elsetemp ←S[top]top ←top - 1return tempend Pop.

Sample Input Stack size N = 6 Menu1.Push2.Pop3.Display4.ExitEnter the choice : 110Enter the choice : 120Enter the choice : 130Enter the choice : 310 20 30Enter the choice : 2Item has been poppedEnter the choice : 310 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 QueueThe 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).

3DS 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}

AlgorithmAlgorithm 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

4DS LAB MANUAL

if r = N - 1then Write "Queue is Full"elser ←r + 1Q[r] ←eend 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 pointersif f >rthenWrite "Queue Underflow"elsetemp ←Q[f]if f = r // only one element in queuef ←r ← 0 // re-initialize queue pointerselsef ←f + 1return tempend enqueue.

Sample Input and OutputQueue Size n =5Menu

1. Enqueue2. Dequeue3. Display4. Exit

Enter the choice : 110Enter the choice : 120Enter the choice : 130Enter the choice : 310 20 30Enter the choice : 2Item has been dequeuedEnter the choice : 320 30

3 A) .Implementation of singly linked list

5DS 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).

Description of Singly linked list

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.

6DS LAB MANUAL

Algorithm Algorithm InsertFirst(p, e)// p - pointer to a linked list// e - element to be added// Getnode() returns a new nodeq ← Getnode()info(q) ←enext(q) ←pp ←qreturn pend 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 addedk ←pwhile k ← NIL and info(k) ←x do // find the key nodek ←next(k)if k = NILthenWrite "Node not found"return pq ← Getnode()info(q) ←enext(q) ←next(k)next(k) ←qreturn pend InsertAfter.

Algorithm InsertLast(p, e)// p - pointer to a linked list// Getnode() returns a new node// e - element to be addedif p = NILthen

7DS LAB MANUAL

return pk ←pwhile next(k) ← NIL do // find the last nodek ←next(k)q ← Getnode()info(q) ←enext(k) ←qnext(q) ← NILreturn pend InsertLast.

Algorithm DeleteNode(p, x)// p - pointer to linked list// x - key node to be deleted// k and pred – temporary variablesk p; pred NILwhile k NIL and info(k) x do // find the key nodepred kk next(k)if k = NILthenWrite "Node not found"elseif pred = NIL // only one node in the listthenp next(p)elsenext(pred) next(k)return pend DeleteNode.

Algorithm SearchNode(p, x)// p - pointer to a linked list// x - key node to be searched// k - temporary variablek pwhile k NIL and info(k) x do // find the key nodek next(k)if k = NILthenreturn false // key not foundelsereturn true // key foundend SearchNode.

8DS LAB MANUAL

Sample Input and OutputMain Menu

1. Creation of linked list.2. Insertion3. Deletion4. Display5. Search6. Exit

Enter the choice: 1Enter the node’s info: Enter stud id : 1 Enter Student name : Alice Enter Semester: 3

“Node has been created “.Enter the choice: 2

Sub Menu1. Insertion at beg2. Insertion at Middle3. Insertion at end4. Display5. Return to Main menuEnter the choice: 1Enter the node’s info: Enter stud id: 2 Enter Student name: ArunEnter Semester: 4Node has been inserted Enter the choice : 41---- Alice—3 - 2---Arun—4 -

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.

9DS 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 pushedq Getnode()info(q) eprev(q) NILnext(q) pif p NIL // not the first nodethenprev(p) qp qreturn pend InsertFront.

Algorithm InsertAfter(p, x, e)// p - pointer to a linked list// x - key node after which e is inserted// e - element to be addedk pwhile k NIL and info(k) x do // find the key nodek next(k)if k = NILthenWrite "Node not found"return pq Getnode()info(q) eif next(k) NILthen

10DS LAB MANUAL

next(q) next(k)prev(q) knext(k) qprev(next(k)) qelse // key node is at the endnext(q) NILnext(k) qprev(q) kend InsertAfter.

Algorithm DeleteNode(p, x)// p - pointer to a linked list// x - key node to be deleted// k – address of key nodek pwhile k NIL and info(k) x do // find the key nodek next(k)if k = NILthenWrite "Node not found"return p// key foundif k = p and next(k) = NIL // only one node in the listthenp NILreturn pif next(k) = NIL // last node is keythennext(prev(k)) next(k)elseif prev(k) = NIL // first node is keythenp next(p)prev(p) NILelsenext(prev(k)) next(k)prev(next(k)) prev(k)return pend DeleteNode.

Sample Input and OutputMain Menu

1 Creation of linked list.2 Insertion3 Deletion

11DS LAB MANUAL

4 Display5 Search6 ExitEnter the choice: 1Enter the element : 10Enter the choice 1Enter the element : 20Enter the choice 2: Enter the element : 30Enter the choice : 410- ---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 listp3 = phead3;/* now traverse the lists till one list gets exhausted */while ((p1 != NULL) || (p2 != NULL))

12DS 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 OutputEnter the first polynomialEnter the Exp,Co-eff and exponential term : 10 2Enter the Exp,Co-eff and exponential term : 15 1Enter the Exp,Co-eff and exponential term : 2 Enter the second polynomialEnter the Exp,Co-eff and exponential term : 10 2Enter the Exp,Co-eff and exponential term : 15 1Enter 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 evaluation2. Backtracking (game playing, finding paths, exhaustive searching)

13DS 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. 

Infix Prefix Postfix

a + b + a b a b +

a + b * c + a * b c a b c * +

(a + b) * (c - d) * + a b - c d a b + c d - *

b * b - 4 * a * c    

40 - 3 * 5 + 1

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/stream2. Scan the infix input string/stream left to right3. 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 stack6. 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.

14DS 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 it’s an operand – append it to the postfix string 2. if it’s a ‘(‘ – push it on the stack.3. if it’s 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 it’s 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 char Stack Postfix String Rule Used

7-(2*3+5)*(8-4/2) empty null

-(2*3+5)*(8-4/2) empty 7 1

(2*3+5)*(8-4/2) - 7 3

2*3+5)*(8-4/2) -( 7 2

*3+5)*(8-4/2) -( 72 1

3+5)*(8-4/2) -(* 72 3

+5)*(8-4/2) -(* 723 3

5)*(8-4/2) -(+ 723* 3

*(8-4/2) - 723*5+ 4

8-4/2) -* 723*5+ 3

8-4/2) -*( 723*5+ 2

15DS LAB MANUAL

-4/2) -*( 723*5+8 1

4/2) -*(- 723*5+8 3

2) -*(-/ 723*5+84 3

) -*(-/ 723*5+842 1

null empty 723*5+842/-*- 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

16DS 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

17DS LAB MANUAL

7. If an item is to be deleted from front increment the front pointer by 1 and remove the item8. If an item is to be deleted from rear remove the item and decrement the pointer by 1.9. Display all items10. End.

Sample Input output

Main Menu

1. Creation of queue2. add at front 3. add at rear 4. Delete from front 5. Delete from rear.6. Display

Enter the choice : 110Enter the choice : 320Enter the choice : 330Enter the choice : 610 20 30Enter the choice : 215Enter the choice : 217Enter the choice : 617 15 10 20 30Enter the choice : 4Enter the choice : 2Enter the choice : 517 15 10 20

18DS LAB MANUAL

7. Implement an expression tree. Produce its pre-order, in-order, and postordertraversals.

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.

In this binary search tree

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)

Algorithm

1. Create a structure for tree Struct node {

19DS LAB MANUAL

int data;node * left;node* right;}

2. Construct a tree as per procedureN 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 inserted5. If less than root node it will be inserted as left node6. 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 thenIf(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 treeint size(p)if (p == null)   return 0else   return (size (p->left) + size(p->right) + 1)end if

20DS LAB MANUAL

Sample Input outputMain menu

1. Creation2. Insertion3. Preorder4. Postorder5. Inorder6. Exit

Enter the choice : 1Enter the data : AEnter the choice : 2Enter the data : BEnter the choice : 2Enter the data : CEnter the choice : 2Enter the data : DEnter the choice : 2Enter the data : EEnter the choice : 2Enter the data : FEnter the choice : 2Enter the data : GEnter the choice : 2Enter the data : HEnter the choice : 2Enter the data : IEnter 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)

21DS LAB MANUAL

8. Implement binary search tree and do the following operationsa. Find the minimum nodeb. 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 v;

else

22DS LAB MANUAL

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 left child of 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 right child of 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

//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)fif(node = NULL)return NULLif(X = node:data)return node

23DS LAB MANUAL

else if(X < node:data)return find(X,node:leftChild)else // X > node:datareturn 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 treeThe 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. returnx8. end

24DS LAB MANUAL

Sample Input and output

Main Menu1. Creattion2. Deletion3. Display4. Minimum Node5. Searching for nodeEnter the choice: 1Do u want to continue (Y/N) : YEnter the element : 8Do u want to continue (Y/N) : YEnter the element : 10Do u want to continue (Y/N) : YEnter the element : 6Do u want to continue (Y/N) : YEnter the element : 13Do u want to continue (Y/N) : YEnter the element : 7Do u want to continue (Y/N) : YEnter the element : 3Do u want to continue (Y/N) : YEnter the element : 1Do u want to continue (Y/N) : YEnter the element : 4Do u want to continue (Y/N) : YEnter the element : 13Do u want to continue (Y/N) : NMain Menu1. Creation2. Deletion3. Display

25DS LAB MANUAL

4. Minimum Node5. Searching for nodeEnter the choice : 2

8. Deleting a node with single child9. Deleting a node with 2 childs.

Enter the choice : 8Enter 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 thealgorithm 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){Perform Right-Left Rotation (RL) rotation

26DS LAB MANUAL

}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 : 3Enter the element : 2Enter the element : 1 3-21Single 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) priority queue: elements are pulled highest-priority-first (e.g. cutting in line, or VIP service).

27DS LAB MANUAL

Priority queueA priority queue is a queue where each element has a priority and the element with thehighest priority is at the front of the queue and will be the first element to be removed. To becontrasted 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 acomplete binary tree which satisfies the heap condition.A heap can be implemented using pointers (each node 3 pointers – parent, left child and rightchild) or much more simply using a partially ordered array. In the array implementationwhere the highest priority key is in array position 1 we have:parent(i) = i/2lchild(i) = 2irchild(i) = 2i+1Here parent(i) is the array index of the parent of node i.A heap is partially ordered by satisfying the heap condition.Heap array

28DS LAB MANUAL

Mary

Mike SamAnn

Tom

Pam Sue

Joe Bob Jane2

15

4

7

6

9

8

10

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 PseudocodeKey // a type, usually int, describes type of values in heapint N // number of elements in array or heapKey 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] = xsiftUp( 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 hsiftUp( int k)v = h[k]h[0] = ∞while( v > h[k/2] )h[k] = h[k/2]k = k/2h[k] = v

29DS LAB MANUAL

// 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 hsiftDown(int k)v = h[k]while( k ≤ N/2 ) // while node at pos k has a left child nodej = 2kif( j < N ∧ h[j] < h[j+1]) ++jif( v ≥ h[j] ) breakh[k] = h[j]; k = jh[k] = vKey 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 jelse

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 = 02. repeat

j = h(k,i) if (T[j] = k) return j // Successful search. else i = i + 1until ( (T[j] = NULL) or (i = m) ).

30DS LAB MANUAL

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 connected weighted undirected 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 ÎV2. doD [u ] ¬ ¥3. D[ r ]¬ 0

4. PQ ¬make-heap(D,V, {})//No edges 5. T ¬ Æ6.7. whilePQ ¹Æ do8. (u,e ) ¬ PQ.extractMin() 9. add (u,e) to T10. for each v Î Adjacent (u )11. do if v ÎPQ&&w( u, v ) <D [ v ]12. then D [ v ] ¬ w (u, v)

31DS LAB MANUAL

13. 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 TThe 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

32DS LAB MANUAL