Вы находитесь на странице: 1из 38

EEC-II YR-III SEM-IT2205-DS LAB

UNIVERSITY SYLLABUS
IT2205 DATA STRUCTURES AND ALGORITHMS LAB 0 0 3 2

AIM:
To develop programming skills in design and implementation of data structures and their applications. 1. 2. Implement singly and doubly linked lists. 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 array-based circular queue and use it to simulate a producerconsumer problem. 5. Implement an expression tree. Produce its pre-order, in-order, and postorder traversals. 6. Implement binary search tree. 7. Implement priority queue using heaps 8. Implement hashing techniques. 9. Implement Dijkstra's algorithm using priority queues 10. Implement a backtracking algorithm for Knapsack problem

Total: 45

Page 1 of 38

EEC-II YR-III SEM-IT2205-DS LAB

LIST OF PROGRAMS
1. EMPLOYEE DATABASE SYSTEM USING ARRAYS 2. IMPLEMENTATION OF LIST ADT USING LINKED LIST 3. APPLYING LIST ADT FOR POLYNOMIAL ADDITION USING LINKED LIST. 4. IMPLEMENTATION OF DOUBLY LINKED LIST 5. CONVERSION FROM INFIX EXPRESSION TO POSTFIX EXPRESSION USING STACK ADT 6. SIMULATION OF PRODUCER-CONSUMER PROBLEM USING ARRAY IMPLEMENTAION OF CIRCULAR QUEUE. 7. IMPLEMENTATION OF EXPRESSION TREE ADT AND TREE TRAVERSALS 8. IMPLEMENTATION OF BINARY SEARCH TREE ADT 9. IMPLEMENTATION PRIORITY QUEUE USING HEAPS 10. IMPLEMENTATION OF HASHING TECHNIQUES. 11. IMPLEMENTATION OF DIJKSTRA'S ALGORITHM USING PRIORITY QUEUES 12. IMPLEMENTATION OF A BACKTRACKING ALGORITHM FOR KNAPSACK PROBLEM 13.BEYOND THE SYLLABI i. IMPLEMETATION OF PRIMS AND KRUSKALS ALGORITHM

14.VIVA QUESTIONS

Software Requirements Operating System - Windows XP/Vista/7/8 Software - Turbo C/ C++

Page 2 of 38

EEC-II YR-III SEM-IT2205-DS LAB

INTRODUCTION
This manual is organized in such a way that the students can directly use it in the laboratory. Each laboratory exercise comprises of 1. Statement of the problem 2. Description 3. Inference 4. Algorithm 5. Sample Input Output 6. Conclusion Students must follow this sequence to do any data structures experiment in the laboratory and write the coding accordingly. Using the algorithms given in this section one can implement in any language at a later time.

INTRODUCTION TO C
C was brought to us by Dennis Ritchie and Brian at Bell Labs. AT&T people had themselves this Operating System called UNIX that needed a programming language. They made it, and since the previous version was called B, they decided to call it C for obvious reasons. There was never an A programming language. The B in B stood for Bell. C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use. C has been around for several decades and has won widespread acceptance because it gives programmers maximum control and efficiency. C is called a compiled language. This means that once you write your C program, you must run it through a C compiler to turn your program into an executable that the computer can run (execute). The C program is the human-readable form, while the executable that comes out of the compiler is the machine-readable and executable form. This means that to write and run a C program, you must have access to a C compiler. If you are using a UNIX machine (for example, if you are writing CGI scripts in C on your host's UNIX computer, or if you are a student working on a lab's UNIX machine), the C compiler is available for free. It is called either "cc" or "gcc" and is available on the command line.

Page 3 of 38

EEC-II YR-III SEM-IT2205-DS LAB

CHARACTERISTICS OF C LANGUAGE
Modularity: Ability to breakdown a large module into manageable sub modules called as modularitythat is an important feature of structured programming languages. Advantages: 1. Projects can be completed in time. 2. Debugging will be easier and faster. Portability: The ability to port i.e. to install the software in different platform is called portability. Highest degree of portability: C language offers highest degree of portability i.e., percentage of changes to be made to the sources code is at minimum when the software is to be loaded in another platform. Percentage of changes to the source code is minimum. Extendibility: Ability to extend the existing software by adding new features is called as extendibility. Speed: C is also called as middle level language because programs written in C language run at the speeds matching to that of the same programs written in assembly language so C language has both the merits of high level and middle level language and because if this feature it is mainly used in developing system software. Areas of Application The C programming language is used in many different areas of application, but the most prolific area is UNIX operating system applications. The C language is also used in computer games: UNIX operating system computer games

DATA STRUCTURES
A data structure is an arrangement of data in a computer's memory or even disk storage. An example of several common data structures are arrays, linked lists, queues, stacks, binary trees, and hash tables. Algorithms, on the other hand, are used to manipulate the data contained in these data structures as in searching and sorting. C provides us with just one built in data structure, the array. Although efficient and easily used and understood, arrays often don't provide us with the level of functionality we need from a data structure. If the quantity of data we need to store is not well known at

Page 4 of 38

EEC-II YR-III SEM-IT2205-DS LAB compile time, then using arrays could waste memory if too large, or waste time in resizing at runtime if too small. Several, more abstract, data structures can be constructed to better serve our needs. Many algorithms apply directly to a specific data structures. When working with certain data structures you need to know how to insert new data, search for a specified item, and deleting a specific item. Commonly used algorithms include are useful for: Searching for a particular data item (or record). Sorting the data. There are many ways to sort data. Simple sorting, Advanced sorting Iterating through all the items in a data structure. (Visiting each item in turn so as to display it or perform some other action on these items). Some data structures with the comparisons made on them are shown below.

Page 5 of 38

EEC-II YR-III SEM-IT2205-DS LAB

Page 6 of 38

EEC-II YR-III SEM-IT2205-DS LAB

1. EMPLOYEE DATABASE SYSTEM USING ARRAYS


PROBLEM STATEMENT To implement employee data base system using arrays and structures DESCRIPTION

A structure provides a means of grouping variables under a single name for easier handling and identification. A structure is declared by using the keyword struct followed by an optional structure tag followed by the body of the structure. The variables or members of the structure are declared within the body.

INFERENCE The disadvantage of using arrays is studied from this program.

ALGORITHM i. Create a structure using the struct variable for each employee containing the necessary attributes of that employee. ii. Create an array of such structures for n number of employees. iii. Get the input of each attribute for each employee from the user. iv. Calculate the gross salary by the following formulas. hra (10 %), da(50%), ta(5%), pf(11%), tax(6%) from basic. Gross = basic + hra + da + ta Deduction = pf + tax Netsalary = gross deduction v. Display the results.

Page 7 of 38

EEC-II YR-III SEM-IT2205-DS LAB

CONCLUSION The employee data base system is implemented using structures and arrays. The need for Linked list is also understood from this program.

2. IMPLEMENTATION OF LIST ADT USING LINKED LIST


PROBLEM STATEMENT Write a C Program to implement List ADT operations such as insert, delete, deletelist, find, and isempty using linked list. DESCRIPTION A list is a set of elements (A1, A2,.An). The position of an element Ai in the list is i. List can be implemented using an Array, Linked list or Cursor implementation. The operations that can be performed on the List ADT are Insert, Delete, Find, and Print. A linked list is data structure that consists of a sequence of data records such

field that contains a reference (i.e., a link) to the next record in the sequence. Each record of a linked list is often called an element or node.
that in each record there is a The head of a list is its first node, and the tail is the list minus that node (or a pointer thereto). Advantages 1. Length of the list need not be known in advance 2. Optimum use of memory 3. Dynamic data structure. 4. We can perform deletion and insertion anywhere in the list. 5. We can merge two list easily. 6. Memory is not wasted if you remove an element from the list as it is freed Disadvantages 1. Backward traversing is not possible in singly linked list. 2. Insertion is easy but deletion take some additional time, because disadvantage of backward traversing INFERENCE How to implement List ADT using linked list is inferred by this exercise. The students will be able to use linked list to implement other data structures like Stack, Queue, Trees etc. ALGORITHM 1. Create a structure NODE with a data element and a pointer of type NODE 2. Create a header node 3. Accept the user choice Insert, Delete, DeleteList Find, and Display 4. If the Choice is Insert i. Accept the data ii.Find the position in the list for the new data iii. Allocate space for new node and store new data in it. iv. Insert the new node in the correct position by updating pointers (assume the list is sorted) 5. If the Choice is Delete a. Get the data to be deleted from the list. b. Remove the node containing data by updating the pointers 6. If the Choice is DeleteList Delete all the data nodes in the list. 7. If the choice is Find

Page 8 of 38

EEC-II YR-III SEM-IT2205-DS LAB a. Accept the data x b. Traverse the list till the data x is found or end of list c. If found display Element found If the choice is Display then display all the elements by traversing the list Stop

8. 9.

SAMPLE INPUT AND OUTPUT Program - Implementation of List ADT using Linked list 1. Insert operation 2. Delete an element 3. Delete the list 4. Find operation 5. Display List elements 6. Quit Enter your choice 1 Enter the element 11 1. Insert operation 2. Delete an element 3. Delete the list 4. Find operation 5. Display List elements 6. Quit Enter your choice 1 Enter the element 5 1. Insert operation 2. Delete an element 3. Delete the list 5. Display List elements 6. Quit Enter your choice 4 Enter the element to be searched 55 Element not found 1. Insert operation 2. Delete an element 3. Delete the list 4. Find operation 5. Display List elements 6. Quit Enter your choice4 Enter the element to be searched5 Element found 1. Insert operation 2. Delete an element 3. Delete the list 4. Find operation 5. Display List elements 6. Quit Enter your choice5 5 11

Page 9 of 38

EEC-II YR-III SEM-IT2205-DS LAB

CONCLUSION The list ADT is implemented using Linked list. The operations insert, delete, find, findprevious, deletelist and isempty of the list ADT are implemented. The program is executed and verified for sample input and output.

3. APPLYING LIST ADT FOR POLYNOMIAL ADDITION USING LINKED LIST.


PROBLEM STATEMENT List data structure can be used to represent polynomial . Write a C Program to implement polynomial ADTs addition operation using linked list implementation of list. DESCRIPTION List can be used to represent a polynomial. When there are less number of nonzero terms the array implementation of a polynomial can be used. There large number of non-zero terms are available linked list implementation of polynomial can be used. INFERENCE How a polynomial can be represented using the linked list and also how to perform operation like addition is inferred by this exercise. The students will be able to perform others operations of Polynomial ADT after completion of this exercise. ALGORITHM 1. Define the node structure 2. Create a header node for the first polynomial. 3. Get first polynomial terms coefficients and powers from the user (assume terms/nodes are sorted by exponent) . 4. For each term of the polynomial, create a node and store the coefficient and power. 5. Link the above nodes to the linked list, for first polynomial. 6. Repeat the steps 2 to 5 for the second polynomial. 7. Make pointers, to point to first term of the polynomial. 8. If the exponents of both the terms are equal then add the coefficients. a. Create a node of resultant polynomial b. Store the added coefficient and exponent in the node and link it to the resultant linked list. c. Update the pointers to point to next node in each polynomial. 9. If the exponent of first polynomial is greater than the second a. Then copy the node to the resultant polynomial b. Update the pointer of the first polynomial 10. If the exponent of second polynomial is greater than the first a. Then copy the node to the resultant polynomial b. Update the pointer of the second polynomial 11. Repeat the steps 8-10 until end of first polynomial or second polynomial is reached. 12. If end of first polynomial is not reached then copy the remaining terms to the resultant polynomial. 13. If end of second polynomial is not reached then copy the remaining terms to the resultant polynomial. 14. Print the resultant polynomial.

SAMPLE INPUT AND OUTPUT

Page 10 of 38

EEC-II YR-III SEM-IT2205-DS LAB Polynomial Addition Create the First polynomial Enter no. of elements in the polynomial3 Note: Enter nodes sorted by exponent Enter the exponent4 Enter the coefficient11 Enter the exponent2 Enter the coefficient10 Enter the exponent0 Enter the coefficient7 Create the Second polynomial Enter no. of elements in the polynomial2 Note: Enter nodes sorted by exponent Enter the exponent4 Enter the coefficient3 Enter the exponent1 Enter the coefficient66 11x^4 + 10x^2 + 7x^0 + 3x^4 + 66x^1 + 14x^4 + 10x^2 + 66x^1 + 7x^0 +

Page 11 of 38

EEC-II YR-III SEM-IT2205-DS LAB

CONCLUSION The application of list data structure is Polynomial ADT. Polynomial ADT is implemented using Linked list. The addition operation of polynomial ADT is implemented by writing a C program. The program is executed and verified for sample input and output.

4. IMPLEMENTATION OF DOUBLY LINKED LIST


PROBLEM STATEMENT Write a C Program to implement List ADT operations such as insert, delete, deletelist, find, and isempty using Doubly linked list. DESCRIPTION A variant of a linked list in which each item has a link to the previous item as well as the next. This allows easily accessing list items backward as well as forward and deleting any item in constant time. Also known as two-way linked list, symmetrically linked list.

A doubly linked list is a linked list in which each node has three fields namely data field, forward link (Flink) and backward link (Blink). Flink points to the successor node in the list whereas Blink points to the predecessor node How to implement List ADT using linked list is inferred by this exercise. The students will be able to use linked list to implement other data structures like Stack, Queue, Trees etc.

Advantages: 1. Deletion process is easier. 2. Additional pointer for previous node is not necessary. 3. Back warding and forwarding traverse are possible. Disadvantages: More Memory space is required since it has two pointers
INFERENCE How to implement List ADT using Doubly linked list is inferred by this exercise. The students will be able to use linked list to implement other data structures like Stack, Queue, Trees etc. ALGORITHM 1. Create a structure NODE with a data element ,flink, blink 2. Create a header node 3. Accept the user choice Insert, Delete, DeleteList Find, and Display 4. If the Choice is Insert a. Accept the data b. Find the position in the list for the new data c. Allocate space for new node and store new data in it. d. Insert the new node in the correct position by updating pointers (assume the list is sorted) 5. If the Choice is Delete a. Get the data to be deleted from the list. b. Remove the node containing data by updating the pointers 6. If the Choice is DeleteList i. Delete all the data nodes in the list. 7. If the choice is Find a. Accept the data x

Page 12 of 38

EEC-II YR-III SEM-IT2205-DS LAB b. Traverse the list till the data x is found or end of list c. If found display Element found 8. If the choice is Display then display all the elements by traversing the list 9. Stop

SAMPLE INPUT AND OUTPUT


Program-Implementation of Doubly Linked List 1.Insert operation 2.Delete an element 3.Delete the list 4.Find operation 5.Display List elements 6.Quit Enter your choice 5 10 20 30 40 50 1.Insert operation 2.Delete an element 3.Delete the list 4.Find operation 5.Display List elements 6.Quit Enter your choice 2 Enter the element to be deleted 30 1.Insert operation 2.Delete an element 3.Delete the list 4.Find operation 5.Display List elements 6.Quit Enter your choice 5 10 20 40 50

Page 13 of 38

EEC-II YR-III SEM-IT2205-DS LAB

CONCLUSION The list ADT is implemented using Doubly Linked list. The operations insert, delete, find, deletelist and isempty of the list ADT are implemented. The program is executed and verified for sample input and output.

Page 14 of 38

EEC-II YR-III SEM-IT2205-DS LAB

5. CONVERSION OF INFIX EXPRESSION TO POSTFIX EXPRESSION USING STACK ADT


PROBLEM STATEMENT Write a C program to convert an infix expression to postfix expression using Stack ADT. DESCRIPTION Infix Expression and Postfix Expression Expression can be expressed as Infix expression : Notation in which the operator separates its operands. Eg (a + b) * c. Infix notation requires the use of brackets to specify the order of evaluation. Prefix expression : Operators are written before their operands. Postfix expression : Reverse Polish Notation or Suffix Notation in which the operator follows its operands. Eg a + b * c represented as abc*+. INFERENCE How to convert and given infix expression to postfix expression is learned by the learners. Evaluation of postfix expression needs only a scan through the expression unlike infix expression which may needs more than one forward scan depending upon the priority of the operators in the expression. ALGORITHM Scan the Infix string from left to right. Initialise an empty stack. If the scannned character is an operand, add it to the Postfix string. If the scanned character is an operator and if the stack is empty Push the character to stack. If the scanned character is an Operand and the stack is not empty, compare the precedence of the character with the element on top of the stack (topStack). If topStack has higher precedence over the scanned character Pop the stack else Push the scanned character to stack. Repeat this step as long as stack is not empty and topStack has precedence over the character. Repeat this step till all the characters are scanned. (After all characters are scanned, we have to add any character that the stack may have to the Postfix string.) If stack is not empty add topStack to Postfix string and Pop the stack. Repeat this step as long as stack is not empty. Return the Postfix string.

SAMPLE INPUT AND OUTPUT Enter Infix Expression : A + B + C / (E - F) Postfix Expression is : A B + C E F - / +

Page 15 of 38

EEC-II YR-III SEM-IT2205-DS LAB CONCLUSION Conversion of Infix expression to Postfix expression is implemented by writing a C program. The program is executed and verified for sample input and output.

6. ARRAY IMPLEMENTATION OF CIRCULAR QUEUE & SIMULATE PRODUCER-CONSUMER PROBLEM USING CIRCULAR QUEUE
PROBLEM STATEMENT Write a C program to implement circular queue using array and simulate producer consumer problem. DESCRIPTION A queue is a "first-in, first-out" temporary storage structure. Circular queue have less memory consuption as comared to linear queue because while doing insertion after deletion operation it allocate an extra space the first remaining vacant but in circular queue the first is used as it comes immediate after the last. A circular queue recycles the available storage space using two pointers - one for the input position and one for the output position. The input pointer advances as new data comes into the queue, and the output pointer advances as data is removed. The queue is "caught up" when the two pointers are equal. An application of this is the print spooler built into Windows and other operating systems. INFERENCE How to simulate Producer-Consumer problem using circular queue is inferred by the learners. Producer is the one who produces the item and consumer is the one who consumes the item. If there is no item to consume, the consumer cannot consume. If there is no enough space, to store the item, the producer should not produce until there is space to store the item. ALGORITHM 1. Initialize an array of size N 2. Accept the user choice Insert, Delete & Display 3. If the choice is insert, accept the value only if queue is not full 4. Store the value entered in the next location and increment the pointer REAR by one. 5. If the choice is Delete ,accept the value only if queue is not empty 6. Delete the last element and increment the pointer FRONT by one 7. If the choice is display, then display the elements of the queue. 8. Stop. SAMPLE INPUT AND OUTPUT Program - Implementation of Circular queue using Array 1. Enqueue 2. Dequeue 3. Display Queue elements 4. Quit Enter your choice1 Enter the element11 Enqueue operation front 1 rear 1 1. Enqueue 2. Dequeue 3. Display Queue elements 4. Quit Enter your choice1 Enter the element22 Enqueue operation front 1 rear 2 1. Enqueue

Page 16 of 38

EEC-II YR-III SEM-IT2205-DS LAB 2. Dequeue 3. Display Queue elements 4. Quit Enter your choice2 Deleted element 11 1. Enqueue 2. Dequeue 3. Display Queue elements 4. Quit Enter your choice2 Deleted element 22 1. Enqueue 2. Dequeue 3. Display Queue elements 4. Quit Enter your choice2 Empty queue 1. Enqueue 2. Dequeue 3. Display Queue elements 4. Quit Enter your choice4

CONCLUSION

Page 17 of 38

EEC-II YR-III SEM-IT2205-DS LAB Implementation of circular queue using array and simulation of producer consumer problem is done using C program. . The program is executed and verified for sample input and output.

Page 18 of 38

EEC-II YR-III SEM-IT2205-DS LAB

7. IMPLEMENTATION OF EXPRESSION TREE AND TREE TRAVERSALS


PROBLEM STATEMENT Write a program to construct an expression tree using a postfix expression and perform in-order traversal in the expression tree to get infix expression. DESCRIPTION Expression Trees Expression trees are useful as a vehicle for discussing the traversal of a tree. An expression tree is a binary tree which is used to represent a mathematical expression. For example, if we have the expression (2 * (4 + (5 + 3))), we could construct a tree to represent it. In an expression tree, the parent nodes are the operators, and the children are the operands. To find the result of this expression, we need to first solve (5 + 3), which is 8, then solve (4 + 8), which is 12, and then finally solve 2 * 12, which is 24. So our root node will contain the operator within the outermost set of parentheses, its left child will be the value "2", and the right child will be the remaining expression that needs to be solved, which would be (4 + (5 + 3)).

There

are three different ways we could represent an expression: Infix, where the operator comes between its two operands Prefix, where the operator comes before its two operands Postfix, where the operator comes after its two operands

Given an expression tree, we can generate any of the three representations using one of the three traversals of a binary tree: in-order, pre-order, and post-order. In-Order Traversal In an infix expression, the operator comes between its operands, so if we want to generate the infix expression from an expression tree, we will need to print the operand on the left before we print out the operator. But what if the left operand is another expression to evaluate? We use recursion. We print out the entire left subtree, then print the current node, then print out the entire right subtree. Pre-Order Traversal We can generate a prefix expression using a pre-order traversal. Much like for the in-order traversal, we will use recursion to print the entire left subtree and the entire right subtree. In a prefix expression, the operator comes before its two operands, so we will have to print out the parent node's data before recursively printing its left and right children. Post-Order Traversal In postfix the operator comes after its two operands, will recursively print the left and right subtrees before we print out the data at the current node.

Page 19 of 38

EEC-II YR-III SEM-IT2205-DS LAB INFERENCE How to construct an expression tree using a postfix expression and perform inorder traversal in the expression tree to get infix expression is learned by the learners in this exercise. ALGORITHM CONSTRUCTON OF EXPRESSION TREE Given a postfix expression to construct an expression tree, steps are 1. Scan the postfix expression character by character till the end of expression 1.a)When operand is encountered , Create a node, store the operand in the node and push the pointer of the node to stack 1.b)When operator is encountered, create a node, store the operator in the node, pop two pointers from the stack and make the node pointers as right and left child of the operator node. 2. The stack will have only one entry, which is the pointer of the root, of the required expression tree. TREE TRAVERSAL To traverse a non-empty binary tree in preorder, perform the following operations recursively at each node, starting with the root node: 1. Visit the node. 2. Traverse the left subtree. 3. Traverse the right subtree. (This is also called Depth-first traversal.) To traverse a non-empty binary tree in inorder, perform the following operations recursively at each node: 1. Traverse the left subtree. 2. Visit the node. 3. Traverse the right subtree. (This is also called Symmetric traversal.) To traverse a non-empty binary tree in postorder, perform the following operations recursively at each node: 1. Traverse the left subtree. 2. Traverse the right subtree. 3. Visit the node. SAMPLE INPUT AND OUTPUT Enter the postfix expression for expression tree construction abc*+ inorder traversal of the expression tree infix expression a+b*c

CONCLUSION

Page 20 of 38

EEC-II YR-III SEM-IT2205-DS LAB An expression tree is constructed using a postfix expression and in-order traversal is performed in the expression tree to get infix expression. . The program is executed and verified for sample input and output

Page 21 of 38

EEC-II YR-III SEM-IT2205-DS LAB

8. SEARCH TREE ADT - BINARY SEARCH TREE


PROBLEM STATEMENT Implement search Tree ADT and perform operations such as find, findmin, findmax, insert and delete operation on the Binary search tree. DESCRIPTION An important application of binary trees is, their use in searching. The property that makes a binary tree into a binary search tree is that for every node, X in the tree, the values of all the keys in its left subtree are smaller than the key value in X, and the values of all the keys in its right subtree are larger than the key value in X. Routines for operation of search tree are written recursively. Binary search tree (BST) is a binary tree data structure which has the following properties: Each node (item in the tree) has a distinct value. Both the left and right subtrees must also be binary search trees. The left subtree of a node contains only values lesser than the node's value. The right subtree of a node contains only values greater than the node's value. The major advantage of binary search trees over other data structures is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient. Binary search trees can choose to allow or disallow duplicate values, depending on the implementation. Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets, multisets, and associative arrays. Operations Operations on a binary tree require comparisons between nodes. These comparisons are made with calls to a comparator, which is a subroutine that computes the total order (linear order) on any two values. This comparator can be explicitly or implicitly defined, depending on the language in which the BST is implemented. Searching Searching a binary tree for a specific value can be a recursive or iterative process. Explanation : We begin by examining the root node. If the tree is null, the value we are searching for does not exist in the tree. Otherwise, if the value equals the root, the search is successful. If the value is less than the root, search the left subtree. Similarly, if it is greater than the root, search the right subtree. This process is repeated until the value is found or the indicated subtree is null. If the searched value is not found before a null subtree is reached, then the item must not be present in the tree. Insertion Insertion begins as a search would begin; if the root is not equal to the value, we search the left or right subtrees as before. Eventually, we will reach an external node and add the value as its right or left child, depending on the node's value. In other words, we examine the root and recursively insert the new node to the left subtree if the new value is less than the root, or the right subtree if the new value is greater than or equal to the root. Another way to explain insertion is that in order to insert a new node in the tree, its value is first compared with the value of the root. If its value is less than the root's, it is then compared with the value of the root's left child. If its value is greater, it is compared with the root's right child. This process continues, until the new node is compared with a leaf node, and then it is added as this node's right or left child, depending on its value.

Page 22 of 38

EEC-II YR-III SEM-IT2205-DS LAB Deletion There are several cases to be considered: Deleting a leaf: Deleting a node with no children is easy, as we can simply remove it from the tree. Deleting a node with one child: Delete it and replace it with its child. Deleting a node with two children: Suppose the node to be deleted is called N. We replace the value of N with either its in-order successor (the left-most child of the right subtree) or the in-order predecessor (the right-most child of the left subtree).

Once we find either the in-order successor or predecessor, swap it with N, and then delete it. Since both the successor and the predecessor must have fewer than two children, either one can be deleted using the previous two cases. A good implementation avoids consistently using one of these nodes, however, because this can unbalance the tree. Once the binary search tree has been created, its elements can be retrieved inorder by recursively traversing the left subtree of the root node, accessing the node itself, then recursively traversing the right subtree of the node, continuing this pattern with each node in the tree as it's recursively accessed. The tree may also be traversed in pre-order or post-order traversals. INFERENCE How to implement Binary search tree ADT and perform operations such as find, findmin, findmax, delete and insert operations of the BST ADT is learned by the learners. ALGORITHM 1. Initialize node structure containing a data element X and two pointers for left subtree and right subtree. 2. Accept the user choice Insert, Delete and Find 3. If the choice is Insert, a. Accept the data element X and subtree T b. If the subtree T is null, then create a new treenode T and set X= T-->element and T-->left=null & T-->right=null c. Other wise check if X is less than the data element of treenode T, If so, set T-->left=call insert(X, T-->left) d. Otherwise check if X is greater than the data element of treenode T, If so , set T -->right=call insert(X, T -->right) 4. If the choice is delete, a. Accept the data element X and subtree T b. If the X is less than T--> element then set T-->left= call delete( X, T-->left) c. Otherwise, check if X is greater than T-->element then T-->right=call delete(X,T-->right) d. Otherwise, Check if the treenode which is to be deleted is having two children, then Replace the element of treenode T with the smallest data in its right subtree and set

Page 23 of 38

EEC-II YR-III SEM-IT2205-DS LAB T-->right= call delete(T-->element, T-->right) e. Otherwise, check if the treenode which is to be deleted is having one or zero children, then Return left subtree if the right subtree is null or Return right subtree if the left subtree is null and Finally remove the treenode T from the tree If the user choice is find, a. Accept the Data element X and subtree T b. If the X is less than T-element then Continue the search in the left subtree recursively. c. Otherwise check If the X is greater than T-->element then Continue the search in the right subtree recursively. d. Otherwise return the treenode T Stop

5.

6.

SAMPLE INPUT AND OUTPUT 1.insert 2.delete 3.findmin 4.findmax 5.display 6.exit Enter your choice 1 Enter the element11 1.insert 2.delete 3.findmin 4.findmax 5.display 6.exit Enter your choice1 Enter the element5 1.insert 2.delete 3.findmin 4.findmax 5.display 6.exit Enter your choice1 Enter the element44 1.insert 2.delete 3.findmin 4.findmax 5.display 6.exit Enter your choice 5 5 11 44 1.insert 2.delete 3.findmin 4.findmax 5.display 6.exit Enter your choice6

Page 24 of 38

EEC-II YR-III SEM-IT2205-DS LAB CONCLUSION Binary search Tree ADT is implemented and BST operations such as find, findmin, findmax, insert and delete operation is coded by writing a C program. The program is executed and verified for sample input and output

Page 25 of 38

EEC-II YR-III SEM-IT2205-DS LAB

9. IMPLEMENT PRIORITY QUEUE USING HEAPS


PROBLEM STATEMENT Write a program to implement Priority queue using heaps DESCRIPTION A heap is a partially sorted binary tree. Although a heap is not completely in order, it conforms to a sorting principle: every node has a value less (for the sake of simplicity, we will assume that all orderings are from least to greatest) than either of its children. Additionally, a heap is a "complete tree" -- a complete tree is one in which there are no gaps between leaves. For instance, a tree with a root node that has only one child must have its child as the left node. More precisely, a complete tree is one that has every level filled in before adding a node to the next level, and one that has the nodes in a given level filled in from left to right, with no breaks.

Why use a heap? A heap can be thought of as a priority queue; the most important node will always be at the top, and when removed, its replacement will be the most important. This can be useful when coding algorithms that require certain things to processed in a complete order, but when you don't want to perform a full sort or need to know anything about the rest of the nodes. For instance, a well-known algorithm for finding the shortest distance between nodes in a graph, Dijkstra's Algorithm, can be optimized by using a priority queue. Heaps can also be used to sort data. A heap sort is O(nlogn) efficiency, though it is not the fastest possible sorting algorithm. Check out a tutorial on heap sort for more information related to heap sort. How do you implement a heap? Although the concept of a heap is simple, the actual implementation can appear tricky. How do you remove the root node and still ensure that it is eventually replaced by the correct node? How do you add a new node to a heap and ensure that it is moved into the proper spot? The answers to these questions are more straight forward than meets the eye, but to understand the process, let's first take a look at two operations that are used for adding and removing nodes from a heap: upheaping and downheaping. Upheap: The upheap process is used to add a node to a heap. When you upheap a node, you compare its value to its parent node; if its value is less than its parent node, then you switch the two nodes and continue the process. Otherwise the condition is met that the node is less than its parent node, and so you can stop the process. As you know that in a heap, a node is always less than its parent node, you are assured that if the node you are upheaping is less than its parent node, that that node is also less than the parents of the parent node. Downheap: The downheap process is similar to the upheaping process. When you downheap a node, you compare its value with its two children. If the node is less than both of its children, it remains in place; otherwise, if it is greater than one or both of its children, then you switch it with the child of lowest value, thereby ensuring that of the three nodes being compared, the new parent node is lowest. Of course, you cannot be assured that the node being downheaped is in its proper position -- it may be greater

Page 26 of 38

EEC-II YR-III SEM-IT2205-DS LAB than one or both of its children; the downheap process must be repeated until the node is less than both of its children. When you add a new node to a heap, you add it to the rightmost unoccupied leaf on the lowest level. Then you upheap that node until it has reached its proper position. In this way, the heap's order is maintained and the heap remains a complete tree. Removing the root node from a heap is almost as simple: when you take the node out of the tree, you replace it with "last" node in the tree: the node on the last level and rightmost on that level. Once the top node has been replaced, you downhead the node that was moved until it reaches its proper position. As usual, the result will be a proper heap, as it will be complete, and even if the node in the last position happens to be the greatest node in the entire heap, it will do no worse than end up back where it started.

ALGORITHM 1. Define the capacity, size and array of store the elements of the heap. 2. Build the heap using the initial elements of the heap. Insertion 3. Get the new element to be inserted in the heap. Percolate up 4. Insert a empty node(hole) in the next available location. Size of heap increases by 1 5. Check X can be placed in the hole without violating heap order property. If NO, slide the holes parent node into the hole. 6. Repeat step 5 until X can be placed in the hole. DeleteMin 7. The minimum element in the root is removed. By that a hole is created at the root. Size of the heap reduces by 1. Percolate Down-Finding right place for the last element X in the heap. 8. Check X can be placed in the hole, without violating heap order property. If NO, slide the smaller of the holes children into the hole. 9. Repeat step 8 until X can be place in the hole.

CONCLUSION Priority Queue using heap is implemented and the operations insert and delete operation is coded by writing a C program. The program is executed and verified for sample input and output

Page 27 of 38

EEC-II YR-III SEM-IT2205-DS LAB

10. IMPLEMENT HASHING TECHNIQUE SEPARATE CHAINING


PROBLEM STATEMENT Write a C Program to implement hashing techniques using separate chaining technique DESCRIPTION HASH FUNCTION A hash function is any well-defined procedure or mathematical function which converts a large, possibly variable-sized amount of data into a small datum, usually a single integer that may serve as an index into an array. The values returned by a hash function are called hash values, hash codes, hash sums, or simply hashes. Hash functions are mostly used to speed up table lookup or data comparison tasks such as finding items in a database, detecting duplicated or similar records in a large file, finding similar stretches in DNA sequences, and so on. A hash function may map two or more keys to the same hash value. In many applications, it is desirable to minimize the occurrence of such collisions; which means that the hash function must map the keys to the hash values as evenly as possible HASH TABLES Hash functions are primarily used in hash tables, to quickly locate a data record (for example, a dictionary definition) given its search key (the headword). Specifically, the hash function is used to map the search key to the hash. The index gives the place where the corresponding record should be stored. Hash tables, in turn, are used to implement associative arrays and dynamic sets. Hashing with Separate Chaining Hash table is a popular and a very efficient way to implement dictionaries for keys with an available hash function. Hash Functions: We use the hash function to insert elements in an array (we insert element with key x into position h(x). When to elements hash into the same position we face a collision. Hashing with seperate chaining overcomes the collision problem by using buckets in each cell (lists of possible contents). Example: x: A S E R C H I N G X M P L h(x): 0 2 0 4 4 4 2 2 1 2 4 3 3

Page 28 of 38

EEC-II YR-III SEM-IT2205-DS LAB

INFERENCE: How to perform hashing using separate chaining is learned by the learners by this exercise. ALGORITHM 1. Define the node (listnode)with a data element and pointer to the node 2. Define a structure (hash table) with tablesize and pointer to the pointer of the listnode 3. Allocate space for the hash table 4. Create a header node for the lists in the hash table 5. Insert new element into the hash table by applying hash function to the data and locate the corresponding list. a. If collision occurs the data goes to the same list at the end 6. To find an data apply the hash function and locate the list in the hash table a. Locate the element in the identified list

CONCLUSION

Page 29 of 38

EEC-II YR-III SEM-IT2205-DS LAB The hash table is constructed using separate chaining technique and the operations such as inserting the new element into the table and locating an element are performed using C coding

11.IMPLEMENT DIJKSTRA'S ALGORITHM USING PRIORITY QUEUES


AIM Write a program to implement Dijkstras algorithm using priority queues DESCRIPTION Take the origin vertex, set the weight of the shortest path to 0 and push it onto the priority queue. while the priority queue is not empty, pop an entry <v,w_v,p_v>where v is the vertex, w_v and p_v are the augmented labels of v. for each edge e=(v,u) in G, where u has augmented labels w_u, p_u. if wt(e) + w_v < w_u then set p_u to v set w_u to wt(e) + w_v add <u,>to the priority queue. ALGORITHM 1 2 3 4 5 6 7 8 function Dijkstra(Graph, source): for each vertex v in Graph: dist[v] := infinity previous[v] := undefined dist[source] := 0 Q := copy(Graph) while Q is not empty: u := extract_min(Q) // Initializations

// Unknown distance // function from source to v // Distance from source to source

// All nodes in the graph // are unoptimized - thus are in Q // The main loop

9 Q. 10 11 12 13 14

// Remove and return best vertex // from nodes in two given nodes // we would use a path finding algorithm // on the new graph, // such as depth-first search. for each neighbor v of u: // where v has not yet been removed from alt = dist[u] + length(u, v) if alt < dist[v] // Relax (u,v) dist[v] := alt previous[v] := u return previous[]

SAMPLE INPUT AND PUTPUT ENTER THE NO OF ROUTERS : 3 ENTER THE COST MATRIX VALUES:

Page 30 of 38

EEC-II YR-III SEM-IT2205-DS LAB 0->0:100 0->1:1 0->2:1 1->0:3 1->1:100 1->2:1 2->1:1 2->2:100 ENTER THE SOURCE ROUTER:1 1==> 0: PATH TAKEN :0 ==>2 ==>1 SHORTEST PATH COST: 2

CONCLUSION Thus the Dijkstra Algorithm is implemented using Priority queue.

Page 31 of 38

EEC-II YR-III SEM-IT2205-DS LAB

12. IMPLEMENT A BACKTRACKING ALGORITHM FOR KNAPSACK PROBLEM


PROBLEM STATEMENT Write a program to implement Backtracking algorithm using priority queues DESCRIPTION The knapsack problem or rucksack problem is a problem in

combinatorial

optimization: Given a set of items, each with a weight and a value, determine the
number of each item to include in a collection so that the total weight is less than a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most useful items. In this section we consider backtracking algorithms . As in the preceding section, we view the problem to be solved as a sequence of decisions. A backtracking algorithm systematically considers all possible outcomes for each decision. In this sense, backtracking algorithms are like the brute-force algorithms discussed in the preceding section. However, backtracking algorithms are distinguished by the way in which the space of possible solutions is explored. Sometimes a backtracking algorithm can detect that an exhaustive search is unnecessary and, therefore, it can perform much better. The 0/1 knapsack problem is closely related to the change counting problem discussed in the preceding section: We are given a set of n items from which we are to select some number of items to be carried in a knapsack. Each item has both a weight and a profit. The objective is to chose the set of items that fits in the knapsack and maximizes the profit. Let be the weight of the item, be the profit accrued when the item is

carried in the knapsack, and C be the capacity of the knapsack. Let value of which is either zero or one. The variable carried in the knapsack. Given and

be a variable the item is

has the value one when the

, our objective is to maximize

subject to the constraint

Clearly, we can solve this problem by exhaustively enumerating the feasible solutions and selecting the one with the highest profit. However, since there are possible solutions, the running time required for the brute-force solution becomes prohibitive as n gets large. An alternative is to use a greedy solution strategy which

Page 32 of 38

EEC-II YR-III SEM-IT2205-DS LAB solves the problem by putting items into the knapsack one-by-one. This approach is greedy because once an item has been put into the knapsack, it is never removed. ALGORITHM

SAMPLE INPUT AND OUTPUT Readind data from file BandP.txt 50 replaces -2147483648 57 replaces 50 58 replaces 57 Optimal Knapsack ; (11, 45) (2, 7) (2, 6) Total Weight :15 Total Value : 58 Total method invocations :129

CONCLUSION

Page 33 of 38

EEC-II YR-III SEM-IT2205-DS LAB The Program to implement Backtracking algorithm using priority queues is executed and verified for sample input and output.

13.1 IMPLEMENTATION OF PRIMS AND KRUSKALS ALGORITHM


AIM Write a C program to implement prims algorithm. ALGORITHM 1. Declare the header files. 2. Get the input as no of nodes and edges. 3. Get the weight for all the edges. 4. Find the no of possible path. 5. Find the minimum spanning tree. 6. Print the total length. SAMPLE OUTPUT Enter the no of nodes: 4 Enter the no of edges :5 Enter the no of edges and weight : Enter the edges by v1 and v2 :12 Enter the weight :2 Enter the weight by v1 and v2 :13 Enter the weight :3 Enter the weight :13 Enter the weight :1 Enter the edge by v1 and v2:24 Enter the weight :2 Enter the edgeby v1 and v2 :34 Enter the weight :1 Minimum spanning tree edge(41)& wt= 1 Minimum spanning tree edge(43)& wt= 1 Minimum spanning tree edge(12)& wt= 1 Total path length = 4

CONCLUSION

Page 34 of 38

EEC-II YR-III SEM-IT2205-DS LAB The Program to implement prims algorithm is executed and verified for sample input and output.

VIVA QUESTIONS 1. What are the limitations of arrays?


i) Arrays are of fixed size. ii)Data elements are stored in continuous memory locations which may not be available always. iii)Adding and removing of elements is problematic because of shifting the locations. 2. What is Brute Force algorithm? Algorithm used to search the contents by comparing each element of array is called Brute Force algorithm. 3. How can you overcome the limitations of arrays? Limitations of arrays can be solved by using the linked list. 4. List out the areas in which data structures are applied extensively? Compiler Design, Operating System, Database Management System, Statistical analysis package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation 5. What is a linked list? Linked list is a data structure which store same kind of data elements but not in continuous memory locations and size is not fixed. The linked lists are related logically. 6. What is a node? The data element of a linked list is called a node. 7. What does node consist of? Node consists of two fields:data field to store the element and link field to store the address of the next node. 8. What is the need for the header? Header of the linked list is the first element in the list and it stores the number of elements in the list. It points to the first data element of the list. 9.What do you mean by: Syntax Error, Logical Error, Run time Error? Syntax Error-Syntax Error is due to lack of knowledge in a specific language. It is due to somebody does not know how to use the features of a language.We can know the errors at the time of compilation. logical Error-It is due to the poor understanding of the requirement or problem. Run time Error-The exceptions like divide a number by 0,overflow and underflow comes under this. 10. What do you mean by overflow and underflow? When new data is to be inserted into the data structure but there is no available space i.e.free storage list is empty this situation is called overflow.When we want to delete data from a data structure that is empty thissituation is called underflow. 11. What is the data structures used to perform recursion? Stack. Because of its LIFO (Last In First Out) property it remembers its 'caller' so knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls. Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used. 12.List out few of the Application of tree data-structure? The manipulation of Arithmetic expression, Symbol Table construction, Syntax analysis. 13. In tree construction which is the suitable efficient data structure? (Array, Linked list, Stack, Queue) :Linked list is the suitable efficient data structure. 14. What is the type of the algorithm used in solving the 8 Queens problem? Backtracking. 15. In an AVL tree, at what condition the balancing is to be done? If the 'pivotal value' (or the 'Height factor') is greater than 1 or less than -1. 16. What is the bucket size, when the overlapping and collision occur at same time?

Page 35 of 38

EEC-II YR-III SEM-IT2205-DS LAB One. If there is only one entry possible in the bucket, when the collision occurs, there is no way to accommodate the colliding value. This results in the overlapping of values. 17. Classify the Hashing Functions based on the various methods by which the key value is found. Direct method, Subtraction method, Modulo-Division method, Digit-Extraction method, Mid-Square method, Folding method, Pseudo-random method. 18. What are the types of Collision Resolution Techniques and the methods used in each of the type? Open addressing (closed hashing), The methods used include: Overflow block. Closed addressing (open hashing), The methods used include: Linked list , Binary tree. 19. What is a spanning Tree? A spanning tree is a tree associated with a network. All the nodes of the graph appear on the tree once. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodes is minimized. 20. Does the minimum spanning tree of a graph give the shortest distance between any 2 specified nodes? No. The Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it doesn't mean that the distance between any two nodes involved in the minimum-spanning tree is minimum. 21. Which is the simplest file structure? (Sequential, Indexed, Random) Sequential is the simplest file structure. 22. Whether Linked List is linear or Non-linear data structure? According to Access strategies Linked list is a linear one. According to Storage Linked List is a Non-linear one. 23. Differentiate file structure from storage structure. Basically, the key difference is the memory area that is being accessed. When dealing with the structure that resides the main memory of the computer system, this is referred to as storage structure. When dealing with an auxiliary structure, we refer to it as file structure. 24. When is a binary search best applied? A binary search is an algorithm that is best applied to search a list when the elements are already in order or sorted. The list is search starting in the middle, such that if that middle value is not the target search key, it will check to see if it will continue the search on the lower half of the list or the higher half. The split and search will then continue in the same manner. 25. What are multidimensional arrays? Multidimensional arrays make use of multiple indexes to store data. It is useful when storing data that cannot be represented using a single dimensional indexing, such as data representation in a board game, tables with data stored in more than one column. 26. What is the difference between a grounded header link list and a circular header link list? A header linked list is a linked list which always contains a special node, called the header node, at the beginning of the list. The two kinds of header linked lists are:i. Grounder header linked list ii. Circular header linked list The difference between the two is thatA grounded header list is a header list where the last node contains the null pointer. A circular header list is a header list where the last node points back to the header node. 27. Briefly explain recursive algorithm : Recursive algorithm targets a problem by dividing it into smaller, manageable subproblems. The output of one recursion after processing one sub-problem becomes the input to the next recursive process 28) How do you search for a target key in a linked list?

Page 36 of 38

EEC-II YR-III SEM-IT2205-DS LAB To find the target key in a linked list, you have to apply sequential search. Each node is traversed and compared with the target key, and if it is different, then it follows the link to the next node. This traversal continues until either the target key is found or if the last node is reached. 29.If you are using C language to implement the heterogeneous linked list, what pointer type will you use? - A heterogeneous linked list contains different data types in its nodes. We can not use ordinary pointer to connect them. - The pointer that we use in such a case is void pointer as it is a generic pointer type and capable of storing pointer to any type. 30. What is an iterative algorithm? An iterative algorithm executes steps in iterations. It aims to find successive approximation in sequence to reach a solution. They are most commonly used in linear programs where large numbers of variables are involved. 31. What is sequential search? What is the average number of comparisons in a sequential search? Sequential search searches for elements in an array sequentially until the element is found. The average number of comparisons can be n+1/2. 32. Explain the terms Base case, Recursive case, Binding Time, Run-Time Stack and Tail Recursion. Base case: A case in recursion, in which the answer is known when the termination for a recursive condition is to unwind back. Recursive Case: A case which returns to the answer which is closer. Run-time Stack: A run time stack used for saving the frame stack of a function when every recursion or every call occurs. Tail Recursion: It is a situation where a single recursive call is consisted by a function, and it is the final statement to be executed. It can be replaced by iteration. 33. Is it possible to insert different type of elements in a stack? How? Different elements can be inserted into a stack. This is possible by implementing union / structure data type. It is efficient to use union rather than structure, as only one items memory is used at a time. 34. The maximum degree of any vertex in a simple graph with n vertices is ------------Ans : n-1 35. A technique for direct search is -------Ans : Hashing 36. If a node having two children is deleted from a binary tree, it is replaced by its ---- -Ans: In order successor 37. The searching technique that takes O (1) time to find a data is ---- -----Ans: Hashing 38.The number of interchanges required to sort 5, 1, 6, 2 4 in ascending order using Bubble Sort is --------Ans : 5 39. A linear list of elements in which deletion can be done from one end (front) and insertion can take place only at the other end (rear) is known as a ----------Ans: Queue 40. A full binary tree with n leaves contains --------- nodes? Ans: Non leaf nodes 41. In a linked list with n nodes, the time taken to insert an element after an element pointed by some pointer is order of --------Ans: 1 42. The minimum number of multiplications and additions required to evaluate the polynomial P = 4x3+3x2-15x+45 is -----------Ans : 3 & 3

Page 37 of 38

EEC-II YR-III SEM-IT2205-DS LAB 43. The data structure required for Breadth First Traversal on a graph is ---------Ans: Queue 44.The quick sort algorithm exploit _________ design technique Ans: 45.Representation of data structure in memory is known as: --------Ans: 46. Which sorting algorithm is best if the list is already sorted? Why? Insertion sort as there is no movement of data if the list is already sorted and complexity is of the order O(N) 47. What is an algorithm? What are the characteristics of a good algorithm? An algorithm is a step-by-step procedure for accomplishing some task'' An algorithm can be given in many ways. For example, it can be written down in English (or French, or any other ''natural'' language). However, we are interested in algorithms which have been precisely specified using an appropriate mathematical formalism--such as a programming language. Every algorithm should have the following five characteristics: Input: The algorithm should take zero or more input. Output: The algorithm should produce one or more outputs. Definiteness: Each and every step of algorithm should be defined unambiguously. Effectiveness: A human should be able to calculate the values involved in the procedure of the algorithm using paper and pencil. Termination: An algorithm must terminate after a finite number of steps. 48.The OS of a computer may periodically collect all the free memory space to form contiguous block of free space. This is called ----------Ans : Garbage collection 49. What are circular queues? Static queues have a very big drawback that once the queue is FULL, even though we delete few elements from the "front" and relieve some occupied space, we are not able to add anymore elements as the "rear" has already reached the Queue's rear most position 50. What are the different ways of representing a graph? Adjacency list representation and Adjacency Matrix representation

Page 38 of 38

Вам также может понравиться