Академический Документы
Профессиональный Документы
Культура Документы
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
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
Page 2 of 38
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
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
Page 6 of 38
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.
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
CONCLUSION The employee data base system is implemented using structures and arrays. The need for Linked list is also understood from this program.
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
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.
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
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.
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
Page 13 of 38
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
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
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
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
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
Page 28 of 38
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
// 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
Page 31 of 38
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
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.
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.
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