Anda di halaman 1dari 52

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

LAB MANUAL DATA STRUCTURE THROUGH C++


FOR THE ACADAMIC YEAR (2011-2012)

Department of Computer Science and Engineering

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

LAB CODE

1. Student should report to the concerned as per the time table. 2. Students who turn up late to the labs will in no case be permitted to the program schedule for the day. 3. After completion of the program, certification of the concerned staff incharge in the observation book is necessary. 4. Student should bring a note book of 100 pages and should enter the readings/observations into the note book while performing the experiment. 5. The record of observations along with the detailed experimental procedure of the experiment in the immediate last session should be submitted and certified staff member in-charge 6. Not more than 3 students in a group are permitted to perform the experiment on the set. 7. The group-wise division made in the beginning should be adhered to and no mix up of students among different groups will be permitted. 8. The components required pertaining to the experiment should be collected from stores in-charge after duly filling in the requisition form. 9. When the experiment is completed, should disconnect the setup made by them, and should return all the components / instruments taken for the purpose. 10.Any damage of the equipment or burn out components will be viewed seriously either by putting penalty or by dismissing the total group of students from the lab for the semester / year. 11.Students should be present in the labs for total scheduled duration. 12.Students are required to prepare thoroughly to perform the experiment before coming to laboratory. 13.Procedure sheets/data sheets provided to students groups should be maintained neatly and to be returned after the experiment.
2 |Page

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

INDEX

SNO 1 2 3 4 5 6 7 8 9 10 11 12 13

Experim ent No

Name of the Experiment

Page No 4 5-9 10-14 15-16 17-19 20-13 24-26 27-32 33-36 37-39 40-42 43-45 46-47

Objective , Hardware Software Requirement, Instructions 1 2 3 4 5 6 7 8 9 10 11 12 Stack ADT & Queue ADT using Array Stack ADT & Queue ADT using Linked List Deque using Doubly Linked List Binary Search Tree Non Recursive Traversal of BST Recursive Traversal of BST BFS & DFS Marge Sort and Heap Sort B-TREE AVL Tree Dictionary Knuth-Morris- Pratt

3 |Page

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Objective
To make the student learn an object oriented way of solving problems and To make the student write ADTS for all data structures.

Hardware and Software required


1. Intel based desktop PC 2. Minimum of 166 MHZ or faster processor 3. At least 64 MB RAM 4. At least 100 MB free disk space 5. C++ compiler and STL Recommended

4 |Page

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

1 Stack and Queue ADT using

Name of the Experiment: Array

1. AIM: To Implement a Stack and Queue Abstract Data Types using Array data structure C++ programs to implement the following using an array.
a)

Stack ADT b) Queue ADT

2. Theory: 2.A)Stack ADT


Well illustration from the real world is a stack of books, where you can operate with a "top" of the stack only. We will dedicate six operations on the stack. You can put a book on top (push); look, which one lays on top of a stack (peek) and remove a topmost book (pop) and check, if stack is empty (isEmpty). Also, there are two operations to create and to destroy a stack. Let us structure them up in the following list.

Operations

Stack create() creates empty stack boolean isEmpty(Stack s) tells whether the stack s is empty push(Stack s, Item e) put e on top of the stack s Item peek(Stack s) returns topmost element in stack s Precondition: s is not empty pop(Stack s) removes topmost element from the stack s Precondition: s is not empty destroy(Stack s) destroys stack s

Example
Sketchy, stack can be shown like this:

5 |Page

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

3.a)Algorithm:
1. 2. 3. 4. 5.

Initialy top = -1; push operation increases top by one and writes pushed element to storage[top]; pop operation checks that top is not equal to -1 and decreases top variable by 1; peek operation checks that top is not equal to -1 and returns storage[top]; isEmpty returns boolean (top == -1).

4.A) Input:
PUSH(10), PUSH(20), PUSH(30)

5.A) Output:
POP()-> 30, POP()-> 20, POP()-> 10

2.B)Queue ADT
In practice we often deal with priorities. For instance, in a to-do-list for a day, each task has an associated significance. Is absolutely necessary to collect a car from repair shop (highest priority) and you may possibly watch a new film (lowest priority). Besides real life examples, many computer tasks work with priorities. Frequently cited instance is the Dijkstra's shortest path algorithm. Priority queue ADT lets us to work with objects that have an associated priority.

6 |Page

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Operations

PriorityQueue create() creates empty priority queue boolean isEmpty(PriorityQueue pq) tells whether priority queue pq is empty insert(PriorityQueue pq, Item e) inserts item e to priority queue pq Item minimum(PriorityQueue pq) tells minimal item in priority queue pq Precondition: pq is not empty removeMin(PriorityQueue pq) removes minimum item from priority queue pq Precondition: pq is not empty destroy(PriorityQueue pq) destroys priority queue pq

3.B)Algorithm:
1. 2. 3.

Initialy front = -1 and rear =-1; push operation increases rear by one and writes pushed element to storage[rear]; pop operation checks that front is not equal to -1 and increases front variable by 1;

4.B)Input:
PUSH(10), PUSH(20), PUSH(30)

5.B)Output:
POP()-> 10, POP()-> 20, POP()-> 30

6.Inference: Stack is a Last in First Out ADT and Queue is a First in First Out ADT. 7. Applications:
1. Stack: Expression Tress, searching in Binary Tree 2. Queue: Linear Search and BFS 7 |Page

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

8.Extension:
Implementation of railway booking systems with multiple ticket request.

9.Viva Voice Questions:


1. The time to initialize the max heap is _______ [01M01] 1. O(1) 2. O(N) 3. O(N2) 4. O( log N) 2. The total time taken by performing n inserts into an initially empty heap is _____ [01M02] 1. 2. 3. 4. O(N log N) O(N) O(N2) O( log N)

3. A complete binary tree with the property that the value at each node is atleast as large as the values at its children is know as ____ [01M03] 1. 2. 3. 4. Heap Binary search tree Balanced tree AVL tree

4.Which of the following is not an application of Priority Queues? [01M04] 1. 2. 3. 4. Machine scheduling The generation of Huffman codes Developing O(n log n) sorting method Finding shortest distance

5. A priority queue is efficiently implemented with the help of ______ data structure. [01S01] 1. 2. 3. 4. Stack Queue Heap List

6. If a simple linked list is used to implement the insertion operation on to a priority queue at the front in, then the complexity is ______ [01S02] 1. O(1) 2. O(N) 3. O(N2) 4. O( log N) 7. The average running time for insertion operation of the priority queue if it is implemented by using a binary search tree is ______ [01S03]
8 |Page

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. O(1) 2. O(N) 3. O(N2) 4. O( log N) 8. A heap which is a complete binary tree, with n elements has ______ height. [01S04]
1. 2. 3. 4.

log2(1) log2(n) log2(n+1) log2(2n)

9. The complexity for deleting an element into a heap is _____ [01S05]


1. 2. 3. 4.

log2(1) log2(n) log2(n+1) log2(2n)

10. The complete binary tree heap with height [log2(n+1)] has at most ______ nodes at level j. [01S06] 1. 2. 3. 4. 2j 2j-1 2*j 2

9 |Page

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

2 Stack and Queue ADT using

Name of the Experiment: Linked List

1. AIM: To Implement a Stack and Queue Abstract Data


Types using Linked List Data structure C++ programs to implement the following using a linked list.
b)

Stack ADT b) Queue ADT

2. Theory: 2.A)Stack ADT


Well illustration from the real world is a stack of books, where you can operate with a "top" of the stack only. We will dedicate six operations on the stack. You can put a book on top (push); look, which one lays on top of a stack (peek) and remove a topmost book (pop) and check, if stack is empty (isEmpty). Also, there are two operations to create and to destroy a stack. Let us structure them up in the following list.

Operations

Stack create() creates empty stack boolean isEmpty(Stack s) tells whether the stack s is empty push(Stack s, Item e) put e on top of the stack s Item peek(Stack s) returns topmost element in stack s Precondition: s is not empty pop(Stack s) removes topmost element from the stack s Precondition: s is not empty destroy(Stack s) destroys stack s

Example
Sketchy, stack can be shown like this:

10 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

3.a)Algorithm:

Initialy top = -1; 7. push operation increases top by one and writes pushed element to storage[top]; 8. pop operation checks that top is not equal to -1 and decreases top variable by 1; 9. peek operation checks that top is not equal to -1 and returns storage[top]; 10. isEmpty returns boolean (top == -1).
6.

4.A) Input:
PUSH(10), PUSH(20), PUSH(30)

5.A) Output:
POP()-> 30, POP()-> 20, POP()-> 10

2.B)Queue ADT
In practice we often deal with priorities. For instance, in a to-do-list for a day, each task has an associated significance. Is absolutely necessary to collect a car from repair shop (highest priority) and you may possibly watch a new film (lowest priority). Besides real life examples, many computer tasks work with priorities. Frequently cited instance is the Dijkstra's shortest path algorithm. Priority queue ADT lets us to work with objects that have an associated priority.

11 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Operations

PriorityQueue create() creates empty priority queue boolean isEmpty(PriorityQueue pq) tells whether priority queue pq is empty insert(PriorityQueue pq, Item e) inserts item e to priority queue pq Item minimum(PriorityQueue pq) tells minimal item in priority queue pq Precondition: pq is not empty removeMin(PriorityQueue pq) removes minimum item from priority queue pq Precondition: pq is not empty destroy(PriorityQueue pq) destroys priority queue pq

3.B)Algorithm:
4. 5. 6.

Initialy front = -1 and rear =-1; push operation increases rear by one and writes pushed element to storage[rear]; pop operation checks that front is not equal to -1 and increases front variable by 1;

4.B)Input:
PUSH(10), PUSH(20), PUSH(30)

5.B)Output:
POP()-> 10, POP()-> 20, POP()-> 30

6.Inference: Stack is a Last in First Out ADT and Queue is a First in First Out ADT. 7. Applications:
3. Stack: Expression Tress, searching in Binary Tree

4. Queue: Linear Search and BFS


12 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

8.Extension:
Implementation of railway booking systems with multiple ticket request.

9. Viva voice Questions:


1. In the worst case, at most ______________ comparisons are used by heapsort. [02D01] 1. 2. 3. 4. 2N log N O(N) 2N log N - O(N) 2N log N + O(N)

2. The average number of comparisons used to heap sort a random permutation of N distinct items is _____________ [02D02] 1. 2. 3. 4. 2N log N + O(N) 2N log N - O(N) 2N log N * O(N) 2N log N / O(N)

3. The number of passes required for sorting M records of length N using simple external sorting algorithm is __________ [02M01] 1. 2. 3. 4. [log(N+M)] [log(N-M)] [log(N*M)] [log(N/M)]

4. Choose the correct statement, [02M02] 1. 2. 3. 4. Internal sorting is used if the number of items to be sorted is very large External sorting is used if the number of items to be sorted is very large External sorting does not need auxiliary storage Internal sorting needs auxiliary storage

5. Which of the following sorting algorithm has the worst time complexity of O(n log n)? [02S01] 1. 2. 3. 4. Heap sort Quick Sort Insertion sort Selection sort

6. A sort which uses the binary tree concept such that any number is larger than all the numbers in the subtree below it is called ______ [02S02] 1. 2. 3. 4. Selection sort Insertion sort Heap sort Quick sort

13 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

7. The basic external sorting algorithm uses ______ concept. [02S03] 1. 2. 3. 4. Partition Merging Randomizing Selecting

8. ________ is derived from an ordinary binary search tree by adding the field left size to each tree node. [03D01] 1. 2. 3. 4. Binary search tree with duplicates Binary tree Logographical binary search tree Indexed binary search tree

9. Which of the following traversal techniques lists the nodes of a binary search tree in ascending order? [03M01] 1. 2. 3. 4. Post-order In-order Pre-order Out-order

10. The worst case complexity for delete operation in a binary search tree is ______ [03M02] 1. 2. 3. 4. O(n) O(n log n) O(h) O(n log n)

14 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

3 Deque ADT using Linked List

Name of the Experiment:

1. AIM: To Implement a Deque Abstract Data Types using Linked List Data structure Write C++ programs to implement the deque (double ended queue) ADT using a doubly linked list and an array. 2. Theory: Deque ADT
A deque, D, has data stored in an array D:A[1::n] and the current index of the front and back of the deque are stored in D:front and D:back (the contents of which can be accessed using D:A[D:front] and D:A[D:back]). The size of the array is stored in the constant D:n. A boolean ag D:isempty is set to true when the deque contains no elements. You are required to write pseudocode for the functions: (a) PopFront(D) and PopBack(D) which takes a deque as input and returns the value from the front or back of the deque (b) PushFront(D; v) and PushBack(D; v) which adds the value v to the front or back of the stack (c) SizeOf(D) which returns the number of elements currently in the deque You must update the indexes to the front and back of the deque as necessary and also report underow or overow errors as appropriate. A newly initialised deque has D:isempty = true while D:front and D:back are not assigned. Again, assume that parameters are passed by reference.
2.

Algorithm:
1. Create the Array 2. Front and Rear are at front. 3. If Insert at END Only Increment the rear 4. If Insert at FRONT 5. Increment Rear 6. Implement swap() method 7. Insert value 8. If delete at From Increment front
9. If Delete at Rear Decrement Rear

15 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

3.Inference: A Deque is a First in First out and First In Last Out or Any order implementation. 4. Input Push(10), Push(10), Push(30), POPR(),POPf() 5. Output 30 10

6. Applications:
1. Queue: Multi way search tree

5.Extension:
Implement a two way array.

6.Viva voice Questions:


1. The worst case complexity for search operation in a binary search tree is ______ [03M03] 1. 2. 3. 4. O(n) O(n log n) O(h) O(log n)

2. In a binary search tree if the search is ________ then the element is inserted at the point the search terminated. [03M04] 1. 2. 3. 4. Successful Un Successful True Correct

3. In binary search tree, if the element to be inserted is greater than the root node, the element is inserted in ______ [03S01] 1. 2. 3. 4. Root right sub-tree left sub-tree cannot be inserted

4. The time complexity for insert operation in binary search tree with height h and n nodes is ________ [03S02]
16 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. 2. 3. 4.

O(n) O(n log n) O(h) O(log n)

5. The order of the binary search algorithm is ______ [03S03] 1. n 2. n2 3. n log n 4. log n

17 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

4 Binary Search Tree

Name of the Experiment:

1. AIM: Write a C++ program to perform the following operations: a) Insert an element into a binary search tree. b) Delete an element from a binary search tree. c) Search for a key element in a binary search tree. 2. Theory:

Binary search tree


First of all, binary search tree (BST) is a dynamic data structure, which means, that its size is only limited by amount of free memory in the operating system and number of elements may vary during the program run. Main advantage of binary search trees is rapid search, while addition is quite cheap. Let us see more formal definition of BST. Binary search tree is a data structure, which meets the following requirements:

it is a binary tree; each node contains a value; a total order is defined on these values (every two values can be compared with each other); left subtree of a node contains only values lesser, than the node's value; right subtree of a node contains only values greater, than the node's value.

Notice, that definition above doesn't allow duplicates.

Example of a binary search tree

18 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

What for binary search trees are used?


Binary search tree is used to construct map data structure. In practice, data can be often associated with some unique key. For instance, in the phone book such a key is a telephone number. Storing such a data in binary search tree allows to look up for the record by key faster, than if it was stored in unordered list. Also, BST can be utilized to construct set data structure, which allows to store an unordered collection of unique values and make operations with such collections. Performance of a binary search tree depends of its height. In order to keep tree balanced and minimize its height, the idea of binary search trees was advanced in balanced search trees (AVL trees, Red-Black trees, Splay trees). Here we will discuss the basic ideas, laying in the foundation of binary search trees.

3. Algorithm: 1. Add a new value 2. Search for a value 3. Remove a value 4. Get values from BST in order 4. Inference: Binary search tree is ADT which is best for searching and does not allow Duplicate values. 5. Input Insert(1o), Insert(9), Insert(20), Insert(8), display() 6. Output 8 9 10 20

7. Applications:
1. BST: Advanced Searing techniques

8. Extension:
Implement a search engine.

9. Viva voice Questions:


1. A binary search tree contains the values - 1,2,3,4,5,6,7,8. The tree is traversed in preorder and the values are printed out. Which of the following sequences is a valid output? [03S04]
19 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. 2. 3. 4.

53124786 53126497 53241678 53124768

2. In a binary search tree if the key element is less than the root element then sub tree must be searched in ________ [03S05] 1. 2. 3. 4. left right root center

3. In a binary search tree keys are inserted in the order 1, 2, 3&&. n as result then find insert, delete operations take time as _______. [04M01] 1. O(n) 2. O(n log n) 3. O(n2 ) 4. O(log n) 4. Which of the following operation is not performed on a dictionary? [04M02] 1. 2. 3. 4. Insert Sorting Search Deleting

5. Which traversal of a binary search tree traverses visits to the nodes in ascending order of key values? [04M03] 1. 2. 3. 4. In order Past order Pre order Post order

6. To delete a leaf node in binary search tree_____ [04M04] 1. 2. 3. 4. Node is replaced by its child Node is replaced by smallest element in right sub tree The Pointer in the parent node is made null Nodes parent will point to nodes child

7. Which of the following statement is false with respect to binary search tree? [04M05] 1. 2. 3. 4. Right child is greater than left child Root has maximum elements Right child is greater than parent node Left child is less than parent node

8. In indexed binary search tree left side field contain _______ [04S01]
20 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. 2. 3. 4.

no. of elements in left sub tree +1 Value of left leaf node no. of left leaf node+1 no. of elements in left sub tree

21 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

5
Non Recursive Traversal of BST

Name of the Experiment: 1. AIM:

Write C++ programs that use non-recursive functions to traverse the given binary tree in a) Preorder b) Inorder and c) Postorder. 2. Theory:

Binary search tree Traversal Tree traversal


In computer science, tree-traversal refers to the process of visiting each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited. The following algorithms are described for a binary tree, but they may be generalized to other trees as well. Traversal methods Compared to linear data structures like linked lists and one dimensional arrays, which have only one logical means of traversal, tree structures can be traversed in many different ways. Starting at the root of a binary tree, there are three main steps that can be performed and the order in which they are performed define the traversal type. These steps (in no particular order) are: performing an action on the current node (referred to as "visiting" the node), traversing to the left child node, and traversing to the right child node. Thus the process is most easily described through recursion. To traverse a non-empty binary tree in preorder, perform the following operations recursively at each node, starting with the root node: # Visit the root. # Traverse the left subtree. # Traverse the right subtree.(This is also called Depth-first traversal.) To traverse a non-empty binary tree in inorder, perform the following operations recursively at each node, starting with the root node: # Traverse the left subtree. # Visit the root. # Traverse the right subtree. To traverse a non-empty binary tree in postorder, perform the following operations recursively at each node, starting with the root node: # Traverse the left subtree. # Traverse the right subtree. # Visit the root.
22 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Finally, trees can also be traversed in level-order, where we visit every node on a level before going to a lower level. This is also called Breadth-first traversal.

3.Algorithm:
1. preorder(node) print node.value if node.left null then preorder(node.left) if node.right null then preorder(node.right) 2. inorder(node) if node.left null then inorder(node.left) print node.value if node.right null then inorder(node.right) 3. postorder(node) if node.left null then postorder(node.left) if node.right null then postorder(node.right) print node.value

4. Input Insert(1o), Insert(9), Insert(20), Insert(8), inorder(),preorder(),postorder() 5. Output 8 10 8 9 9 9 10 8 20 20 20 10

5. Inference: In order traversal gives a sorted data set in ascending order. 6. Applications:
2. BST: Advanced Searing techniques

7. Extension:
Implement a search engine.

8. Viva voice Questions:


1. Before inserting an element in a binary search tree we must perform______ operation to check distinct property. [04S02] 1. 2. 3. 4. Create ascend delete search

2. If the root is null it means that search tree has_____ [04S03]


23 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. 2. 3. 4.

1 element un known elements un countable elements no element

3. A rotation is local operation in a search tree that preserves traversal key ordering is _______ [04S04] 1. 2. 3. 4. Pre order Post order Past order In order

4. The height of the AVL Tree with n elements is______ [05S01] 1. log n 2. n2 3. n 4. n log n 5. In AVL trees the transformation for an imbalance can be viewed as an LL rotation followed by an RR rotation. [05S02] 1. 2. 3. 4. LR LL RL RR

6. Trees with a worst-case height of O(log n) are called ______ [05S03] 1. 2. 3. 4. Binary trees binary search trees Balanced trees bipartite trees

7. An n element AVL search tree can be searched in _________ time. [05S04] 1. 2. 3. 4. O(n) O(n log n) O(h) O(log n)

8. The complexity for inserting a new element in to an n-element AVL search tree is _________ [05S05] 1. 2. 3. 4. O(n) O(n log n) O(h) O(log n)

9. The complexity for deleting an element from an n-element AVL search tree is _________ [05S06]
24 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. 2. 3. 4.

O(n) O(n log n) O(h) O(log n)

10. The difference between the height of left sub tree & right sub tree is called____ [05S07] 1. 2. 3. 4. Load balance Balance Factor Rank Height difference

11. If a new node is added on the left side of left sub tree and tree is imbalance then the balance factor of the node which is imbalanced is_______ [05S08] 1. 2. 3. 4. 2 -2 0 either 2 or -2

12. If a new node is added on the right side and AVL tree is imbalance then the balance factor of the node which is imbalanced is_______ [05S09] 1. 2. 3. 4. either 2 or -2 -2 0 2

13. Which of the following balance factor is not allowed in AVL trees? [05S10] 1. 2. 3. 4. 0 2 -1 1

14. The permissible balance factors of an AVL trees are ____ [06D01] 1. 2. 3. 4. -1,0,1 -1,0,2 1,0,-2 0,1,2

15. In deletion of AVL Search tree which of the following is not classified as imbalance? [06M01] 1. 2. 3. 4. R-1 R1 R0 R2

25 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

6
Recursive Traversal of BST

Name of the Experiment: 1. AIM:

Write C++ programs that use recursive functions to traverse the given binary tree in a) Preorder b) Inorder and c) Postorder. 2. Theory:

Binary search tree Traversal Tree traversal


In computer science, tree-traversal refers to the process of visiting each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited. The following algorithms are described for a binary tree, but they may be generalized to other trees as well. Traversal methods Compared to linear data structures like linked lists and one dimensional arrays, which have only one logical means of traversal, tree structures can be traversed in many different ways. Starting at the root of a binary tree, there are three main steps that can be performed and the order in which they are performed define the traversal type. These steps (in no particular order) are: performing an action on the current node (referred to as "visiting" the node), traversing to the left child node, and traversing to the right child node. Thus the process is most easily described through recursion. To traverse a non-empty binary tree in preorder, perform the following operations recursively at each node, starting with the root node: # Visit the root. # Traverse the left subtree. # Traverse the right subtree.(This is also called Depth-first traversal.) To traverse a non-empty binary tree in inorder, perform the following operations recursively at each node, starting with the root node: # Traverse the left subtree. # Visit the root. # Traverse the right subtree. To traverse a non-empty binary tree in postorder, perform the following operations recursively at each node, starting with the root node: # Traverse the left subtree. # Traverse the right subtree. # Visit the root.
26 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Finally, trees can also be traversed in level-order, where we visit every node on a level before going to a lower level. This is also called Breadth-first traversal.

3. Algorithm:
1. preorder(node) print node.value if node.left null then preorder(node.left) if node.right null then preorder(node.right) 2. inorder(node) if node.left null then inorder(node.left) print node.value if node.right null then inorder(node.right) 3. postorder(node) if node.left null then postorder(node.left) if node.right null then postorder(node.right) print node.value

4. Input Insert(1o), Insert(9), Insert(20), Insert(8), inorder(),preorder(),postorder() 5. Output 8 10 8 9 9 9 10 8 20 20 20 10

5. Inference: In order traversal gives a sorted data set in ascending order. 6.Applications:
1. BST: Advanced Searing techniques

7.Extension:
Implement a search engine.

8.Viva Voice Questions:


1. In AVL trees the transformation for an imbalance can be viewed as an LL rotation followed by an RR rotation is ________ [06M05] 1. 2. 3. 4. LR RL RR LL

27 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

2. In AVL trees the transformation for an imbalance can be viewed as an RR rotation followed by an LL rotation is ______ [06M06] 1. 2. 3. 4. RR LL LR RL

3. After inserting an element in AVL tree node A became imbalanced. The new element added in the left child of right grandchild of node A. Then the imbalance is of type ______ [06M07] 1. 2. 3. 4. RR LL LR RL

4. Which of the following is an example of balanced binary tree structure? [06S01] 1. 2. 3. 4. B-tree 2-4 tree AVL tree B+ tree

5. The transformation done for ____ and ____ imbalances are called double rotations that causes due to insertion in a AVL tree [06S02] 1. 2. 3. 4. LL & RL LL & RR LR & RL RR & RL

6. The rank of the external node and root node is ______ [07M01] 1. 2. 3. 4. 0&2 1&2 0 &1 1&0

7. A binary search tree in which every node is colored either with read or black is _______ [07S01] 1. 2. 3. 4. AVL trees Red-Black trees Splay trees B-trees

8. If a non-leaf node is red then it has ______ [07S02] 1. both black &red child 2. only red Childs 3. only black Childs
28 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

4. no-child 9. In red-black trees every path from the root to an external node has _______ pointers [07S03] 1. 2. 3. 4. 2 black 1 red 2 red 1 balck

29 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

7
BFS & DFS

Name of the Experiment: 1. AIM:

Write C++ programs for the implementation of bfs and dfs for a given graph. 2.Theory:
A graph G = (V, E) consists of a set of vertices V, and a set of edges E. In an undirected graph, we represent an edge by a pair of vertices (u, v) indicating that vertex u and v are connected by an edge. In the case of a directed graph, we represent an edge by an ordered pair (u, v) indicating a directed edge from vertex u to v. When analyzing the runtime of algorithm, we will use V to indicate the number of vertices in the graph and E to indicate the number of edges in the graph. In the pseudo-codes, we assume that the vertices are labeled from 0V-1. A graph may be weighted - each edge has a weight associated with it. Graph Representation: There are two ways to store the graph in your program: 1) Adjacency Matrix Use a 2D array bool graph[][] to represent the graph. graph[u][v] = true iff (u, v) is an edge in the graph Cons: use lots of memory, take O(V) to check all edges leaving a vertex. Pros: can check existence of edge in O(1) time. 2) Adjacency List Use a vector< vector<int> > graph to represent the graph. graph[u] is a vector storing all vertex v for which the edge (u, v). Cons: slow to check on the existence of an edge in the graph Pros: low memory usage, fast to check all edges leaving a vertex. Graph Exploration: The most basic thing we want to do with a graph is to explore all of its vertices from some source vertex s. This is useful for many purposes such as checking the connectivity of the graph.
30 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

There are two basic algorithms: 1) Depth First Search A recursive algorithm that explore each branch of a graph as much as possible. At a vertex v, we explore all edges e = (v, u) that leaves v and recurse on the vertex u. After all edges are explored, we backtrack to the vertex where we came from. In the main function, we call dfs(s). bool seen[]; void dfs( int v ) { seen[v] = true; for ( each edge e = (v, u) leaving from v ) if ( !seen[u] ) dfs( u ); } 2) Breadth First Search Explore the vertices of in the sequence of when we first discover it. We maintain a queue that stores all nodes that weve discovered but not yet processed. At each stage, we process the node at the front of the queue. When we process node v, we add all newly discovered nodes reachable from v to the end of the queue we are maintaining. At the very beginning, only the source vertex is in the queue. bool seen[]; void bfs( int s ) { seen[s] = true; queue<int> q; q.push(s); while ( !q.empty() ) {
31 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

int v = q.front(); q.pop(); for ( each edge e = (v, u) leaving from v ) { if ( !seen[u] ) { q.push(u); seen[u] = true; } } } }

3. Algorithm:

DFS
bool seen[]; void dfs( int v ) { seen[v] = true; for ( each edge e = (v, u) leaving from v ) if ( !seen[u] ) dfs( u ); }

BFS
bool seen[]; void bfs( int s ) { seen[s] = true; queue<int> q; q.push(s);
32 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

while ( !q.empty() ) { int v = q.front(); q.pop(); for ( each edge e = (v, u) leaving from v ) { if ( !seen[u] ) { q.push(u); seen[u] = true; } }}}

4.Input: Mentioned in Code 5.Output


enterno of vertices9 ente no of edges9

EDGES 12 23 15 14 47 78 89 26 57 enter initial vertex1 Visited vertices 12 4 5 3 6 7 8 9 33 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

6.Inference:
Searing in a graph not in tree.

7.Applications:
1. BST: Advanced Searing techniques

8.Extension:
Implement a travelling seals man problem.

9.Viva Voice Questions:


1. In red-black trees the value of any node is ____ than the value of its left child. [07S04] 1. 2. 3. 4. equal less unequal greater

2. In red-black trees the value of any node is ____ than the value of its right child. [07S05] 1. 2. 3. 4. equal less unequal greater

3. In red-black trees every path from the root to a leaf node contains the same number of _______ [07S06] 1. 2. 3. 4. nodes leaf nodes black nodes red nodes

4. In red-black trees the external nodes are represented by ______ [07S07] 1. 2. 3. 4. Un shaded squares shaded squares shaded circles Un shaded circles

5. In red-black trees the black nodes are represented by ______ [07S08] 1. 2. 3. 4. Un shaded squares shaded squares shaded circles Un shaded circles

6. In red-black trees the red nodes are represented by ______ [07S09]


34 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. 2. 3. 4.

Un shaded squares shaded squares shaded circles Un shaded circles

7. If all the nodes in a splay tree are accessed in sequential order, then the total access time is _______, regardless of the initial tree. [08D01] 1. 2. 3. 4. O(n) O( log n) O( n log n) O( n*n)

8. In splay trees the difference between concrete and amortized cost is charged against the _______ of the data structures. [08D02] 1. 2. 3. 4. Potential analysis search runtime

9. If all the nodes in a splay tree are accessed in sequential order, the resulting tree consists of _______ [08D03] 1. 2. 3. 4. chain of left children chain of right children left children followed by parent right children followed by parent

10. A sequence of m operations on splay tree with initially n nodes takes _____ time order. [08M01] 1. 2. 3. 4. O(n log n + m log n) O(n*m) O(n log n*n) O(n log n*m)

35 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

8
Marge Sort and Heap Sort

Name of the Experiment: 1.AIM:

Write C++ programs for implementing the following sorting methods: a) Merge sort b) Heap sort 2. Theory:
Heap Sort Theory 1. For a tree of height h, we know a binary tree is h = lg n-1 so 2^h = n-1. For a height h, the smallest number of elements possible is that 1 element is in the last level of the tree. So this algorithm is 2^(h) number of elements. For a maximum number of elements, the tree will be full and balanced, so the number of elements will be 2^(h+1) 1. For a example a tree with height 2, will have 2^(2) nodes or 4 nodes. In the max case the tree will be full and we will have 2^3 -1 or 7 nodes. (Use the tree in answer 3 to see how it looks and count the nodes) 2. The smallest number must be a leaf node, it necessarily doesnt have to be in the last level of a height h, or necessarily be the last node in the tree. But since the largest number is a parent and its children cant be larger than its parent thus smallest number is a leaf node. 3. To check this we need to first use a small array then consider it at n. So for a 7 element array <7,6,5,4,3,2,1,> which is reverse sorted, the heap tree is
7

Which is in fact a heap, for n numbers which is in the array of <n,n-1,n-2 .. 2,1,0>, we will find out that this tree is indeed a heap as well, since no node underneath the parents will be greater than the parent.

36 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

4. <23, 17, 14, 6, 13, 10, 1, 5, 7, 12> is in array form, in a tree form we can determine if this is indeed a heap.

2 3

1 7 1 3 1 2 1 0

1 4

From looking at the tree, this array is not a heap. The reason involves the left most sub tree. In order for something to be a heap the parents value must be higher or equal to all of its children. For a example 23 is larger than 17 or 14, so that would satisfy a heap. But in the bottom sub tree the parent 6 has 2 values 5 and 7, but 7 is larger than 6, so it isnt a heap.

Merge Sort
Most sorting algorithms rely upon random-access memory, but merge sort is interesting because it is effective even when one has an extremely restrictive interface to the store (such as an external tape drive or an internal linked-list). The primary data type in dc is the arbitrary-precision number. With one such number we have a stack, accessed via the units position; with two such numbers, mirrored with respect to each other, we have a structure resembling a tape. Given the sequential-access nature of dc numeric values, the merge sort would appear to be a natural algorithm for this environment. With a only few exceptions, dc identifiers are limited to single characters. We will follow a "harvard" convention, and use the lower-case registers for varying values, retaining the upper-case for constant code. Here is a quick synopsis of the program state: The primary variable is s, containing the list to be sorted. It is split into pairs of lists, x and y (of stride length l). Each of these is split into elements, g and h respectively, and merged onto a result list z. Finally, to set up the next pass, the data from z is rewound onto s, and l is doubled to match the new stride length.

37 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

3. Algorithm:
1. partitions and merges by stride (lPx) 2. rewinds (lRx) the merged output back to the input 3. doubles the stride length (ll 2* sl) 4. and repeats while the input is longer than a stride (ll lsZ >D).

4. Input 11 10 9 17 13

5. Output 9 10 11 13 17

Inference:
Sorting Techniques.

6. Applications:
Advanced sorting on unformatted Data

7. Extension:
Implement a file sorting algorithm for Hard Disk.

8. Viva Voice Questions:


1. Which of the following is not a splay operation? [08M02] 1. 2. 3. 4. Split Insert Delete Search

38 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

2. The _______ complexity of an operation in splay tree is an accounting artifact that often bears no direct relationship to the actual complexity. [08M03] 1. 2. 3. 4. Amortized Time Space Potential

3. The sum of the amortized complexities of all operations in the sequence be ________ to the sum of their actual complexities. [08M04] 1. 2. 3. 4. only equal greater than or equal less than or equal unequal

4. The amortized complexity of a find, insert or delete operation performed on a splay tree with n elements is ________ [08M05] 1. 2. 3. 4. O(n) O( log n) O( n log n) O( n*n)

5. Splay trees are invented by ______ [08S01] 1. 2. 3. 4. Hoare & Knuth Sleater & Hoare Knuth& Tarjan Sleator & Tarjan

6. The run time for a splay(x) operation is proportional to the length of the _____ path for x [08S02] 1. 2. 3. 4. join search shortest Insert

7. In a B-tree of order 5, all the non leaf nodes have between ______ and ______ children. [09D01] 1. 2. 3. 4. 1&5 2&5 3&5 4 &5

39 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

9
B-TREE

Name of the Experiment: 1. AIM:

Write a C++ program to perform the following operations a) Insertion into a B-tree b) Deletion from a B-tree 2. Theory:
A B-tree of order m is an ordered tree which satisfies the following properties:

Every node has at most m children. Every node, except the root, has at least m/2 children. The root has at least 2 children. All leaves occur on the same level. The standard representation adopted here is a sequence of number of children of each internal node, where the nodes are traversed bottom-up level-by-level and from rightto-left within a level. See the following figure for an example:

This is a B-tree of order 4 and has the encoding 3 2 2 2 3 2 4 2 3 2 3 . For B-tree of order 3 with n = 1,2,..,17 leaves, the number of trees are: 0, 1, 1, 1, 2, 2, 3, 4, 5, 8, 14, 23, 32, 43, 63, 97, 149.

3.Algorithm: Insert
1. Split the leaf page. 2. Records with keys < middle key go to the left leaf page. 3. Records with keys >= middle key go to the right leaf page. 4. Split the index page. 5. Keys < middle key go to the left index page. 6. Keys > middle key go to the right index page. 7. The middle key goes to the next (higher level) index. IF the next level index page is full, continue splitting the index pages.

Delete
1. Combine the leaf page and its sibling. 2. Adjust the index page to reflect the change.

40 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT


3. Combine the index page with its sibling. Continue combining index pages until you reach a page with the correct fill factor or you reach the root page.

4. Input As Per the code

5. Output As Per the code

6.Inference:
Best for Storage Techniques

7.Applications:
Database applications

8. Extension:
Implement a own database storage.

9. Viva Voice Questions:


1. After deleting an element from a B-tree we merge two siblings into a single node under condition, if the deleted node has _______ [09M01] 1. 2. 3. 4. leaf node root extra element no extra element

2. Deletion of an element from a B-tree from a leaf that containing more than the minimum number of elements requires__________ [09M02] 1. 2. 3. 4. modifying left sibling modifying parent simple deletion of element modifying right sibling

3. The height of B-tree of order m containing n nodes is close to _______ [09M03] 1. 2. 3. 4. m log n log m(n+1) log n log n(m+1)

41 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

4. The height of B-tree of order m containing n nodes is close to _______ [09M04] 1. 2. 3. 4. m log n log m(n+1) log n log n(m+1)

5. In B-tree of order m, the root has ______ child nodes. [09S01] 1. 2. 3. 4. m/2 at least 2 m Zero

6. In ______ trees search node may contain more than one key. [09S02] 1. 2. 3. 4. Splay tree AVL tree B tree Binary tree

7. Which of the following is true regarding a B-tree of order 2? [09S03] 1. 2. 3. 4. No internal node has more than two children All external nodes are at level 3 All internal nodes have exactly 3 children All internal nodes are at same level

8. A B-tree of order 3 is also known as ______ [09S04] 1. 2. 3. 4. splay tree binary tree 2-3 tree 3-4 tree

42 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

10
AVL Tree

Name of the Experiment: 1.AIM:

Write a C++ program to perform the following operations Insertion into an AVL-tree 2.Theory:
In computer science, an AVL tree is a self-balancing binary search tree, and it was the first such data structure to be invented.[1] In an AVL tree, the heights of the two child subtrees of any node differ by at most one; therefore, it is also said to be heightbalanced. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. The AVL tree is named after its two inventors, G.M. Adelson-Velskii and E.M. Landis, who published it in their 1962 paper "An algorithm for the organization of information."[2] The balance factor of a node is the height of its left subtree minus the height of its right subtree (sometimes opposite) and a node with balance factor 1, 0, or 1 is considered balanced. A node with any other balance factor is considered unbalanced and requires rebalancing the tree. The balance factor is either stored directly at each node or computed from the heights of the subtrees. AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. AVL trees perform better than red-black trees for lookup-intensive applications.[3] The AVL tree balancing algorithm appears in many computer science curricula.

3. Algorithm:
A1. [Initialize.] Set N ROOT(T), P Q . A2. [Find insertion point.] If N = , go to step A3. If K = KEY(N), the key is already in the tree and the algorithm terminates with an error. Set P N; if BAL(P) 6= 0, set Q P. If K < KEY(N), then set N LLINK(N), otherwise set N RLINK(N). Repeat this step. A3. [Insert.] Set N AVAIL. If N = , the algorithm terminates with an out of memory error. Set KEY(N) K, LLINK(N) RLINK(N) , PARENT(N) P, and BAL(N) 0. If P = , set ROOT(T) N, and go to step A8. If K < KEY(P), set LLINK(P) N; otherwise, set RLINK(P) N.

43 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

A4. [Adjust balance factors.] If P = Q, go to step A5. If LLINK(P) = N, set BAL(P) 1; otherwise, set BAL(P) +1. Then set N P, and P PARENT(P), and repeat this step. A5. [Check for imbalance.] If Q = , go to step A8. Otherwise: i. If LLINK(Q) = N, set BAL(Q) BAL(Q) 1. If BAL(Q) = 2, go to step A6, otherwise, go to step A8. ii. If RLINK(Q) = N, set BAL(Q) BAL(Q) + 1. If BAL(Q) = +2, go to step A7, otherwise, go to step A8. A6. [Left imbalance.] If BAL(LLINK(Q)) > 0, rotate LLINK(Q) left. Rotate Q right. Go to step A8. A7. [Right imbalance.] If BAL(RLINK(Q)) < 0, rotate RLINK(Q) right. Rotate Q left. Go to step A8. A8. [All done.] The algorithm terminates successfully.

4. Input Insert(10), Insert(20), Insert(30),Display() 5. Output 10 20 30

6.Inference:
Self Balanced Binary Tree.

7.Applications:
To Implement a Right and Left Sub tree balanced

8.Extension:
Implement a leveled binary tree.

9.Viva Voice Questions:


1. In B-tree of order m, all external nodes ______ [09S05] 1. 2. 3. 4. are at different level are at same level have 1 child node have 2 child nodes

2. An m-way search tree of height h may have as many as ____elements. [10D01] 1. m+1 2. mh-1
44 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

3. m*h-1 4. m 3. A 200-way search tree of height 5 has _______ elements. [10D02] 1. 2. 3. 4. 32*1010 32*109 32*1010 -1 32 * 10

4. In B-trees, when an insertion causes s nodes to split, the number if disk accesses needed for an insertion is________ [10M01] 1. 2. 3. 4. h+2s+1 h+2s h-2s h*2s

5. An m-way search tree of height h may have as many as ____elements. [10M02] 1. 2. 3. 4. m+1 mh-1 m*h-1 m

6. In a m-way search tree every node with p elements has exactly _____ children. [10S01] 1. 2. 3. 4. p p-1 p+1 zero

7. In Deletion from a B-tree, if the element to be deleted from a nonleaf is transformed to deleting from a leaf by replacing the deleted element with the largest element in its ______ sub tree. [10S02] 1. 2. 3. 4. left neighboring right neighboring left right

8. In Deletion from a B-tree, if the element to be deleted from a nonleaf is transformed to deleting from a leaf by replacing the deleted element with the smallest element in its ______ sub tree [10S03] 1. 2. 3. 4. left neighboring right neighboring left right

9. The worst case disk access count of a B-tree is of height h is ______ [10S04]
45 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. 2. 3. 4.

3h 3h+1 3h -1 3h +n

10. If T(n)=nlog27[T(1) + O(1) , then the order of T(n) is _________ [11D01] 1. 2. 3. 4. O(nlog27) (nlog27) (nlog27) 0(nlog27)

46 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

11
Dictionary

Name of the Experiment: 1.AIM:

Write a C++ program to implement all the functions of a dictionary (ADT) using hashing. 2.Theory:

Dictionary ADT
Dictionary (map, association list) is a data structure, which is generally an association of unique keys with some values. One may bind a value to a key, delete a key (and naturally an associated value) and lookup for a value by the key. Values are not required to be unique. Simple usage example is an explanatory dictionary. In the example, words are keys and explanations are values.

Dictionary ADT
Operations

Dictionary create() creates empty dictionary boolean isEmpty(Dictionary d) tells whether the dictionary d is empty put(Dictionary d, Key k, Value v) associates key k with a value v; if key k already presents in the dictionary old value is replaced by v Value get(Dictionary d, Key k) returns a value, associated with key k or null, if dictionary contains no such key remove(Dictionary d, Key k) removes key k and associated value destroy(Dictionary d) destroys dictionary d

3.Algorithm:
47 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Hash table
Hash table (or hash map) is one of the possible implementions of dictionary ADT. Hence, basically it maps unique keys to associated values. In the view of implementation, hash table is an array-based data structure, which uses hash function to convert the key into the index of an array element, where associated value is to be sought.

Hash function
Hash function is very important part of hash table design. Hash function is considered to be good, if it provides uniform distribution of hash values. Other hash function's properties, required for quality hashing will be examined in detail later. The reason, why hash function is a subject to the principal concern, is that poor hash functions cause collisions and some other unwanted effects, which badly affect hash table overall performance.

Hash table and load factor


Basic underlying data strucutre used to store hash table is an array. The load factor is the ratio between the number of stored items and array's size. Hash table can whether be of a constant size or being dynamically resized, when load factor exceeds some threshold. Resizing is done before the table becomes full to keep the number of collisions under certain amount and prevent performance degradation.

Collisions
What happens, if hash function returns the same hash value for different keys? It yields an effect, called collision. Collisions are practically unavoidable and should be considered when one implements hash table. Due to collisions, keys are also stored in the table, so one can distinguish between key-value pairs having the same hash. There are various ways of collision resolution. Basically, there are two different strategies:

Closed addressing (open hashing). Each slot of the hash table contains a link to another data structure (i.e. linked list), which stores keyvalue pairs with the same hash. When collision occures, this data structure is searched for key-value pair, which matches the key. Open addressing (closed hashing). Each slot actually contains a keyvalue pair. When collision occurs, open addressing algorithm calculates another location (i.e. next one) to locate a free slot. Hash tables, based on open addressing strategy experience drastic performance decrease, when table is tightly filled (load factor is 0.7 or more)

4.Input
Enter the elements to be inserted:10 4 5 8 7 12 6 1

5.Output
Enter the element to be searched:12 Search key is found!!
48 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

6.Inference:
Explanatory dictionary.

7.Applications:
To Implement a Data Dictionary

8.Extension:
Implement a English Dictionary based on Alphabet

9.Viva Voice Questions:


1. The complexity of many divide and conquer algorithms is given by the recurrences of the form ________ [11S04] 1. 2. 3. 4. T(n)=T(1) for n>1 and T(n)=aT(n/b) + f(n) for n=1 T(n)=T(1) for n=1 and T(n)=aT(n/b) + f(n) for n>1 T(n)=T(1) for n=1 and T(n)=aT(n*b) + f(n) for n>1 T(n)=T(1) for n>1 and T(n)=aT(n*b) + f(n) for n=1

2. Which of the following is not a property of Divide and conquer strategy? [11S05] 1. 2. 3. 4. Dividing the problem in to small sub problems Combining the sub problems by recursive applications Reapplying the DAndC procedures to these subproblems Combining the sub solutions will never result the solution

3. Quick sort is run on two inputs as shown below to sort in ascending order (i) 1,2,3,&,n (ii) n,n-1,n-2,n-3,&,2,1 Let C1 and C2 be the number of comparisons made for the inputs (i) and (ii) respectively. Then, _____ [12D01] 1. 2. 3. 4. C1<C2 C1>C2 C1=C2 We cannot say anything for arbitrary n

4. The average number of comparisons for a quick sort on an average case is _________ [12M01] 1. 2. 3. 4. n(n+1)/2 (n+1)/2 n/2 2n(n+1)

5. The worst-case behavior of quick sort algorithm is one if _________ [12M02] 1. the elements are in random order 2. the elements are distributed evenly
49 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

3. the elements are in sorted order 4. the elements are not in sorted order

50 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Experiment No:

12
Knuth-Morris- Pratt

Name of the Experiment: 1.AIM:

Write a C++ program for implementing KnuthMorris- Pratt pattern matching algorithm. 2.Theory:
The KnuthMorrisPratt string searching algorithm (or KMP algorithm) searches for occurrences of a "word" W within a main "text string" S by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin, thus bypassing re-examination of previously matched characters.

3.Algorithm:
algorithm kmp_search: input: an array of characters, S (the text to be searched) an array of characters, W (the word sought) output: an integer (the zero-based position in S at which W is found) define an an an variables: integer, m 0 (the beginning of the current match in S) integer, i 0 (the position of the current character in W) array of integers, T (the table, computed elsewhere)

while m + i is less than the length of S, do: if W[i] = S[m + i], let i i + 1 if i equals the length of W, return m otherwise, let m m + i - T[i], if T[i] is greater than -1, let i T[i] else let i 0 (if we reach here, we have searched all of S unsuccessfully) return the length of S

4. Input Enter the String: ABCCDE 5. Output Search: BCE Match Found
51 | P a g e

HYDERABAD INSTITUTE OF TECHNOLOGY AND MANAGEMENT

6.Inference:
Matching based on Character.

7.Applications:
To Implement a match in string.

8.Extension:
Implement a pattern matching application in Image Data.

9. Viva Voice Questions:


1. Which of the following is not associated with the implementation of Quick sort? [12M03] 1. 2. 3. 4. Division of the array of elements in to two sub arrays Merging the sorted sub arrays Rearranging the elements Reordering other elements

2. Which of the following algorithm design technique is used in the quick sort algorithm? [12S01] 1. Dynamic Programming 2. Backtracking Greedy Method 3. Divide and conquer 3. The average-case time complexity of Quick sort algorithm on n elements is _________ [12S02] 1. O(n log n) 2. O(log n) 3. O(n) 4. (n2) 4. The best-case time complexity of Quick sort algorithm on n elements is _________ [12S03] 1. O(n log n) 2. O(log n) 3. O(log n) 4. O(n2)

52 | P a g e

Anda mungkin juga menyukai