SlideShare uma empresa Scribd logo
1 de 50
Baixar para ler offline
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 1 -
CONTENTS
Sr. No. Name of the Experiment Page No.
1 C Programming Concepts 2
2 Array Implementation of Stack and Queue 4
3
Insertion, deletion operations with Singly linked lists, Reversing a
singly linked list.
8
4 Insertion, deletion operations Doubly linked lists 10
5 Insertion, deletion operations Circular linked lists. 12
6 Linked List implementation of Stack and Queue 13
7
Implementation of operations (insertion, deletion, counting of nodes,
counting of leaf nodes etc.) in a binary search tree
16
8
Implementation of insertion, deletion and traversal for fully in-threaded
binary search tree
19
9 Implementation of AVL tree 21
10 Implementation of operations in a B tree 26
11
Implementation of adjacency matrix creation, Implementation of
addition and deletion of edges in a directed graph using adjacency
matrix.
28
12
Implementation of insertion and deletion of vertices and edges in a
directed graph using adjacency list.
30
13 Implementation of Heap Sort 31
14 Implementation of Binary Search. 33
15
Implementation of Selection sort
Implementation of Bubble sort
Implementation of Insertion sort
Implementation of Quick sort
36
16
Implementation of infix to postfix conversion and evaluation of postfix
expression
42
17 Implementation of Josephus Problem using circular linked list 44
18
1. Implementation of traversal of a directed graph through BFS
2. Implementation of traversal of a directed graph through DFS
45
19 Implementation of finding shortest distances using Dijkstra’s algorithm 47
20
Implementation of hashing functions with different collision
resolution techniques
1. Linear Probing
2. Quadratic Probing
3. Double Hashing
49
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 2 -
Experiment No. 1
Name of the Experiment: C Programming Concepts.
Aim: Exploring the concepts of Structure and Pointer in C Language
1. Consider any real world entity as a Structure.
2. Write Minimum 4 attributes, Input Method and Display Method.
3. Pass pointer to Structure as parameter to both the methods.
4. Create an array of 5 objects for the defined structure and invoke Input and Display
method.
5. Modify the code to illustrate Nested Structures
6. Modify the code to illustrate Self Referential Structures
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
A structure can be defined as a single entity holding variables of different data types that are
logically related to each other. ‘struct’ keyword is used to create a Structure. There are two
types of operators used for accessing members of a structure.
1. . Member operator
2. → Structure pointer operator
A structure can be passed as a function argument in the same way as you pass any other
variable or pointer. Pointer to structure can be created and the address of a structure variable
in can be stored in it.
When a structure variable is passed by its value, a copy of the members is passed to the
function. If the function modifies any member, then the changes do not affect the structure
variable’s copy of members. When a structure variable is passed by its reference, the address
of the structure variable is passed to the function. This means the function does not get any
copy, instead, it gets the reference or address of the structure variable’s members.
Nested structures are structures within a structure
Array of structures is just like an array of simple data types stored at consecutive memory
locations.
Sample Input and Output:
Enter the total no of Books: 2
Book 1
Enter ISBN:
Enter Title:
Enter Author:
Enter Price:
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 3 -
Enter No. of Pages:
Book 2
Enter ISBN:
Enter Title:
Enter Author:
Enter Price:
Enter No. of Pages:
SrNo ISBN Title Author Price NoPages
1 678 DSA Tan 315 500
2 456 DBMS Kor 654 700
***************************
Enter the total no of Persons: 1
Person 1
Enter ID:
Enter Name
First Name:
Middle Name:
Last Name:
Enter Address
Flat No:
Building:
Street:
City:
Enter Age:
ID First Middle Last Flat Bldg Street City Age
1 aa bb cc 6 dd 7 yy 19
Conclusion:
Structures are used to group different characteristics of an entity into a group. All the
members of a group are stored at consecutive memory locations. Database like structures can
be created using the concept of Structures.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 4 -
Experiment No. 2
Name of the Experiment: Array Implementation of Stack and Queue
Aim: Write a program in C to create a stack of elements of any type. It should support all
the basic operations. Write a Main program to implement the stack operations.
Write a program in C to create a queue of elements of any type. It should support all
the basic operations. Write a Main program to implement the queue operations.
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
A stack is called a "last in, first out," or LIFO data structure, because the last item added is
the first to be removed.
A stack can have any abstract data type as an element, but is characterized by only two
fundamental operations: push and pop.
The push operation adds to the top of the list, hiding any items already on the stack, or
initializing the stack if it is empty.
The pop operation removes an item from the top of the list, and returns this value to the
caller. A pop either reveals previously concealed items, or results in an empty list.
A stack is a restricted data structure, because only a small number of operations are
performed on it. The nature of the pop and push operations also means that stack elements
have a natural order. Elements are removed from the stack in the reverse order to the order of
their addition: therefore, the lower elements are typically those that have been in the list the
longest. When implemented Stack perform following operations
push(element), element pop(), element peek(),
display(), boolean isEmpty(), boolean isFull()
Stack using array
Push(10) Push(20) Push(30), Push(40), Push(50) Pop(), Pop()
top=-1 top=0 top=1 top=4 top=2
9
…
4
3
2
1
0
9
…
4
3
2
1
0 10
9
…
4
3
2
1 20
0 10
9
…
4 50
3 40
2 30
1 20
0 10
9
…
4
3
2 30
1 20
0 10
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 5 -
A queue is a particular kind of collection in which the entities in the collection are kept in
order and the principal (or only) operations on the collection are the addition of entities to the
rear terminal position and removal of entities from the front terminal position. This makes
the queue a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first
element added to the queue will be the first one to be removed. This is equivalent to the
requirement that whenever an element is added, all elements that were added before have to
be removed before the new element can be invoked. A queue is an example of a linear data
structure.
Queue operations
1. enqueue - insert item at the back of queue Q
2. dequeue - return (and virtually remove) the front item from queue Q
Given Q=(a[1],a[2],….a[n]) when viewed as a queue with a[n] as the rear element one says
that a[i+1] is behind a[i], 1<i<=n. the restrictions on a queue imply that if the elements,
A,B,C,D,E are added to the queue, then the first element which is inserted into the queue will
be the first one to be removed. Thus A is the first letter to be removed, and queues are
known as First In First Out (FIFO) lists.
Circular Queue:
In case of a ordinary queue the insertion take place from the front end and the deletion take
place from the rear end. In the case of deletion from the front end data is deleted but the
space of the queue is not utilized for the further storage. So this problem is solved in case of a
circular queue. Even if the rear is full but there is space at the front end then the data can be
stored in the front end until the queue overflows.
As the name suggests, this Queue is not straight but circular; meaning, you got to have a
structure like this -
A circular queue is one in which the insertion of a new element is done at the very first
location of the queue if last location of the queue is full. In other words if we have queue Q
of say n elements, then after an inserting an element last (i.e. in the n-1th) location of the
array the next element will be inserted at the very first location( i.e. location with subscript 0)
of the array. It is possible to insert new elements, if and only if those locations (slots) are
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 6 -
empty. We can say that a circular queue is one in which the first element comes just after the
last elements. It can be viewed as a mesh or loop of wire, in which the ends of the wire are
connected together. A circular queue overcomes the problem of unutilized space in linear
queues implemented as arrays. A circular queue also have a front and rear to keep the track
of the elements to be deleted and inserted and therefore to maintain the unique characteristics
of the queue.
Sample Input and Output:
**************Stack Operations*****************
Menu:
1. Push
2. Pop
3. Display
Option: 1
Enter Number: 10
Stack: 10
Option: 1
Enter Number: 20
Stack: 10 20
Option: 1
Enter Number: 30
Stack: 10 20 30
Option: 1
Enter Number: 40
Stack: 10 20 30 40
Option: 2
Stack: 10 20 30
Option: 2
Stack: 10 20
**************Queue Operations*****************
Menu:
1. Enqueue
2. Dequeue
3. Display
Option: 1
Enter Number: 10
Queue: 10
Option: 1
Enter Number: 20
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 7 -
Queue: 10 20
Option: 1
Enter Number: 30
Queue: 10 20 30
Option: 1
Enter Number: 40
Queue: 10 20 30 40
Option: 2
Queue: 20 30 40
Option: 2
Queue: 30 40
Conclusion:
The stack is a Data Structure where insertions and deletions are possible only at one end.
Stack is used in following applications
1. During execution of nested function calls for storing context of a function
2. Evaluation of postfix expression
3. Conversion from infix to postfix and infix to prefix.
The queue is a Data Structure where insertions and deletions take place at opposite ends.
Queue is mostly used in scheduling applications.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 8 -
Experiment No. 3
Name of the Experiment: Insertion, deletion operations with Singly linked lists, Reversing a
singly linked list
Aim : Implement linked list and perform insertion and deletion operations.
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
Linked list are special list of some data elements linked to one another. The logical ordering
is represented by having each element pointing to the next element. Each element is called a
node, which has two parts: INFO part which stores the information and POINTER which
points to the next element.
A linked list whose nodes contain two fields: an integer value and a link to the next node
A singly linked list is a dynamic structure. It may grow or shrink. Growing or shrinking
depends on the operation made. In singly linked list we have one pointer (next) pointing to
the next node. Linked lists are among the simplest and most common data structures; they
provide an easy implementation for several important abstract data structures, including
stacks, queues, associative arrays, and symbolic expressions. The principal benefit of a linked
list over a conventional array is that the order of the linked items may be different from the
order that the data items are stored in memory or on disk. For that reason, linked lists allow
insertion and removal of nodes at any point in the list, with a constant number of operations
Reversing a singly linked list
Head or the first node of the Linked List (which is 4 in our case)
4 -> 6 -> 7 -> 1 -> 5 - > 8 -> 3 -> 2 -> NULL
There are two approaches to solve the problem. These two approaches are:
1. Iterative Approach
2. Recursive Approach
The following are some steps involved in the iterative approach.
Step 1: Take three-pointers (previous, current, and next), and initialize them as the
following.
previous = NULL, current = head, next = NULL.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 9 -
Step 2: Iterating through the linked list using a loop, and do following.
next = current -> next
current -> next = previous
previous = current
current = next
Reverse a LinkedList Using Recursive Approach
The following are some steps involved in the recursive approach.
Step 1: Split the list given into two parts - the first node and the rest of the linked list.
Step 2: Invoke the reverseList() method for the remaining portion of the linked list.
Step 3: Join the rest to the first.
Step 4: Fix the head pointer.
Sample Input and Output:
Implement all the following operations
1. Insert node at the Beginning
2. Insert node at the End
3. Insert at specific position
4. Add Before a particular node
5. Add After a particular node
6. Delete the first node
7. Delete the last node
8. Delete node at specific position
9. Delete Before a particular node
10. Delete After a particular node
11. Reverse the Linked List
Default: Display
Conclusion:
Advantage of linked list over an array is, it’s dynamic implementation a which makes
effective utilization of memory.
Insertions and deletion of nodes in linked list requires manipulation of few pointers while in
case of arrays there is cost of shifting the elements down for insertions and up for deletions.
But accessing an element in linked list requires traversing the whole list starting from the
first node, while accessing elements from an array is easier.
In singly linked list, one can not traverse backwards, so doubly linked list can be used which
uses two pointers, one points to the next node and the other one points to the previous node.
Linked lists are very useful in polynomial evaluation.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 10 -
Experiment No. 4
Name of the Experiment: Insertion, deletion operations with Doubly linked lists
Aim : Implement Doubly linked list and perform insertion and deletion operations.
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer,
together with next pointer and data which are there in singly linked list. 1) A DLL can be
traversed in both forward and backward direction. 2) The delete operation in DLL is more
efficient if pointer to the node to be deleted is given. 3) We can quickly insert a new node
before a given node. In singly linked list, to delete a node, pointer to the previous node is
needed. To get this previous node, sometimes the list is traversed. In DLL, we can get the
previous node using previous pointer.
Sample Input and Output:
Implement all the following operations
1. Insert node at the Beginning
2. Insert node at the End
3. Insert at specific position
4. Add Before a particular node
5. Add After a particular node
6. Delete the first node
7. Delete the last node
8. Delete node at specific position
9. Delete Before a particular node
10. Delete After a particular node
Default: Display
Conclusion:
The insertion operations that do not require traversal have the time complexity of O(1). And,
insertion that requires traversal has time complexity of O(n) The space complexity is O(1).
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 11 -
Applications of DLL are in Redo and undo functionality in software, Forward and backward
navigation in browsers, For navigation systems where forward and backward navigation is
required.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 12 -
Experiment No. 5
Name of the Experiment: Insertion, deletion operations with Circular linked lists
Aim : Implement Circular linked list and perform insertion and deletion operations.
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
Circular linked list is a linked list where all nodes are connected to form a circle. There is no
NULL at the end. A circular linked list can be a singly circular linked list or a doubly circular
linked list.
Circular Singly Linked Lists, where each node has 2 pointers, Next and Back to points to
Next and the previous Node respectively, plus the next of last points to first Node(and vice
versa), forming a Circle. Such a data structure is known as a circular doubly linked list.
Sample Input and Output:
Implement all the following operations
1. Insert node at the Beginning
2. Insert node at the End
3. Delete the first node
4. Delete the last node
Default: Display
Conclusion:
Circular Singly Linked Lists: where we can only transverse in one direction, while
maintaining the circular property. Circular Doubly Linked Lists: where we can transverse in
both directions, while also maintaining the circular property.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 13 -
Experiment No. 6
Name of the Experiment: Linked List implementation of Stack and Queue
Aim: Write a program in java to create a stack using linked list. It should support all the
basic operations. Write a Main program to implement the stack operations.
Write a program in java to create a queue using linked list. It should support all the
basic operations. Write a Main program to implement the queue operations.
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
A stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have
any abstract data type as an element, but is characterized by only two fundamental
operations: push and pop.
The linked-list implementation is equally simple and straightforward. It requires that we
implement a linked-list where only the head node or element can be removed, or popped, and
a node can only be inserted by becoming the new head node.
The push() operation adds a new node to a stack. It can be implemented using either
insert_beginning or insert_end operation on singly linked list.
A pop() operation removes the node from the stack. It can be implemented using either
delete_beginning or delete_end operation on singly linked list.
A queue is a first in, first out (FIFO) abstract data type and data structure. A queue can have
any abstract data type as an element, but is characterized by only two fundamental
operations: enqueue and dequeue.
The linked-list implementation is equally simple and straightforward. It requires that we
implement a linked-list where only the front node or element can be removed, or dequeued,
and a node can only be inserted by becoming the new rear node.
The enqueue() operation adds a new node in the queue. It can be implemented using either
insert_beginning or insert_end operation on singly linked list.
top
6
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 14 -
A dequeue() operation removes the node from the queue. It can be implemented using
either delete_end or delete_beginning operation on singly linked list.
front rear
null
Sample Input and Output:
Menu:
1. Push
2. Pop
3. Display
Option: 1
Enter Number: 10
Stack: 10
Option: 1
Enter Number: 20
Stack: 10 20
Option: 1
Enter Number: 30
Stack: 10 20 30
Option: 1
Enter Number: 40
Stack: 10 20 30 40
Option: 2
Stack: 10 20 30
Option: 2
Stack: 10 20
Menu:
1. Enqueue
2. Dequeue
3. Display
Option: 1
Enter Number: 10
Queue: 10
Option: 1
Enter Number: 20
Queue: 10 20
Option: 1
10 20 30 40
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 15 -
Enter Number: 30
Queue: 10 20 30
Option: 1
Enter Number: 40
Queue: 10 20 30 40
Option: 2
Queue: 20 30 40
Option: 2
Queue: 30 40
Conclusion:
Use of linked list overcomes the problem of limited static space allotted and stack
overflow. Use of linked list overcomes the problem of limited static space allotted
and queue overflow.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 16 -
Experiment No. 7
Name of the Experiment: Binary Search Tree
Aim: Implementation of operations (insertion, deletion, counting of nodes, counting of leaf nodes
etc.) in a binary search tree.
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
A binary tree is a tree data structure in which each node has at most two child nodes, usually
distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes
may contain references to their parents. Outside the tree, there is often a reference to the
"root" node (the ancestor of all nodes), if it exists. Any node in the data structure can be
reached by starting at root node and repeatedly following references to either the left or right
child. Binary trees are commonly used to implement binary search trees and binary heaps. A
binary search tree is a non linear data structure in which items are arranged in a sorted
sequence. It is used to represent hierarchical relationship existing among several data items.
It can be traversed using Inorder(LVR), Preorder(VLR) and Postorder(LRV) techniques.
A Binary Search Tree (BST) is a data structure such that elements are stored in tree nodes.
Each tree node has a reference to its parent, left child, and right child. Each node in a BST
also has a key associated with it. The Binary Search Tree Property is such that:
1. All keys in a node’s left-subtree are less than that node’s key
2. All keys in a node’s right-subtree are greater than that node’s key
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 17 -
Insert Node into the BST always insert new node as leaf node
1. Start at root node as current node
2. If new node’s key < current’s key
1. If current node has a left child, search left
2. Else add new node as current’s left child
4. If new node’s key > current’s key
1. If current node has a right child, search right
2. Else add new node as current’s right child
Find a Node into the BST
• Use the search key to direct a recursive binary search for a matching node
1. Start at the root node as current node
2. If the search key’s value matches the current node’s key then found a match
3. If search key’s value is greater than current node’s 1. If the current node has a right child,
search right 2. Else, no matching node in the tree
4. If search key is less than the current node’s 1. If the current node has a left child, search
left 2. Else, no matching node in the tree
Deletion in BST
• Basic idea: find the node to be removed, then “fix” the tree so that it is still a binary search
tree
• Three potential cases to fix: – Node has no children (leaf) – Node has one child – Node has
two children
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 18 -
Sample Input and Output:
Enter a set of Node: A B D C E G F H I
Inorder: BDAGECHFI
Postorder: DBGEHIFCA
Enter Node to be deleted: D
Inorder: BAGECHFI
Postorder: BGEHIFCA
Enter Node to be deleted: E
Inorder: BAGCHFI
Postorder: BGHIFCA
Enter Node to be deleted: C
Inorder: BAGHFI
Postorder: BGIFHA
Conclusion: Complexity of Building a Binary Search Tree • Worst case: O(n2) • Best case:
O(n log n).
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 19 -
Experiment No. 8
Name of the Experiment: Fully in-threaded binary search tree
Aim: Implementation of insertion, deletion and traversal for fully in-threaded binary search tree
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
In the linked representation of binary trees, more than one half of the link fields contain
NULL values which results in wastage of storage space. If a binary tree consists of n nodes
then n+1 link fields contain NULL values. So in order to effectively manage the space, a
method was devised by Perlis and Thornton in which the NULL links are replaced with
special links known as threads. Such binary trees with threads are known as threaded binary
trees. Each node in a threaded binary tree either contains a link to its child node or thread to
other nodes in the tree. In one-way threaded binary trees, a thread will appear either in the
right or left link field of a node. If it appears in the right link field of a node then it will point
to the next node that will appear on performing in order traversal. Such trees are called Right
threaded binary trees. If thread appears in the left field of a node then it will point to the
nodes inorder predecessor. Such trees are called Left threaded binary trees. Left threaded
binary trees are used less often as they don't yield the last advantages of right threaded binary
trees. In one-way threaded binary trees, the right link field of last node and left link field of
first node contain a NULL. In order to distinguish threads from normal links they are
represented by dotted lines. In two-way threaded Binary trees, the right link field of a node
containing NULL values is replaced by a thread that points to nodes inorder successor and
left field of a node containing NULL values is replaced by a thread that points to nodes
inorder predecessor.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 20 -
Sample Input and Output:
Enter a set of Node: A B D C E G F H I
Inorder: BDAGECHFI
Postorder: DBGEHIFCA
Enter Node to be deleted: D
Inorder: BAGECHFI
Postorder: BGEHIFCA
Enter Node to be deleted: E
Inorder: BAGCHFI
Postorder: BGHIFCA
Enter Node to be deleted: C
Inorder: BAGHFI
Postorder: BGIFHA
Conclusion:
Time complexity – O(h), where h is the height of the threaded binary search tree. The height
of the tree can be ‘n’ in the worst case and all the keys are inserted in ascending or
descending order(Skewed Tree) where all the nodes except the leaf have only one child and
we may have to travel from to root to the deepest leaf node Space complexity – O(1)
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 21 -
Experiment No. 9
Name of the Experiment: AVL Tree
Aim: Implementation of AVL tree
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
AVL Tree can be defined as height balanced binary search tree in which each node is
associated with a balance factor which is calculated by subtracting the height of its right sub-
tree from that of its left sub-tree. Tree is said to be balanced if balance factor of each node is
in between -1 to 1, otherwise, the tree will be unbalanced and need to be balanced. Balance
Factor (k) = height (left(k)) - height (right(k)) If balance factor of any node is 1, it means that
the left sub-tree is one level higher than the right sub-tree. If balance factor of any node is 0,
it means that the left sub-tree and right sub-tree contain equal height. If balance factor of any
node is -1, it means that the left sub-tree is one level lower than the right sub-tree. An AVL
tree is given in the following figure. We can see that, balance factor associated with each
node is in between -1 and +1. therefore, it is an example of AVL tree.
We perform rotation in AVL tree only in case if Balance Factor is other than -1, 0, and 1.
There are basically four types of rotations which are as follows:
L L rotation: Inserted node is in the left subtree of left subtree of A
R R rotation : Inserted node is in the right subtree of right subtree of A
L R rotation : Inserted node is in the right subtree of left subtree of A
R L rotation : Inserted node is in the left subtree of right subtree of A
Where node A is the node whose balance Factor is other than -1, 0, 1.
The first two rotations LL and RR are single rotations and the next two rotations LR and RL
are double rotations. For a tree to be unbalanced, minimum height must be at least 2, Let us
understand each rotation
1. RR Rotation
When BST becomes unbalanced, due to a node is inserted into the right subtree of the right
subtree of A, then we perform RR rotation, RR rotation is an anticlockwise rotation, which is
applied on the edge below a node having balance factor -2
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 22 -
In above example, node A has balance factor -2 because a node C is inserted in the right
subtree of A right subtree. We perform the RR rotation on the edge below A.
2. LL Rotation
When BST becomes unbalanced, due to a node is inserted into the left subtree of the left
subtree of C, then we perform LL rotation, LL rotation is clockwise rotation, which is applied
on the edge below a node having balance factor 2.
In above example, node C has balance factor 2 because a node A is inserted in the left
subtree of C left subtree. We perform the LL rotation on the edge below A.
3. LR Rotation
Double rotations are bit tougher than single rotation which has already explained above. LR
rotation = RR rotation + LL rotation, i.e., first RR rotation is performed on subtree and then
LL rotation is performed on full tree, by full tree we mean the first node from the path of
inserted node whose balance factor is other than -1, 0, or 1.
State Action
A node B has been inserted into the right subtree of A the left subtree
of C, because of which C has become an unbalanced node having
balance factor 2. This case is L R rotation where: Inserted node is in the
right subtree of left subtree of C
As LR rotation = RR + LL rotation, hence RR (anticlockwise) on
subtree rooted at A is performed first. By doing RR rotation, node A,
has become the left subtree of B.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 23 -
After performing RR rotation, node C is still unbalanced, i.e., having
balance factor 2, as inserted node A is in the left of left of C
Now we perform LL clockwise rotation on full tree, i.e. on node C.
node C has now become the right subtree of node B, A is left subtree of
B
Balance factor of each node is now either -1, 0, or 1, i.e. BST is
balanced now.
4. RL Rotation
As already discussed, that double rotations are bit tougher than single rotation which has
already explained above. R L rotation = LL rotation + RR rotation, i.e., first LL rotation is
performed on subtree and then RR rotation is performed on full tree, by full tree we mean the
first node from the path of inserted node whose balance factor is other than -1, 0, or 1.
State Action
A node B has been inserted into the left subtree of C the right subtree
of A, because of which A has become an unbalanced node having
balance factor - 2. This case is RL rotation where: Inserted node is in
the left subtree of right subtree of A
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 24 -
As RL rotation = LL rotation + RR rotation, hence, LL (clockwise) on
subtree rooted at C is performed first. By doing RR rotation,
node C has become the right subtree of B.
After performing LL rotation, node A is still unbalanced, i.e. having
balance factor -2, which is because of the right-subtree of the right-
subtree node A.
Now we perform RR rotation (anticlockwise rotation) on full tree, i.e.
on node A. node C has now become the right subtree of node B, and
node A has become the left subtree of B.
Balance factor of each node is now either -1, 0, or 1, i.e., BST is
balanced now.
Construct AVL Tree for H, I, J, B, A, E, C, F, D, G, K, L
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 25 -
Sample Input and Output:
Enter the elements: 10 20 30 40 50 25
Preorder traversal of the constructed AVL tree is
30 20 10 25 40 50
Conclusion:
AVL tree controls the height of the binary search tree by not letting it to be skewed. The time
taken for all operations in a binary search tree of height h is O(h). However, it can be
extended to O(n) if the BST becomes skewed (i.e. worst case). By limiting this height to log
n, AVL tree imposes an upper bound on each operation to be O(log n) where n is the number
of nodes.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 26 -
Experiment No. 10
Name of the Experiment: B Tree
Aim: Implementation of operations in a B tree.
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
B-tree is a special type of self-balancing search tree in which each node can contain more
than one key and can have more than two children. It is a generalized form of the binary
search tree. It is also known as a height-balanced m-way tree.
1. For each node x, the keys are stored in increasing order.
2. In each node, there is a boolean value x.leaf which is true if x is a leaf.
3. If n is the order of the tree, each internal node can contain at most n - 1 keys along
with a pointer to each child.
4. Each node except root can have at most n children and at least n/2 children.
5. All leaves have the same depth (i.e. height-h of the tree).
6. The root has at least 2 children and contains a minimum of 1 key.
7. If n ≥ 1, then for any n-key B-tree of height h and minimum degree t ≥ 2, h ≥ logt
(n+1)/2.
Insertions are done at the leaf node level.
The following algorithm needs to be followed in order to insert an item into B Tree.
1. Traverse the B Tree in order to find the appropriate leaf node at which the node can
be inserted.
2. If the leaf node contain less than m-1 keys then insert the element in the increasing
order.
3. Else, if the leaf node contains m-1 keys, then follow the following steps.
4. Insert the new element in the increasing order of elements.
5. Split the node into the two nodes at the median.
6. Push the median element upto its parent node.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 27 -
7. If the parent node also contain m-1 number of keys, then split it too by following the
same steps.
Deletion is also performed at the leaf nodes. The node which is to be deleted can either be a
leaf node or an internal node. Following algorithm needs to be followed in order to delete a
node from a B tree.
1. Locate the leaf node.
2. If there are more than m/2 keys in the leaf node then delete the desired key from the
node.
3. If the leaf node doesn't contain m/2 keys then complete the keys by taking the
element from eight or left sibling.
4. If the left sibling contains more than m/2 elements then push its largest element up to
its parent and move the intervening element down to the node where the key is
deleted.
5. If the right sibling contains more than m/2 elements then push its smallest element up
to the parent and move intervening element down to the node where the key is
deleted.
6. If neither of the sibling contain more than m/2 elements then create a new leaf node
by joining two leaf nodes and the intervening element of the parent node.
7. If parent is left with less than m/2 nodes then, apply the above process on the parent
too.
8. If the the node which is to be deleted is an internal node, then replace the node with
its in-order successor or predecessor. Since, successor or predecessor will always be
on the leaf node hence, the process will be similar as the node is being deleted from
the leaf node.
Conclusion:
Worst case Time complexity: Θ(log n), Average case Time complexity: Θ(log n), Best case
Time complexity: Θ(log n), Average case Space complexity: Θ(n), Worst case Space
complexity: Θ(n). B Tree Applications: databases and file systems, to store blocks of data
(secondary storage media), multilevel indexing.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 28 -
Experiment No. 11
Name of the Experiment: Adjacency Matrix Representation of Graph
Aim: Implementation of adjacency matrix creation, Implementation of addition and deletion
of edges in a directed graph using adjacency matrix.
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
An adjacency matrix is a way of representing a graph as a matrix of booleans (0's and 1's). A
finite graph can be represented in the form of a square matrix on a computer, where the
boolean value of the matrix indicates if there is a direct path between two vertices.
Each cell in the above table/matrix is represented as Aij, where i and j are vertices. The value
of Aij is either 1 or 0 depending on whether there is an edge from vertex i to vertex j. If there
is a path from i to j, then the value of Aij is 1 otherwise its 0. For instance, there is a path
from vertex 1 to vertex 2, so A12 is 1 and there is no path from vertex 1 to 3, so A13 is 0. In
case of undirected graphs, the matrix is symmetric about the diagonal because of every edge
(i,j), there is also an edge (j,i).
Sample Input and Output:
Enter Graph Input No. of Nodes: 4
Enter Graph Input No. of Edges: 4
For Edge 1 Enter Starting and Ending Vertex: 0 3
For Edge 2 Enter Starting and Ending Vertex: 0 2
For Edge 3 Enter Starting and Ending Vertex: 0 1
For Edge 4 Enter Starting and Ending Vertex: 1 2
0 1 1 1
1 0 1 0
1 1 0 0
1 0 0 0
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 29 -
Enter Starting and Ending Vertex of Edge to be Deleted: 1 2
0 1 1 1
1 0 0 0
1 0 0 0
1 0 0 0
Conclusion:
The basic operations like adding an edge, removing an edge, and checking whether there is
an edge from vertex i to vertex j are extremely time efficient, constant time operations. If the
graph is dense and the number of edges is large, an adjacency matrix should be the first
choice. Even if the graph and the adjacency matrix is sparse, we can represent it using data
structures for sparse matrices. The biggest advantage, however, comes from the use of
matrices. The recent advances in hardware enable us to perform even expensive matrix
operations on the GPU. By performing operations on the adjacent matrix, we can get
important insights into the nature of the graph and the relationship between its vertices.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 30 -
Experiment No. 12
Name of the Experiment: Adjacency List Representation of Graph
Aim: Implementation of adjacency List creation, Implementation of addition and deletion of
edges in a directed graph using adjacency List.
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
An adjacency list represents a graph as an array of linked lists. The index of the array
represents a vertex and each element in its linked list represents the other vertices that form
an edge with the vertex.
Sample Input and Output:
Enter Graph Input No. of Nodes: 4
Enter Graph Input No. of Edges: 4
For Edge 1 Enter Starting and Ending Vertex: 0 3
For Edge 2 Enter Starting and Ending Vertex: 0 2
For Edge 3 Enter Starting and Ending Vertex: 0 1
For Edge 4 Enter Starting and Ending Vertex: 1 2
0 1 1 1
1 0 1 0
1 1 0 0
1 0 0 0
Enter Starting and Ending Vertex of Edge to be Deleted: 1 2
0 1 1 1
1 0 0 0
1 0 0 0
1 0 0 0
Conclusion:
An adjacency list is efficient in terms of storage because we only need to store the values for
the edges. For a sparse graph with millions of vertices and edges, this can mean a lot of saved
space. It also helps to find all the vertices adjacent to a vertex easily.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 31 -
Experiment No. 13
Name of the Experiment: Implementation of Heap Sort
Aim: Write a java program to accept a set of numbers and sort those using heap sort
techniques and display. (Display the numbers after every iteration)
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
Heapsort is a comparison-based sorting algorithm, Heapsort is an in-place algorithm, but is
not a stable sort. The heap sort works as its name suggests. It begins by building a heap out
of the data set, and then removing the largest item and placing it at the end of the sorted
array. After removing the largest item, it reconstructs the heap, removes the largest remaining
item, and places it in the next open position from the end of the sorted array. This is repeated
until there are no items left in the heap and the sorted array is full.
Algorithm:
Procedure PARENT (i)
return floor(i/2)
Procedure LEFT (i)
return 2i
Procedure RIGHT (i)
return 2i + 1
Procedure Heapify (A, i)
l ← left [i]
r ← right [i]
if l ≤ heap-size [A] and A[l] > A[i]
then largest ← l
else largest ← i
if r ≤ heap-size [A] and A[i] > A[largest]
then largest ← r
if largest ≠ i
then exchange A[i] ↔ A[largest]
Heapify (A, largest)
Procedure BUILD_HEAP (A)
heap-size (A) ← length [A]
For i ← floor(length[A]/2) down to 1 do
Heapify (A, i)
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 32 -
Procedure HEAPSORT (A)
BUILD_HEAP (A)
for i ← length (A) down to 2 do
exchange A[1] ↔ A[i]
heap-size [A] ← heap-size [A] - 1
Heapify (A, 1)
Sample Input and Output:
Enter 8 elements:
25 57 48 37 12 92 86 33
Building a Heap
25 57 48 37 12 92 86 33
25 57 48 37 12 92 86 33
25 57 92 37 12 48 86 33
25 57 92 37 12 48 86 33
92 57 86 37 12 48 25 33
Pass 1: 86 57 48 37 12 33 25 92
Pass 2: 57 37 48 25 12 33 86 92
Pass 3: 48 37 33 25 12 57 86 92
Pass 4: 37 25 33 12 48 57 86 92
Pass 5: 33 25 12 37 48 57 86 92
Pass 6: 25 12 33 37 48 57 86 92
Pass 7: 12 25 33 37 48 57 86 92
Conclusion:
An almost complete binary tree with n vertices has a depth of at most log(n).
Therefore, procedure heapify requires at most log(n) steps. Procedure buildheap calls
heapify for each vertex, therefore it requires at most n·log(n) steps. Heapsort calls
buildheap once; then it calls heapify for each vertex, together it requires at most
2·n·log(n) steps. Thus, the time complexity of heapsort is T(n) O(n·log(n)).
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 33 -
Experiment No.: 14
Name of the Experiment: Implementation of Binary Search.
Aim: Write a program to accept a set of numbers and search a number in a list by using
Linear search and Binary search
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts, Stack, Queue
Theory :
Linear Search:
Linear search or sequential search is a method for finding a particular value in a list, that
consists of checking every one of its elements, one at a time and in sequence, until the
desired one is found. This is a very straightforward loop comparing every element in the
array with the key. As soon as an equal value is found, it returns. If the loop finishes without
finding a match, the search failed and -1 is returned. For small arrays, linear search is a good
solution because it's so straightforward. In an array of a million elements linear search on
average will take 500,000 comparisons to find the key.
Binary Search:
A fast way to search a sorted array is to use a binary search. The idea is to look at the element
in the middle. If the key is equal to that, the search is finished. If the key is less than the
middle element, do a binary search on the first half. If it's greater, do a binary search of the
second half. The advantage of a binary search over a linear search is astounding for large
numbers. There are two common ways to compute the index of the middle element. The most
common way is to add the lowest and highest and divide by two. For example, int mid =
(first + last) + 2; Overflow. This works well, or at least has worked well, until recently. The
problem appeared when memories, and arrays, got very large. For the first time the sum of
two array indexes, an intermediate value in the computation, can overflow the size of an int.
computing the midpoint by adding the two and then dividing doesn't work. Reordering the
expression avoids overflow. The solution is to rewrite the expression so that no intermediate
value overflows the size of an int. This is easy to do using the following. int mid = first +
(last - first) / 2;For most programs the difference between the two computations will never be
seen because it will only appear with very large arrays
Example-. Find 6 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114}.
Step 1 (middle element is 19 > 6): -1 5 6 18 19 25 46 78 102 114
Step 2 (middle element is 5 < 6): -1 5 6 18 19 25 46 78 102 114
Step 3 (middle element is 6 == 6): -1 5 6 18 19 25 46 78 102 114
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 34 -
Algorithm :
1. Algorithm for linear Search: Algorithm for searching an item in the list lsearch(a[])
Let A= array of n elements, item=given item of information, loc=location of item in
A, loc=0 if search is successful.
1. [Initialization counter] set loc=1
2. Search for an item
a. While (data[loc]!=item)
b. Set loc=loc+1
3. [successful] if loc=n+1
a. Then setloc=0
4. Exit/return
2. Algorithm for Binary search: Algorithm for searching an item in the list
bsearch(a[])
Let A= array of n elements, item=given item of information, loc=location of item in
A, low=0 , high=n-1 if search is successful.
1. If(low>high)
i. return
2. mid=(low+high)/2
3. If(x==a[mid])
i. return (mid)
4. if(x<x[mid])
i. search for x in a[low] to a[mid-1]
5. else
i. search for x in a[mid+1] to a[high]
6. return/exit
Sample Input and Output:
********Linear Search**********
Enter the set of 10 Numbers:
12 78 21 56 54 89 32 11 10 69
Linear Search for: 32
Element 32 found at Index 6 with 7 Comparisons
Continue(Y/N): Y
Linear Search for: 99
Element 99 NOT found with 10 Comparisons
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 35 -
********Binary Search**********
Enter the sorted set of 10 Numbers:
10 15 19 25 36 48 57 61 72 88
Binary Search for: 36
Element 36 found at Index 4 with 1 Comparisons
Continue(Y/N): Y
Binary Search for: 19
Element 19 found at Index 2 with 3 Comparisons
Binary Search for: 99
Element 99 NOT found with 4 Comparisons
Conclusion: For an array of a million elements, binary search, O(log N), will find the target
element with a worst case of only 20 comparisons. Linear search, O(N), on average will take
500,000 comparisons to find the element. Probably the only faster kind of search uses
hashing, a topic that isn't covered in these notes. This performance comes at a price - the
array must be sorted first. Because sorting isn't a fast operation, O(N log N), it may not be
worth the effort to sort when there are only a few searches.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 36 -
Experiment No. 15
Name of the Experiment: Implementation of Bubble, Selection, Insertion and Quick
Sort
Aim: Write a java program to accept a set of numbers and sort those using Bubble,
Selection, Insertion and Quick sort techniques and display. (Display the numbers after
every iteration)
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
Bubble Sort
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to
greatest number using bubble sort algorithm. In each step, elements written in bold are being
compared.
First Pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm
does not swap them.
Second Pass:
( 1 4 2 5 8 ) ( 1 4 2 5 8 )
( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
( 1 2 4 5 8 ) ( 1 2 4 5 8 )
Finally, the array is sorted, and the algorithm can terminate.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 37 -
Insertion Sort
The following table shows the steps for sorting the sequence 5 7 0 3 4 2 6 1.For each
iteration, the number of positions the inserted element has moved is shown in brackets.
Altogether this amounts to 17 steps.
5 7 0 3 4 2 6 1 (0)
5 7 0 3 4 2 6 1 (0)
0 5 7 3 4 2 6 1 (2)
0 3 5 7 4 2 6 1 (2)
0 3 4 5 7 2 6 1 (2)
0 2 3 4 5 7 6 1 (4)
0 2 3 4 5 6 7 1 (1)
0 1 2 3 4 5 6 7 (6)
Selection Sort
1. Find the minimum value in the list
2. Swap it with the value in the first position
3. Repeat the steps above for the remainder of the list (starting at the second position and
advancing each time)
For e.g.
64 25 12 22 11
11 25 12 22 64
11 12 25 22 64
11 12 22 25 64
11 12 22 25 64
Quick Sort
Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-lists.
The steps are:
1. Pick an element, called a pivot, from the list.
2. Reorder the list so that all elements which are less than the pivot come before the
pivot and so that all elements greater than the pivot come after it (equal values can go
either way). After this partitioning, the pivot is in its final position. This is called the
partition operation.
3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements.
Algorithm:
procedure bubbleSort( A : list of sortable items )
defined as:
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 38 -
do
swapped := false
for each i in 0 to length(A) - 2 inclusive do:
if A[i] > A[i+1] then
swap( A[i], A[i+1] )
swapped := true
end if
end for
while swapped
end procedure
Algorithm:
procedure insertionSort(array A)
begin
for i := 1 to length[A]-1 do
begin
value := A[i];
j := i - 1;
done := false;
repeat
if A[j] > value then
begin
A[j + 1] := A[j];
j := j - 1;
if j < 0 then
done := true;
end
else
done := true;
until done;
A[j + 1] := value;
end;
end;
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 39 -
Algorithm:
procedure selectionSort(array A)
begin
for i = 0 to length[A] – 2 do
begin
min = i;
for j = i + 1 to length[A]-1 do
begin
if (a[j] < a[min])
begin
min = j;
end
end
if (i != min)
begin
swap = a[i];
a[i] = a[min];
a[min] = swap;
end
end
end
Algorithm:
procedure quicksort(array, left, right)
if right > left
select a pivot index
pivotNewIndex:=partition(array, left, right, pivotIndex)
quicksort(array, left, pivotNewIndex - 1)
quicksort(array, pivotNewIndex + 1, right)
function partition(array, left, right, pivotIndex)
pivotValue := array[pivotIndex]
swap array[pivotIndex] and array[right]
storeIndex := left
for i from left to right - 1
if array[i] < pivotValue
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 40 -
swap array[i] and array[storeIndex]
storeIndex := storeIndex + 1
swap array[storeIndex] and array[right]
return storeIndex
Sample Input and Output:
***********Bubble Sort**************
Enter 8 elements:
25 57 48 37 12 92 86 33
Pass 1: 25 48 37 12 57 86 33 92
Pass 2: 25 37 12 48 57 33 86 92
Pass 3: 25 12 37 48 33 57 86 92
Pass 4: 12 25 37 33 48 57 86 92
Pass 5: 12 25 33 37 48 57 86 92
Pass 6: 12 25 33 37 48 57 86 92
Pass 7: 12 25 33 37 48 57 86 92
***********Insertion Sort**************
Enter 8 elements:
25 57 48 37 12 92 86 33
Pass 1: 25 57 48 37 12 92 86 33
Pass 2: 25 48 57 37 12 92 86 33
Pass 3: 25 37 48 57 12 92 86 33
Pass 4: 12 25 37 48 57 92 86 33
Pass 5: 12 25 37 48 57 92 86 33
Pass 6: 12 25 37 48 57 86 92 33
Pass 7: 12 25 33 37 48 57 86 92
***********Selection Sort**************
Enter 8 elements:
25 57 48 37 12 92 86 33
Pass 1: 25 57 48 37 12 33 86 92
Pass 2: 25 57 48 37 12 33 86 92
Pass 3: 25 33 48 37 12 57 86 92
Pass 4: 25 33 12 37 48 57 86 92
Pass 5: 25 33 12 37 48 57 86 92
Pass 6: 25 12 33 37 48 57 86 92
Pass 7: 12 25 33 37 48 57 86 92
***********Quick Sort**************
Enter 8 elements:
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 41 -
25 57 48 37 12 92 86 33
Pass 1: 12 25 48 37 57 92 86 33
Pass 2: 12 25 33 37 48 92 86 57
Pass 3: 12 25 33 37 48 92 86 57
Pass 4: 12 25 33 37 48 57 86 92
Pass 5: 12 25 33 37 48 57 86 92
Conclusion:
Bubble sort has worst-case and average complexity both О(n²), where n is the number of
items being sorted. However, one significant advantage that bubble sort has over most other
implementations, even QuickSort, is that the ability to detect that the list is sorted is
efficiently built into the algorithm. Performance of bubble sort over an already-sorted list
(best-case) is O(n).
The best case input is an array that is already sorted. In this case insertion sort has a linear
running time (i.e., Θ(n)). During each iteration, the first remaining element of the input is
only compared with the right-most element of the sorted subsection of the array.
The worst case input is an array sorted in reverse order. In this case every iteration of the
inner loop will scan and shift the entire sorted subsection of the array before inserting the
next element. For this case insertion sort has a quadratic running time (i.e., O(n2
)).
The average case is also quadratic, which makes insertion sort impractical for sorting large
arrays. However, insertion sort is one of the fastest algorithms for sorting arrays containing
fewer than ten elements.
Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2)
complexity, making it inefficient on large lists, and generally performs worse than the similar
insertion sort. Selection sort is noted for its simplicity, and also has performance advantages
over more complicated algorithms in certain situations
Quicksort takes Θ(nlogn) time on average. It's not hard to see that the partition operation,
which simply loops over the elements of the array once, uses Θ(n) time. In versions that
perform concatenation, this operation is also Θ(n).
In the best case, each time we perform a partition we divide the list into two nearly equal
pieces. This means each recursive call processes a list of half the size.
Consequently, we can make only logn nested calls before we reach a list of size 1. This
means that the depth of the call tree is Θ(logn). But no two calls at the same level of the call
tree process the same part of the original list; thus, each level of calls needs only Θ(n) time
all together (each call has some constant overhead, but since there are only Θ(n) calls at each
level, this is subsumed in the Θ(n) factor). The result is that the algorithm uses only Θ(nlogn)
time.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 42 -
Experiment No. 16
Name of the Experiment: Implementation of infix to postfix conversion and evaluation of
postfix expression
Aim: Write a C Program to convert Infix Expression to Postfix Expression and Evaluate it.
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts, Stack, Queue
Theory:
Infix: ( ( ( A + B ) * ( C – D ) ) / N )
Prefix: /*+AB –CDN
Postfix: AB+CD-*N/
Evaluation of PostFix Expression
Step 1: If a character is an operand push it to Stack
Step 2: If the character is an operator
Pop two elements from the Stack.
Operate on these elements according to the operator, and push the result back to the
Stack
Step 3: Step 1 and 2 will be repeated until the end has reached.
Step 4: The Result is stored at the top of the Stack,
return it
Step 5: End
For e.g. postexp= “3 4 + 7 3 - * 3 %”
Stack: Empty
Postexp[0]= 3 operand push(3)
Stack: 3
Postexp[1]= 4 operand push(4)
Stack: 3 4
Postexp[2]= + operator b=pop(),a=pop()
c=a+b=3+4=7
push(c)
Stack: 7
Postexp[3]= 7 operand push(7)
Stack: 7 7
Postexp[4]= 3 operand push(3)
Stack: 7 7 3
Postexp[5]= - operator b=pop(),a=pop()
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 43 -
c=a-b=7-3=4
push(c)
Stack: 7 4
Postexp[6]= * operator b=pop(),a=pop()
c=a*b=7*4=28
push(c)
Stack: 28
Postexp[7]= 3 operand push(3)
Stack: 28 3
Postexp[8]= % operator b=pop(),a=pop()
c=a*b=28%3=1
push(c)
Stack: 1
Result=1
Conversion of Infix to Postfix
Step 1: Scan the Infix Expression from left to right.
Step 2: If the scanned character is an operand, append it with final Infix to Postfix string.
Step 3: Else,
Step 3.1: If the precedence order of the scanned (incoming) operator is greater than the
precedence order of the operator in the stack (or the stack is empty or the stack contains a ‘(‘
or ‘[‘ or ‘{‘), push it on stack.
Step 3.2: Else, Pop all the operators from the stack which are greater than or equal to in
precedence than that of the scanned operator. After doing that Push the scanned operator to
the stack. (If you encounter parenthesis while popping then stop there and push the scanned
operator in the stack.)
Step 4: If the scanned character is an ‘(‘ or ‘[‘ or ‘{‘, push it to the stack.
Step 5: If the scanned character is an ‘)’or ‘]’ or ‘}’, pop the stack and output it until a ‘(‘ or
‘[‘ or ‘{‘ respectively is encountered, and discard both the parenthesis.
Step 6: Repeat steps 2-6 until infix expression is scanned.
Step 7: Print the output
Step 8: Pop and output from the stack until it is not empty.
Sample Input and Output:
Enter a infix expression: (3+4)*(7-3)
Postfix expression: 3 4 + 7 3 - *
Result: 28
Conclusion:
Stack can efficiently be used to evaluate post fix expressions.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 44 -
Experiment No. 17
Name of the Experiment: Application of Circular Linked List
Aim: Write Implementation of Josephus Problem using circular linked list
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts, Stack, Queue
Theory:
There are N people standing in a circle numbered from 1 to N. Also given an integer K. First,
count the K-th number starting from the first one and delete it. Then K numbers are counted
starting from the next one and the K-th one is removed again, and so on. The process stops
when one number remains. The task is to find the last number.
For n = 7 and k = 2
Algorithm
1. Create a list containing integers from 1 to N.
2. Create a recursive function which deletes every Kth element from the list in each
iteration in the clockwise direction.
3. Continue repeating the above steps until only one element is left.
Sample Input and Output:
Input: N = 6, K = 2
Output: 5
Conclusion:
Josephus Problem can be used in Random Number generation
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 45 -
Experiment No. 18
Name of the Experiment: Implementation of traversal of a directed graph through BFS and DFS
Aim: Given A connected graph G(V,E), write a program in java to visit all the vertices
using Breadth First Traversal and Depth First Traversal technique. (Use Adjacency
matrix representation for the graph)
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts, Stack, Queue
Theory:
A DFS algorithm, as the name implies, is used to search deeper in the graph, whenever
possible. The edges are explored, out of the most recently discovered vertex v that still has
unexplored edges leaving it. When all of v's edges have been explored, the search backtracks
to explore edges leaving the vertex from which v was discovered. This process continues
until we have discovered all the vertices that are reachable from the source vertex. DFS uses
stack structure to maintain the order in which the vertices are to be processed.
Algorithm:
Step 1: Initialize all nodes to ready state (status = 1)
Step 2: Push the starting node in stack and change its status to the waiting state (status
= 2)
Step 3: Repeat step 4 and 5 until stack is empty
Step 4: pop the top node n of stack. Process n and change the status of n to the
processed state (status = 3)
Step 5: Push on to the stack, all the neighbor of n that are in ready state (status = 1),
and change their status to the waiting state (status = 2) [End of the step 3 loop]
Step 6: exit
In graph theory, breadth-first search (BFS) is a graph search algorithm that begins at the root
node and explores all the neighboring nodes. Then for each of those nearest nodes, it
explores their unexplored neighbor nodes, and so on, until it finds the goal.
BFS uses queue structure to maintain the order in which the vertices are to be processed.
Algorithm:
1. Enqueue the root node.
2. Dequeue a node and examine it.
3. If the element sought is found in this node, quit the search and return a result.
4. Otherwise enqueue any successors (the direct child nodes) that have not yet been
discovered.
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 46 -
5. If the queue is empty, every node on the graph has been examined – quit the search
and return "not found".
6. Repeat from Step 2.
Sample Input and Output:
Enter no. of vertices: 7
Enter no. of edges: 7
Enter Source and Destination for edge 1: A B
Enter Source and Destination for edge 2: A C
Enter Source and Destination for edge 3: A D
Enter Source and Destination for edge 4: B E
Enter Source and Destination for edge 5: B F
Enter Source and Destination for edge 6: C G
Enter Source and Destination for edge 7: D F
Breadth First Traversal: A B C D E F G
Depth First Traversal: A B E F D C G
Conclusion:
DFS(G, v) visits all the vertices and edges in the connected component of v. The discovery
edges labeled by DFS(G, v) form a spanning tree of the connected component of v. The time
and space analysis of DFS differs according to its application area. In theoretical computer
science, DFS is typically used to traverse an entire graph, and takes time O(|V| + |E|), linear
in the size of the graph. In these applications it also uses space O(|V|) in the worst case to
store the stack of vertices on the current search path as well as the set of already-visited
vertices. The time complexity can also be expressed as O( | E | + | V | ) where | E | is the
cardinality of the set of edges (the number of edges), and | V | is the cardinality of the set of
vertices, since every vertex and every edge will be explored in the worst case.
A
B C D
E F G
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 47 -
Experiment No. 19
Name of the Experiment: Dijkstra’s algorithm
Aim: Implementation of finding shortest distances using Dijkstra’s algorithm
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
Dijkstra's algorithm allows us to find the shortest path between any two vertices of a graph.
Dijkstra's Algorithm works on the basis that any subpath B -> D of the shortest path A -> D
between vertices A and D is also the shortest path between vertices B and D. The algorithm
uses a greedy approach in the sense that we find the next best solution hoping that the end
result is the best solution for the whole problem.
function dijkstra(G, S)
for each vertex V in G
distance[V] <- infinite
previous[V] <- NULL
If V != S, add V to Priority Queue Q
distance[S] <- 0
while Q IS NOT EMPTY
U <- Extract MIN from Q
for each unvisited neighbour V of U
tempDistance <- distance[U] + edge_weight(U, V)
if tempDistance < distance[V]
distance[V] <- tempDistance
previous[V] <- U
return distance[], previous[]
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 48 -
Sample Input and Output:
For following Graph
Enter Adjacency Matrix
0 3 1 0 0
3 0 7 5 1
1 7 0 2 0
0 5 2 0 7
0 1 0 7 0
Adjacency Matrix
0 3 1 0 0
3 0 7 5 1
1 7 0 2 0
0 5 2 0 7
0 1 0 7 0
Enter the starting vertex:0
Distance of node1=3
Path=1<-0
Distance of node2=1
Path=2<-0
Distance of node3=3
Path=3<-2<-0
Distance of node4=4
Path=4<-1<-0
Conclusion:
Time Complexity: O(E Log V) where, E is the number of edges and V is the number of
vertices. Space Complexity: O(V)
To find the shortest path, In social networking applications, In a telephone network, To find
the locations in the map
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 49 -
Experiment No. 20
Name of the Experiment: Collision Resolution Techniques
Aim: Implementation of hashing functions with different collision resolution techniques
1. Linear Probing
2. Quadratic Probing
3. Double Hashing
Equipments / Components required: C/C++ Compiler
Pre-requisite: C Programming Concepts
Theory:
Like separate chaining, open addressing is a method for handling collisions. In Open
Addressing, all elements are stored in the hash table itself. So at any point, the size of the
table must be greater than or equal to the total number of keys. This approach is also known
as closed hashing. This entire procedure is based upon probing. We will understand types of
probing ahead.
Open Addressing is done in the following ways:
a) Linear Probing: In linear probing, the hash table is searched sequentially that starts from
the original location of the hash. If in case the location that we get is already occupied, then
we check for the next location. The function used for rehashing is as follows: rehash(key) =
(n+1)%table-size. For example, the typical gap between two probes is 1 as seen in the
example below.
Let hash(x) be the slot index computed using a hash function and S be the table size
If slot hash(x) % S is full, then we try (hash(x) + 1) % S
If (hash(x) + 1) % S is also full, then we try (hash(x) + 2) % S
If (hash(x) + 2) % S is also full, then we try (hash(x) + 3) % S
b) Quadratic Probing If you observe carefully, then you will understand that the interval
between probes will increase proportionally to the hash value. Quadratic probing is a method
with the help of which we can solve the problem of clustering that was discussed above.
This method is also known as mid-square method. In this method we look for i2
‘th slot in i’th
iteration. We always start from the original hash location. If only the location is occupied
then we check the other slots.
Let hash(x) be the slot index computed using hash function.
If slot hash(x) % S is full, then we try (hash(x) + 1*1) % S
If (hash(x) + 1*1) % S is also full, then we try (hash(x) + 2*2) % S
If (hash(x) + 2*2) % S is also full, then we try (hash(x) + 3*3) % S
Laboratory Manual [SEIT Sem. III] Data Structures and Analysis
Information Technology, BVCOE, Navi Mumbai - 50 -
c) Double Hashing The intervals that lie between probes is computed by another hash
function. Double hashing is a technique that reduces clustering in an optimized way. In this
technique, the increments for the probing sequence are computed by using another hash
function. We use another hash function hash2(x) and look for i*hash2(x) slot in i’th rotation.
Let hash(x) be the slot index computed using hash function.
If slot hash(x) % S is full, then we try (hash(x) + 1*hash2(x)) % S
If (hash(x) + 1*hash2(x)) % S is also full, then we try (hash(x) + 2*hash2(x)) % S
If (hash(x) + 2*hash2(x)) % S is also full, then we try (hash(x) + 3*hash2(x)) % S
Sample Input and Output:
Enter the size of the Hash Table: 7
Enter the No. of Keys: 5
Enter the Keys: 16 40 27 9 75
Linear Probing: 75 X 16 9 X 40 27
Enter the size of the Hash Table: 7
Enter the No. of Keys: 3
Enter the Keys: 15 23 85
Quadratic Probing: X 15 23 X X 85 X
Enter the size of the Hash Table: 7
Enter the No. of Keys: 5
Enter the Keys: 37 25 12 40 75
Double Hashing: 47 X 37 40 25 12 X
Conclusion:
Linear probing has the best cache performance but suffers from clustering. One more
advantage of Linear probing is easy to compute. Quadratic probing lies between the two in
terms of cache performance and clustering. Double hashing has poor cache performance but
no clustering. Double hashing requires more computation time as two hash functions need to
be computed.

Mais conteúdo relacionado

Mais procurados

linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structuresDurgaDeviCbit
 
Data Structures with C Linked List
Data Structures with C Linked ListData Structures with C Linked List
Data Structures with C Linked ListReazul Islam
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queueSrajan Shukla
 
List Data Structure
List Data StructureList Data Structure
List Data StructureZidny Nafan
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]Muhammad Hammad Waseem
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked ListsAfaq Mansoor Khan
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked listKeval Bhogayata
 
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHIBCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHISowmya Jyothi
 

Mais procurados (20)

linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
 
Queues in C++
Queues in C++Queues in C++
Queues in C++
 
Data Structures with C Linked List
Data Structures with C Linked ListData Structures with C Linked List
Data Structures with C Linked List
 
Ppt on Linked list,stack,queue
Ppt on Linked list,stack,queuePpt on Linked list,stack,queue
Ppt on Linked list,stack,queue
 
Stack
StackStack
Stack
 
Queue
QueueQueue
Queue
 
Queue
QueueQueue
Queue
 
List Data Structure
List Data StructureList Data Structure
List Data Structure
 
Linked list
Linked listLinked list
Linked list
 
Doubly linked list (animated)
Doubly linked list (animated)Doubly linked list (animated)
Doubly linked list (animated)
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
 
Selection sort algorithm presentation, selection sort example using power point
Selection sort algorithm presentation, selection sort example using power point Selection sort algorithm presentation, selection sort example using power point
Selection sort algorithm presentation, selection sort example using power point
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked list
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
single linked list
single linked listsingle linked list
single linked list
 
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHIBCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Link list
Link listLink list
Link list
 

Semelhante a DSA Lab Manual C Scheme.pdf

chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptxselemonGamo
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queueRai University
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queueRai University
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddumaneesh boddu
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueRai University
 
basics of queues
basics of queuesbasics of queues
basics of queuessirmanohar
 
chapter-4-data-structure.pdf
chapter-4-data-structure.pdfchapter-4-data-structure.pdf
chapter-4-data-structure.pdfstudy material
 
unit 5 stack & queue.ppt
unit 5 stack & queue.pptunit 5 stack & queue.ppt
unit 5 stack & queue.pptSeethaDinesh
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptxskilljiolms
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringRAJASEKHARV8
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbRAtna29
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queuePulkitmodi1998
 
Data Structure
Data Structure Data Structure
Data Structure Ibrahim MH
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Getachew Ganfur
 

Semelhante a DSA Lab Manual C Scheme.pdf (20)

Data structures
Data structuresData structures
Data structures
 
12888239 (2).ppt
12888239 (2).ppt12888239 (2).ppt
12888239 (2).ppt
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptx
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
 
basics of queues
basics of queuesbasics of queues
basics of queues
 
chapter-4-data-structure.pdf
chapter-4-data-structure.pdfchapter-4-data-structure.pdf
chapter-4-data-structure.pdf
 
1.1 ADS data-structure.pdf
1.1 ADS data-structure.pdf1.1 ADS data-structure.pdf
1.1 ADS data-structure.pdf
 
Unit i(dsc++)
Unit i(dsc++)Unit i(dsc++)
Unit i(dsc++)
 
unit 5 stack & queue.ppt
unit 5 stack & queue.pptunit 5 stack & queue.ppt
unit 5 stack & queue.ppt
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbbqueuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
queuesArrays.ppt bbbbbbbbbbbbbbbbbbbbbbbbbb
 
Difference between stack and queue
Difference between stack and queueDifference between stack and queue
Difference between stack and queue
 
Data structures
Data structuresData structures
Data structures
 
Data Structure
Data Structure Data Structure
Data Structure
 
Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9Stacks queues-1220971554378778-9
Stacks queues-1220971554378778-9
 
Rana Junaid Rasheed
Rana Junaid RasheedRana Junaid Rasheed
Rana Junaid Rasheed
 

Último

Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...ranjana rawat
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 

Último (20)

Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 

DSA Lab Manual C Scheme.pdf

  • 1. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 1 - CONTENTS Sr. No. Name of the Experiment Page No. 1 C Programming Concepts 2 2 Array Implementation of Stack and Queue 4 3 Insertion, deletion operations with Singly linked lists, Reversing a singly linked list. 8 4 Insertion, deletion operations Doubly linked lists 10 5 Insertion, deletion operations Circular linked lists. 12 6 Linked List implementation of Stack and Queue 13 7 Implementation of operations (insertion, deletion, counting of nodes, counting of leaf nodes etc.) in a binary search tree 16 8 Implementation of insertion, deletion and traversal for fully in-threaded binary search tree 19 9 Implementation of AVL tree 21 10 Implementation of operations in a B tree 26 11 Implementation of adjacency matrix creation, Implementation of addition and deletion of edges in a directed graph using adjacency matrix. 28 12 Implementation of insertion and deletion of vertices and edges in a directed graph using adjacency list. 30 13 Implementation of Heap Sort 31 14 Implementation of Binary Search. 33 15 Implementation of Selection sort Implementation of Bubble sort Implementation of Insertion sort Implementation of Quick sort 36 16 Implementation of infix to postfix conversion and evaluation of postfix expression 42 17 Implementation of Josephus Problem using circular linked list 44 18 1. Implementation of traversal of a directed graph through BFS 2. Implementation of traversal of a directed graph through DFS 45 19 Implementation of finding shortest distances using Dijkstra’s algorithm 47 20 Implementation of hashing functions with different collision resolution techniques 1. Linear Probing 2. Quadratic Probing 3. Double Hashing 49
  • 2. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 2 - Experiment No. 1 Name of the Experiment: C Programming Concepts. Aim: Exploring the concepts of Structure and Pointer in C Language 1. Consider any real world entity as a Structure. 2. Write Minimum 4 attributes, Input Method and Display Method. 3. Pass pointer to Structure as parameter to both the methods. 4. Create an array of 5 objects for the defined structure and invoke Input and Display method. 5. Modify the code to illustrate Nested Structures 6. Modify the code to illustrate Self Referential Structures Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: A structure can be defined as a single entity holding variables of different data types that are logically related to each other. ‘struct’ keyword is used to create a Structure. There are two types of operators used for accessing members of a structure. 1. . Member operator 2. → Structure pointer operator A structure can be passed as a function argument in the same way as you pass any other variable or pointer. Pointer to structure can be created and the address of a structure variable in can be stored in it. When a structure variable is passed by its value, a copy of the members is passed to the function. If the function modifies any member, then the changes do not affect the structure variable’s copy of members. When a structure variable is passed by its reference, the address of the structure variable is passed to the function. This means the function does not get any copy, instead, it gets the reference or address of the structure variable’s members. Nested structures are structures within a structure Array of structures is just like an array of simple data types stored at consecutive memory locations. Sample Input and Output: Enter the total no of Books: 2 Book 1 Enter ISBN: Enter Title: Enter Author: Enter Price:
  • 3. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 3 - Enter No. of Pages: Book 2 Enter ISBN: Enter Title: Enter Author: Enter Price: Enter No. of Pages: SrNo ISBN Title Author Price NoPages 1 678 DSA Tan 315 500 2 456 DBMS Kor 654 700 *************************** Enter the total no of Persons: 1 Person 1 Enter ID: Enter Name First Name: Middle Name: Last Name: Enter Address Flat No: Building: Street: City: Enter Age: ID First Middle Last Flat Bldg Street City Age 1 aa bb cc 6 dd 7 yy 19 Conclusion: Structures are used to group different characteristics of an entity into a group. All the members of a group are stored at consecutive memory locations. Database like structures can be created using the concept of Structures.
  • 4. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 4 - Experiment No. 2 Name of the Experiment: Array Implementation of Stack and Queue Aim: Write a program in C to create a stack of elements of any type. It should support all the basic operations. Write a Main program to implement the stack operations. Write a program in C to create a queue of elements of any type. It should support all the basic operations. Write a Main program to implement the queue operations. Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: A stack is called a "last in, first out," or LIFO data structure, because the last item added is the first to be removed. A stack can have any abstract data type as an element, but is characterized by only two fundamental operations: push and pop. The push operation adds to the top of the list, hiding any items already on the stack, or initializing the stack if it is empty. The pop operation removes an item from the top of the list, and returns this value to the caller. A pop either reveals previously concealed items, or results in an empty list. A stack is a restricted data structure, because only a small number of operations are performed on it. The nature of the pop and push operations also means that stack elements have a natural order. Elements are removed from the stack in the reverse order to the order of their addition: therefore, the lower elements are typically those that have been in the list the longest. When implemented Stack perform following operations push(element), element pop(), element peek(), display(), boolean isEmpty(), boolean isFull() Stack using array Push(10) Push(20) Push(30), Push(40), Push(50) Pop(), Pop() top=-1 top=0 top=1 top=4 top=2 9 … 4 3 2 1 0 9 … 4 3 2 1 0 10 9 … 4 3 2 1 20 0 10 9 … 4 50 3 40 2 30 1 20 0 10 9 … 4 3 2 30 1 20 0 10
  • 5. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 5 - A queue is a particular kind of collection in which the entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the rear terminal position and removal of entities from the front terminal position. This makes the queue a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed. This is equivalent to the requirement that whenever an element is added, all elements that were added before have to be removed before the new element can be invoked. A queue is an example of a linear data structure. Queue operations 1. enqueue - insert item at the back of queue Q 2. dequeue - return (and virtually remove) the front item from queue Q Given Q=(a[1],a[2],….a[n]) when viewed as a queue with a[n] as the rear element one says that a[i+1] is behind a[i], 1<i<=n. the restrictions on a queue imply that if the elements, A,B,C,D,E are added to the queue, then the first element which is inserted into the queue will be the first one to be removed. Thus A is the first letter to be removed, and queues are known as First In First Out (FIFO) lists. Circular Queue: In case of a ordinary queue the insertion take place from the front end and the deletion take place from the rear end. In the case of deletion from the front end data is deleted but the space of the queue is not utilized for the further storage. So this problem is solved in case of a circular queue. Even if the rear is full but there is space at the front end then the data can be stored in the front end until the queue overflows. As the name suggests, this Queue is not straight but circular; meaning, you got to have a structure like this - A circular queue is one in which the insertion of a new element is done at the very first location of the queue if last location of the queue is full. In other words if we have queue Q of say n elements, then after an inserting an element last (i.e. in the n-1th) location of the array the next element will be inserted at the very first location( i.e. location with subscript 0) of the array. It is possible to insert new elements, if and only if those locations (slots) are
  • 6. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 6 - empty. We can say that a circular queue is one in which the first element comes just after the last elements. It can be viewed as a mesh or loop of wire, in which the ends of the wire are connected together. A circular queue overcomes the problem of unutilized space in linear queues implemented as arrays. A circular queue also have a front and rear to keep the track of the elements to be deleted and inserted and therefore to maintain the unique characteristics of the queue. Sample Input and Output: **************Stack Operations***************** Menu: 1. Push 2. Pop 3. Display Option: 1 Enter Number: 10 Stack: 10 Option: 1 Enter Number: 20 Stack: 10 20 Option: 1 Enter Number: 30 Stack: 10 20 30 Option: 1 Enter Number: 40 Stack: 10 20 30 40 Option: 2 Stack: 10 20 30 Option: 2 Stack: 10 20 **************Queue Operations***************** Menu: 1. Enqueue 2. Dequeue 3. Display Option: 1 Enter Number: 10 Queue: 10 Option: 1 Enter Number: 20
  • 7. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 7 - Queue: 10 20 Option: 1 Enter Number: 30 Queue: 10 20 30 Option: 1 Enter Number: 40 Queue: 10 20 30 40 Option: 2 Queue: 20 30 40 Option: 2 Queue: 30 40 Conclusion: The stack is a Data Structure where insertions and deletions are possible only at one end. Stack is used in following applications 1. During execution of nested function calls for storing context of a function 2. Evaluation of postfix expression 3. Conversion from infix to postfix and infix to prefix. The queue is a Data Structure where insertions and deletions take place at opposite ends. Queue is mostly used in scheduling applications.
  • 8. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 8 - Experiment No. 3 Name of the Experiment: Insertion, deletion operations with Singly linked lists, Reversing a singly linked list Aim : Implement linked list and perform insertion and deletion operations. Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: Linked list are special list of some data elements linked to one another. The logical ordering is represented by having each element pointing to the next element. Each element is called a node, which has two parts: INFO part which stores the information and POINTER which points to the next element. A linked list whose nodes contain two fields: an integer value and a link to the next node A singly linked list is a dynamic structure. It may grow or shrink. Growing or shrinking depends on the operation made. In singly linked list we have one pointer (next) pointing to the next node. Linked lists are among the simplest and most common data structures; they provide an easy implementation for several important abstract data structures, including stacks, queues, associative arrays, and symbolic expressions. The principal benefit of a linked list over a conventional array is that the order of the linked items may be different from the order that the data items are stored in memory or on disk. For that reason, linked lists allow insertion and removal of nodes at any point in the list, with a constant number of operations Reversing a singly linked list Head or the first node of the Linked List (which is 4 in our case) 4 -> 6 -> 7 -> 1 -> 5 - > 8 -> 3 -> 2 -> NULL There are two approaches to solve the problem. These two approaches are: 1. Iterative Approach 2. Recursive Approach The following are some steps involved in the iterative approach. Step 1: Take three-pointers (previous, current, and next), and initialize them as the following. previous = NULL, current = head, next = NULL.
  • 9. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 9 - Step 2: Iterating through the linked list using a loop, and do following. next = current -> next current -> next = previous previous = current current = next Reverse a LinkedList Using Recursive Approach The following are some steps involved in the recursive approach. Step 1: Split the list given into two parts - the first node and the rest of the linked list. Step 2: Invoke the reverseList() method for the remaining portion of the linked list. Step 3: Join the rest to the first. Step 4: Fix the head pointer. Sample Input and Output: Implement all the following operations 1. Insert node at the Beginning 2. Insert node at the End 3. Insert at specific position 4. Add Before a particular node 5. Add After a particular node 6. Delete the first node 7. Delete the last node 8. Delete node at specific position 9. Delete Before a particular node 10. Delete After a particular node 11. Reverse the Linked List Default: Display Conclusion: Advantage of linked list over an array is, it’s dynamic implementation a which makes effective utilization of memory. Insertions and deletion of nodes in linked list requires manipulation of few pointers while in case of arrays there is cost of shifting the elements down for insertions and up for deletions. But accessing an element in linked list requires traversing the whole list starting from the first node, while accessing elements from an array is easier. In singly linked list, one can not traverse backwards, so doubly linked list can be used which uses two pointers, one points to the next node and the other one points to the previous node. Linked lists are very useful in polynomial evaluation.
  • 10. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 10 - Experiment No. 4 Name of the Experiment: Insertion, deletion operations with Doubly linked lists Aim : Implement Doubly linked list and perform insertion and deletion operations. Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list. 1) A DLL can be traversed in both forward and backward direction. 2) The delete operation in DLL is more efficient if pointer to the node to be deleted is given. 3) We can quickly insert a new node before a given node. In singly linked list, to delete a node, pointer to the previous node is needed. To get this previous node, sometimes the list is traversed. In DLL, we can get the previous node using previous pointer. Sample Input and Output: Implement all the following operations 1. Insert node at the Beginning 2. Insert node at the End 3. Insert at specific position 4. Add Before a particular node 5. Add After a particular node 6. Delete the first node 7. Delete the last node 8. Delete node at specific position 9. Delete Before a particular node 10. Delete After a particular node Default: Display Conclusion: The insertion operations that do not require traversal have the time complexity of O(1). And, insertion that requires traversal has time complexity of O(n) The space complexity is O(1).
  • 11. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 11 - Applications of DLL are in Redo and undo functionality in software, Forward and backward navigation in browsers, For navigation systems where forward and backward navigation is required.
  • 12. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 12 - Experiment No. 5 Name of the Experiment: Insertion, deletion operations with Circular linked lists Aim : Implement Circular linked list and perform insertion and deletion operations. Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: Circular linked list is a linked list where all nodes are connected to form a circle. There is no NULL at the end. A circular linked list can be a singly circular linked list or a doubly circular linked list. Circular Singly Linked Lists, where each node has 2 pointers, Next and Back to points to Next and the previous Node respectively, plus the next of last points to first Node(and vice versa), forming a Circle. Such a data structure is known as a circular doubly linked list. Sample Input and Output: Implement all the following operations 1. Insert node at the Beginning 2. Insert node at the End 3. Delete the first node 4. Delete the last node Default: Display Conclusion: Circular Singly Linked Lists: where we can only transverse in one direction, while maintaining the circular property. Circular Doubly Linked Lists: where we can transverse in both directions, while also maintaining the circular property.
  • 13. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 13 - Experiment No. 6 Name of the Experiment: Linked List implementation of Stack and Queue Aim: Write a program in java to create a stack using linked list. It should support all the basic operations. Write a Main program to implement the stack operations. Write a program in java to create a queue using linked list. It should support all the basic operations. Write a Main program to implement the queue operations. Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: A stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have any abstract data type as an element, but is characterized by only two fundamental operations: push and pop. The linked-list implementation is equally simple and straightforward. It requires that we implement a linked-list where only the head node or element can be removed, or popped, and a node can only be inserted by becoming the new head node. The push() operation adds a new node to a stack. It can be implemented using either insert_beginning or insert_end operation on singly linked list. A pop() operation removes the node from the stack. It can be implemented using either delete_beginning or delete_end operation on singly linked list. A queue is a first in, first out (FIFO) abstract data type and data structure. A queue can have any abstract data type as an element, but is characterized by only two fundamental operations: enqueue and dequeue. The linked-list implementation is equally simple and straightforward. It requires that we implement a linked-list where only the front node or element can be removed, or dequeued, and a node can only be inserted by becoming the new rear node. The enqueue() operation adds a new node in the queue. It can be implemented using either insert_beginning or insert_end operation on singly linked list. top 6
  • 14. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 14 - A dequeue() operation removes the node from the queue. It can be implemented using either delete_end or delete_beginning operation on singly linked list. front rear null Sample Input and Output: Menu: 1. Push 2. Pop 3. Display Option: 1 Enter Number: 10 Stack: 10 Option: 1 Enter Number: 20 Stack: 10 20 Option: 1 Enter Number: 30 Stack: 10 20 30 Option: 1 Enter Number: 40 Stack: 10 20 30 40 Option: 2 Stack: 10 20 30 Option: 2 Stack: 10 20 Menu: 1. Enqueue 2. Dequeue 3. Display Option: 1 Enter Number: 10 Queue: 10 Option: 1 Enter Number: 20 Queue: 10 20 Option: 1 10 20 30 40
  • 15. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 15 - Enter Number: 30 Queue: 10 20 30 Option: 1 Enter Number: 40 Queue: 10 20 30 40 Option: 2 Queue: 20 30 40 Option: 2 Queue: 30 40 Conclusion: Use of linked list overcomes the problem of limited static space allotted and stack overflow. Use of linked list overcomes the problem of limited static space allotted and queue overflow.
  • 16. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 16 - Experiment No. 7 Name of the Experiment: Binary Search Tree Aim: Implementation of operations (insertion, deletion, counting of nodes, counting of leaf nodes etc.) in a binary search tree. Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: A binary tree is a tree data structure in which each node has at most two child nodes, usually distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes may contain references to their parents. Outside the tree, there is often a reference to the "root" node (the ancestor of all nodes), if it exists. Any node in the data structure can be reached by starting at root node and repeatedly following references to either the left or right child. Binary trees are commonly used to implement binary search trees and binary heaps. A binary search tree is a non linear data structure in which items are arranged in a sorted sequence. It is used to represent hierarchical relationship existing among several data items. It can be traversed using Inorder(LVR), Preorder(VLR) and Postorder(LRV) techniques. A Binary Search Tree (BST) is a data structure such that elements are stored in tree nodes. Each tree node has a reference to its parent, left child, and right child. Each node in a BST also has a key associated with it. The Binary Search Tree Property is such that: 1. All keys in a node’s left-subtree are less than that node’s key 2. All keys in a node’s right-subtree are greater than that node’s key
  • 17. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 17 - Insert Node into the BST always insert new node as leaf node 1. Start at root node as current node 2. If new node’s key < current’s key 1. If current node has a left child, search left 2. Else add new node as current’s left child 4. If new node’s key > current’s key 1. If current node has a right child, search right 2. Else add new node as current’s right child Find a Node into the BST • Use the search key to direct a recursive binary search for a matching node 1. Start at the root node as current node 2. If the search key’s value matches the current node’s key then found a match 3. If search key’s value is greater than current node’s 1. If the current node has a right child, search right 2. Else, no matching node in the tree 4. If search key is less than the current node’s 1. If the current node has a left child, search left 2. Else, no matching node in the tree Deletion in BST • Basic idea: find the node to be removed, then “fix” the tree so that it is still a binary search tree • Three potential cases to fix: – Node has no children (leaf) – Node has one child – Node has two children
  • 18. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 18 - Sample Input and Output: Enter a set of Node: A B D C E G F H I Inorder: BDAGECHFI Postorder: DBGEHIFCA Enter Node to be deleted: D Inorder: BAGECHFI Postorder: BGEHIFCA Enter Node to be deleted: E Inorder: BAGCHFI Postorder: BGHIFCA Enter Node to be deleted: C Inorder: BAGHFI Postorder: BGIFHA Conclusion: Complexity of Building a Binary Search Tree • Worst case: O(n2) • Best case: O(n log n).
  • 19. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 19 - Experiment No. 8 Name of the Experiment: Fully in-threaded binary search tree Aim: Implementation of insertion, deletion and traversal for fully in-threaded binary search tree Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: In the linked representation of binary trees, more than one half of the link fields contain NULL values which results in wastage of storage space. If a binary tree consists of n nodes then n+1 link fields contain NULL values. So in order to effectively manage the space, a method was devised by Perlis and Thornton in which the NULL links are replaced with special links known as threads. Such binary trees with threads are known as threaded binary trees. Each node in a threaded binary tree either contains a link to its child node or thread to other nodes in the tree. In one-way threaded binary trees, a thread will appear either in the right or left link field of a node. If it appears in the right link field of a node then it will point to the next node that will appear on performing in order traversal. Such trees are called Right threaded binary trees. If thread appears in the left field of a node then it will point to the nodes inorder predecessor. Such trees are called Left threaded binary trees. Left threaded binary trees are used less often as they don't yield the last advantages of right threaded binary trees. In one-way threaded binary trees, the right link field of last node and left link field of first node contain a NULL. In order to distinguish threads from normal links they are represented by dotted lines. In two-way threaded Binary trees, the right link field of a node containing NULL values is replaced by a thread that points to nodes inorder successor and left field of a node containing NULL values is replaced by a thread that points to nodes inorder predecessor.
  • 20. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 20 - Sample Input and Output: Enter a set of Node: A B D C E G F H I Inorder: BDAGECHFI Postorder: DBGEHIFCA Enter Node to be deleted: D Inorder: BAGECHFI Postorder: BGEHIFCA Enter Node to be deleted: E Inorder: BAGCHFI Postorder: BGHIFCA Enter Node to be deleted: C Inorder: BAGHFI Postorder: BGIFHA Conclusion: Time complexity – O(h), where h is the height of the threaded binary search tree. The height of the tree can be ‘n’ in the worst case and all the keys are inserted in ascending or descending order(Skewed Tree) where all the nodes except the leaf have only one child and we may have to travel from to root to the deepest leaf node Space complexity – O(1)
  • 21. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 21 - Experiment No. 9 Name of the Experiment: AVL Tree Aim: Implementation of AVL tree Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: AVL Tree can be defined as height balanced binary search tree in which each node is associated with a balance factor which is calculated by subtracting the height of its right sub- tree from that of its left sub-tree. Tree is said to be balanced if balance factor of each node is in between -1 to 1, otherwise, the tree will be unbalanced and need to be balanced. Balance Factor (k) = height (left(k)) - height (right(k)) If balance factor of any node is 1, it means that the left sub-tree is one level higher than the right sub-tree. If balance factor of any node is 0, it means that the left sub-tree and right sub-tree contain equal height. If balance factor of any node is -1, it means that the left sub-tree is one level lower than the right sub-tree. An AVL tree is given in the following figure. We can see that, balance factor associated with each node is in between -1 and +1. therefore, it is an example of AVL tree. We perform rotation in AVL tree only in case if Balance Factor is other than -1, 0, and 1. There are basically four types of rotations which are as follows: L L rotation: Inserted node is in the left subtree of left subtree of A R R rotation : Inserted node is in the right subtree of right subtree of A L R rotation : Inserted node is in the right subtree of left subtree of A R L rotation : Inserted node is in the left subtree of right subtree of A Where node A is the node whose balance Factor is other than -1, 0, 1. The first two rotations LL and RR are single rotations and the next two rotations LR and RL are double rotations. For a tree to be unbalanced, minimum height must be at least 2, Let us understand each rotation 1. RR Rotation When BST becomes unbalanced, due to a node is inserted into the right subtree of the right subtree of A, then we perform RR rotation, RR rotation is an anticlockwise rotation, which is applied on the edge below a node having balance factor -2
  • 22. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 22 - In above example, node A has balance factor -2 because a node C is inserted in the right subtree of A right subtree. We perform the RR rotation on the edge below A. 2. LL Rotation When BST becomes unbalanced, due to a node is inserted into the left subtree of the left subtree of C, then we perform LL rotation, LL rotation is clockwise rotation, which is applied on the edge below a node having balance factor 2. In above example, node C has balance factor 2 because a node A is inserted in the left subtree of C left subtree. We perform the LL rotation on the edge below A. 3. LR Rotation Double rotations are bit tougher than single rotation which has already explained above. LR rotation = RR rotation + LL rotation, i.e., first RR rotation is performed on subtree and then LL rotation is performed on full tree, by full tree we mean the first node from the path of inserted node whose balance factor is other than -1, 0, or 1. State Action A node B has been inserted into the right subtree of A the left subtree of C, because of which C has become an unbalanced node having balance factor 2. This case is L R rotation where: Inserted node is in the right subtree of left subtree of C As LR rotation = RR + LL rotation, hence RR (anticlockwise) on subtree rooted at A is performed first. By doing RR rotation, node A, has become the left subtree of B.
  • 23. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 23 - After performing RR rotation, node C is still unbalanced, i.e., having balance factor 2, as inserted node A is in the left of left of C Now we perform LL clockwise rotation on full tree, i.e. on node C. node C has now become the right subtree of node B, A is left subtree of B Balance factor of each node is now either -1, 0, or 1, i.e. BST is balanced now. 4. RL Rotation As already discussed, that double rotations are bit tougher than single rotation which has already explained above. R L rotation = LL rotation + RR rotation, i.e., first LL rotation is performed on subtree and then RR rotation is performed on full tree, by full tree we mean the first node from the path of inserted node whose balance factor is other than -1, 0, or 1. State Action A node B has been inserted into the left subtree of C the right subtree of A, because of which A has become an unbalanced node having balance factor - 2. This case is RL rotation where: Inserted node is in the left subtree of right subtree of A
  • 24. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 24 - As RL rotation = LL rotation + RR rotation, hence, LL (clockwise) on subtree rooted at C is performed first. By doing RR rotation, node C has become the right subtree of B. After performing LL rotation, node A is still unbalanced, i.e. having balance factor -2, which is because of the right-subtree of the right- subtree node A. Now we perform RR rotation (anticlockwise rotation) on full tree, i.e. on node A. node C has now become the right subtree of node B, and node A has become the left subtree of B. Balance factor of each node is now either -1, 0, or 1, i.e., BST is balanced now. Construct AVL Tree for H, I, J, B, A, E, C, F, D, G, K, L
  • 25. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 25 - Sample Input and Output: Enter the elements: 10 20 30 40 50 25 Preorder traversal of the constructed AVL tree is 30 20 10 25 40 50 Conclusion: AVL tree controls the height of the binary search tree by not letting it to be skewed. The time taken for all operations in a binary search tree of height h is O(h). However, it can be extended to O(n) if the BST becomes skewed (i.e. worst case). By limiting this height to log n, AVL tree imposes an upper bound on each operation to be O(log n) where n is the number of nodes.
  • 26. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 26 - Experiment No. 10 Name of the Experiment: B Tree Aim: Implementation of operations in a B tree. Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: B-tree is a special type of self-balancing search tree in which each node can contain more than one key and can have more than two children. It is a generalized form of the binary search tree. It is also known as a height-balanced m-way tree. 1. For each node x, the keys are stored in increasing order. 2. In each node, there is a boolean value x.leaf which is true if x is a leaf. 3. If n is the order of the tree, each internal node can contain at most n - 1 keys along with a pointer to each child. 4. Each node except root can have at most n children and at least n/2 children. 5. All leaves have the same depth (i.e. height-h of the tree). 6. The root has at least 2 children and contains a minimum of 1 key. 7. If n ≥ 1, then for any n-key B-tree of height h and minimum degree t ≥ 2, h ≥ logt (n+1)/2. Insertions are done at the leaf node level. The following algorithm needs to be followed in order to insert an item into B Tree. 1. Traverse the B Tree in order to find the appropriate leaf node at which the node can be inserted. 2. If the leaf node contain less than m-1 keys then insert the element in the increasing order. 3. Else, if the leaf node contains m-1 keys, then follow the following steps. 4. Insert the new element in the increasing order of elements. 5. Split the node into the two nodes at the median. 6. Push the median element upto its parent node.
  • 27. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 27 - 7. If the parent node also contain m-1 number of keys, then split it too by following the same steps. Deletion is also performed at the leaf nodes. The node which is to be deleted can either be a leaf node or an internal node. Following algorithm needs to be followed in order to delete a node from a B tree. 1. Locate the leaf node. 2. If there are more than m/2 keys in the leaf node then delete the desired key from the node. 3. If the leaf node doesn't contain m/2 keys then complete the keys by taking the element from eight or left sibling. 4. If the left sibling contains more than m/2 elements then push its largest element up to its parent and move the intervening element down to the node where the key is deleted. 5. If the right sibling contains more than m/2 elements then push its smallest element up to the parent and move intervening element down to the node where the key is deleted. 6. If neither of the sibling contain more than m/2 elements then create a new leaf node by joining two leaf nodes and the intervening element of the parent node. 7. If parent is left with less than m/2 nodes then, apply the above process on the parent too. 8. If the the node which is to be deleted is an internal node, then replace the node with its in-order successor or predecessor. Since, successor or predecessor will always be on the leaf node hence, the process will be similar as the node is being deleted from the leaf node. Conclusion: Worst case Time complexity: Θ(log n), Average case Time complexity: Θ(log n), Best case Time complexity: Θ(log n), Average case Space complexity: Θ(n), Worst case Space complexity: Θ(n). B Tree Applications: databases and file systems, to store blocks of data (secondary storage media), multilevel indexing.
  • 28. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 28 - Experiment No. 11 Name of the Experiment: Adjacency Matrix Representation of Graph Aim: Implementation of adjacency matrix creation, Implementation of addition and deletion of edges in a directed graph using adjacency matrix. Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: An adjacency matrix is a way of representing a graph as a matrix of booleans (0's and 1's). A finite graph can be represented in the form of a square matrix on a computer, where the boolean value of the matrix indicates if there is a direct path between two vertices. Each cell in the above table/matrix is represented as Aij, where i and j are vertices. The value of Aij is either 1 or 0 depending on whether there is an edge from vertex i to vertex j. If there is a path from i to j, then the value of Aij is 1 otherwise its 0. For instance, there is a path from vertex 1 to vertex 2, so A12 is 1 and there is no path from vertex 1 to 3, so A13 is 0. In case of undirected graphs, the matrix is symmetric about the diagonal because of every edge (i,j), there is also an edge (j,i). Sample Input and Output: Enter Graph Input No. of Nodes: 4 Enter Graph Input No. of Edges: 4 For Edge 1 Enter Starting and Ending Vertex: 0 3 For Edge 2 Enter Starting and Ending Vertex: 0 2 For Edge 3 Enter Starting and Ending Vertex: 0 1 For Edge 4 Enter Starting and Ending Vertex: 1 2 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0
  • 29. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 29 - Enter Starting and Ending Vertex of Edge to be Deleted: 1 2 0 1 1 1 1 0 0 0 1 0 0 0 1 0 0 0 Conclusion: The basic operations like adding an edge, removing an edge, and checking whether there is an edge from vertex i to vertex j are extremely time efficient, constant time operations. If the graph is dense and the number of edges is large, an adjacency matrix should be the first choice. Even if the graph and the adjacency matrix is sparse, we can represent it using data structures for sparse matrices. The biggest advantage, however, comes from the use of matrices. The recent advances in hardware enable us to perform even expensive matrix operations on the GPU. By performing operations on the adjacent matrix, we can get important insights into the nature of the graph and the relationship between its vertices.
  • 30. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 30 - Experiment No. 12 Name of the Experiment: Adjacency List Representation of Graph Aim: Implementation of adjacency List creation, Implementation of addition and deletion of edges in a directed graph using adjacency List. Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: An adjacency list represents a graph as an array of linked lists. The index of the array represents a vertex and each element in its linked list represents the other vertices that form an edge with the vertex. Sample Input and Output: Enter Graph Input No. of Nodes: 4 Enter Graph Input No. of Edges: 4 For Edge 1 Enter Starting and Ending Vertex: 0 3 For Edge 2 Enter Starting and Ending Vertex: 0 2 For Edge 3 Enter Starting and Ending Vertex: 0 1 For Edge 4 Enter Starting and Ending Vertex: 1 2 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 0 Enter Starting and Ending Vertex of Edge to be Deleted: 1 2 0 1 1 1 1 0 0 0 1 0 0 0 1 0 0 0 Conclusion: An adjacency list is efficient in terms of storage because we only need to store the values for the edges. For a sparse graph with millions of vertices and edges, this can mean a lot of saved space. It also helps to find all the vertices adjacent to a vertex easily.
  • 31. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 31 - Experiment No. 13 Name of the Experiment: Implementation of Heap Sort Aim: Write a java program to accept a set of numbers and sort those using heap sort techniques and display. (Display the numbers after every iteration) Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: Heapsort is a comparison-based sorting algorithm, Heapsort is an in-place algorithm, but is not a stable sort. The heap sort works as its name suggests. It begins by building a heap out of the data set, and then removing the largest item and placing it at the end of the sorted array. After removing the largest item, it reconstructs the heap, removes the largest remaining item, and places it in the next open position from the end of the sorted array. This is repeated until there are no items left in the heap and the sorted array is full. Algorithm: Procedure PARENT (i) return floor(i/2) Procedure LEFT (i) return 2i Procedure RIGHT (i) return 2i + 1 Procedure Heapify (A, i) l ← left [i] r ← right [i] if l ≤ heap-size [A] and A[l] > A[i] then largest ← l else largest ← i if r ≤ heap-size [A] and A[i] > A[largest] then largest ← r if largest ≠ i then exchange A[i] ↔ A[largest] Heapify (A, largest) Procedure BUILD_HEAP (A) heap-size (A) ← length [A] For i ← floor(length[A]/2) down to 1 do Heapify (A, i)
  • 32. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 32 - Procedure HEAPSORT (A) BUILD_HEAP (A) for i ← length (A) down to 2 do exchange A[1] ↔ A[i] heap-size [A] ← heap-size [A] - 1 Heapify (A, 1) Sample Input and Output: Enter 8 elements: 25 57 48 37 12 92 86 33 Building a Heap 25 57 48 37 12 92 86 33 25 57 48 37 12 92 86 33 25 57 92 37 12 48 86 33 25 57 92 37 12 48 86 33 92 57 86 37 12 48 25 33 Pass 1: 86 57 48 37 12 33 25 92 Pass 2: 57 37 48 25 12 33 86 92 Pass 3: 48 37 33 25 12 57 86 92 Pass 4: 37 25 33 12 48 57 86 92 Pass 5: 33 25 12 37 48 57 86 92 Pass 6: 25 12 33 37 48 57 86 92 Pass 7: 12 25 33 37 48 57 86 92 Conclusion: An almost complete binary tree with n vertices has a depth of at most log(n). Therefore, procedure heapify requires at most log(n) steps. Procedure buildheap calls heapify for each vertex, therefore it requires at most n·log(n) steps. Heapsort calls buildheap once; then it calls heapify for each vertex, together it requires at most 2·n·log(n) steps. Thus, the time complexity of heapsort is T(n) O(n·log(n)).
  • 33. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 33 - Experiment No.: 14 Name of the Experiment: Implementation of Binary Search. Aim: Write a program to accept a set of numbers and search a number in a list by using Linear search and Binary search Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts, Stack, Queue Theory : Linear Search: Linear search or sequential search is a method for finding a particular value in a list, that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found. This is a very straightforward loop comparing every element in the array with the key. As soon as an equal value is found, it returns. If the loop finishes without finding a match, the search failed and -1 is returned. For small arrays, linear search is a good solution because it's so straightforward. In an array of a million elements linear search on average will take 500,000 comparisons to find the key. Binary Search: A fast way to search a sorted array is to use a binary search. The idea is to look at the element in the middle. If the key is equal to that, the search is finished. If the key is less than the middle element, do a binary search on the first half. If it's greater, do a binary search of the second half. The advantage of a binary search over a linear search is astounding for large numbers. There are two common ways to compute the index of the middle element. The most common way is to add the lowest and highest and divide by two. For example, int mid = (first + last) + 2; Overflow. This works well, or at least has worked well, until recently. The problem appeared when memories, and arrays, got very large. For the first time the sum of two array indexes, an intermediate value in the computation, can overflow the size of an int. computing the midpoint by adding the two and then dividing doesn't work. Reordering the expression avoids overflow. The solution is to rewrite the expression so that no intermediate value overflows the size of an int. This is easy to do using the following. int mid = first + (last - first) / 2;For most programs the difference between the two computations will never be seen because it will only appear with very large arrays Example-. Find 6 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114}. Step 1 (middle element is 19 > 6): -1 5 6 18 19 25 46 78 102 114 Step 2 (middle element is 5 < 6): -1 5 6 18 19 25 46 78 102 114 Step 3 (middle element is 6 == 6): -1 5 6 18 19 25 46 78 102 114
  • 34. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 34 - Algorithm : 1. Algorithm for linear Search: Algorithm for searching an item in the list lsearch(a[]) Let A= array of n elements, item=given item of information, loc=location of item in A, loc=0 if search is successful. 1. [Initialization counter] set loc=1 2. Search for an item a. While (data[loc]!=item) b. Set loc=loc+1 3. [successful] if loc=n+1 a. Then setloc=0 4. Exit/return 2. Algorithm for Binary search: Algorithm for searching an item in the list bsearch(a[]) Let A= array of n elements, item=given item of information, loc=location of item in A, low=0 , high=n-1 if search is successful. 1. If(low>high) i. return 2. mid=(low+high)/2 3. If(x==a[mid]) i. return (mid) 4. if(x<x[mid]) i. search for x in a[low] to a[mid-1] 5. else i. search for x in a[mid+1] to a[high] 6. return/exit Sample Input and Output: ********Linear Search********** Enter the set of 10 Numbers: 12 78 21 56 54 89 32 11 10 69 Linear Search for: 32 Element 32 found at Index 6 with 7 Comparisons Continue(Y/N): Y Linear Search for: 99 Element 99 NOT found with 10 Comparisons
  • 35. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 35 - ********Binary Search********** Enter the sorted set of 10 Numbers: 10 15 19 25 36 48 57 61 72 88 Binary Search for: 36 Element 36 found at Index 4 with 1 Comparisons Continue(Y/N): Y Binary Search for: 19 Element 19 found at Index 2 with 3 Comparisons Binary Search for: 99 Element 99 NOT found with 4 Comparisons Conclusion: For an array of a million elements, binary search, O(log N), will find the target element with a worst case of only 20 comparisons. Linear search, O(N), on average will take 500,000 comparisons to find the element. Probably the only faster kind of search uses hashing, a topic that isn't covered in these notes. This performance comes at a price - the array must be sorted first. Because sorting isn't a fast operation, O(N log N), it may not be worth the effort to sort when there are only a few searches.
  • 36. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 36 - Experiment No. 15 Name of the Experiment: Implementation of Bubble, Selection, Insertion and Quick Sort Aim: Write a java program to accept a set of numbers and sort those using Bubble, Selection, Insertion and Quick sort techniques and display. (Display the numbers after every iteration) Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: Bubble Sort Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort algorithm. In each step, elements written in bold are being compared. First Pass: ( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them. ( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4 ( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2 ( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them. Second Pass: ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2 ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted. Third Pass: ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) Finally, the array is sorted, and the algorithm can terminate.
  • 37. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 37 - Insertion Sort The following table shows the steps for sorting the sequence 5 7 0 3 4 2 6 1.For each iteration, the number of positions the inserted element has moved is shown in brackets. Altogether this amounts to 17 steps. 5 7 0 3 4 2 6 1 (0) 5 7 0 3 4 2 6 1 (0) 0 5 7 3 4 2 6 1 (2) 0 3 5 7 4 2 6 1 (2) 0 3 4 5 7 2 6 1 (2) 0 2 3 4 5 7 6 1 (4) 0 2 3 4 5 6 7 1 (1) 0 1 2 3 4 5 6 7 (6) Selection Sort 1. Find the minimum value in the list 2. Swap it with the value in the first position 3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time) For e.g. 64 25 12 22 11 11 25 12 22 64 11 12 25 22 64 11 12 22 25 64 11 12 22 25 64 Quick Sort Quicksort sorts by employing a divide and conquer strategy to divide a list into two sub-lists. The steps are: 1. Pick an element, called a pivot, from the list. 2. Reorder the list so that all elements which are less than the pivot come before the pivot and so that all elements greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. 3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements. Algorithm: procedure bubbleSort( A : list of sortable items ) defined as:
  • 38. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 38 - do swapped := false for each i in 0 to length(A) - 2 inclusive do: if A[i] > A[i+1] then swap( A[i], A[i+1] ) swapped := true end if end for while swapped end procedure Algorithm: procedure insertionSort(array A) begin for i := 1 to length[A]-1 do begin value := A[i]; j := i - 1; done := false; repeat if A[j] > value then begin A[j + 1] := A[j]; j := j - 1; if j < 0 then done := true; end else done := true; until done; A[j + 1] := value; end; end;
  • 39. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 39 - Algorithm: procedure selectionSort(array A) begin for i = 0 to length[A] – 2 do begin min = i; for j = i + 1 to length[A]-1 do begin if (a[j] < a[min]) begin min = j; end end if (i != min) begin swap = a[i]; a[i] = a[min]; a[min] = swap; end end end Algorithm: procedure quicksort(array, left, right) if right > left select a pivot index pivotNewIndex:=partition(array, left, right, pivotIndex) quicksort(array, left, pivotNewIndex - 1) quicksort(array, pivotNewIndex + 1, right) function partition(array, left, right, pivotIndex) pivotValue := array[pivotIndex] swap array[pivotIndex] and array[right] storeIndex := left for i from left to right - 1 if array[i] < pivotValue
  • 40. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 40 - swap array[i] and array[storeIndex] storeIndex := storeIndex + 1 swap array[storeIndex] and array[right] return storeIndex Sample Input and Output: ***********Bubble Sort************** Enter 8 elements: 25 57 48 37 12 92 86 33 Pass 1: 25 48 37 12 57 86 33 92 Pass 2: 25 37 12 48 57 33 86 92 Pass 3: 25 12 37 48 33 57 86 92 Pass 4: 12 25 37 33 48 57 86 92 Pass 5: 12 25 33 37 48 57 86 92 Pass 6: 12 25 33 37 48 57 86 92 Pass 7: 12 25 33 37 48 57 86 92 ***********Insertion Sort************** Enter 8 elements: 25 57 48 37 12 92 86 33 Pass 1: 25 57 48 37 12 92 86 33 Pass 2: 25 48 57 37 12 92 86 33 Pass 3: 25 37 48 57 12 92 86 33 Pass 4: 12 25 37 48 57 92 86 33 Pass 5: 12 25 37 48 57 92 86 33 Pass 6: 12 25 37 48 57 86 92 33 Pass 7: 12 25 33 37 48 57 86 92 ***********Selection Sort************** Enter 8 elements: 25 57 48 37 12 92 86 33 Pass 1: 25 57 48 37 12 33 86 92 Pass 2: 25 57 48 37 12 33 86 92 Pass 3: 25 33 48 37 12 57 86 92 Pass 4: 25 33 12 37 48 57 86 92 Pass 5: 25 33 12 37 48 57 86 92 Pass 6: 25 12 33 37 48 57 86 92 Pass 7: 12 25 33 37 48 57 86 92 ***********Quick Sort************** Enter 8 elements:
  • 41. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 41 - 25 57 48 37 12 92 86 33 Pass 1: 12 25 48 37 57 92 86 33 Pass 2: 12 25 33 37 48 92 86 57 Pass 3: 12 25 33 37 48 92 86 57 Pass 4: 12 25 33 37 48 57 86 92 Pass 5: 12 25 33 37 48 57 86 92 Conclusion: Bubble sort has worst-case and average complexity both О(n²), where n is the number of items being sorted. However, one significant advantage that bubble sort has over most other implementations, even QuickSort, is that the ability to detect that the list is sorted is efficiently built into the algorithm. Performance of bubble sort over an already-sorted list (best-case) is O(n). The best case input is an array that is already sorted. In this case insertion sort has a linear running time (i.e., Θ(n)). During each iteration, the first remaining element of the input is only compared with the right-most element of the sorted subsection of the array. The worst case input is an array sorted in reverse order. In this case every iteration of the inner loop will scan and shift the entire sorted subsection of the array before inserting the next element. For this case insertion sort has a quadratic running time (i.e., O(n2 )). The average case is also quadratic, which makes insertion sort impractical for sorting large arrays. However, insertion sort is one of the fastest algorithms for sorting arrays containing fewer than ten elements. Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations Quicksort takes Θ(nlogn) time on average. It's not hard to see that the partition operation, which simply loops over the elements of the array once, uses Θ(n) time. In versions that perform concatenation, this operation is also Θ(n). In the best case, each time we perform a partition we divide the list into two nearly equal pieces. This means each recursive call processes a list of half the size. Consequently, we can make only logn nested calls before we reach a list of size 1. This means that the depth of the call tree is Θ(logn). But no two calls at the same level of the call tree process the same part of the original list; thus, each level of calls needs only Θ(n) time all together (each call has some constant overhead, but since there are only Θ(n) calls at each level, this is subsumed in the Θ(n) factor). The result is that the algorithm uses only Θ(nlogn) time.
  • 42. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 42 - Experiment No. 16 Name of the Experiment: Implementation of infix to postfix conversion and evaluation of postfix expression Aim: Write a C Program to convert Infix Expression to Postfix Expression and Evaluate it. Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts, Stack, Queue Theory: Infix: ( ( ( A + B ) * ( C – D ) ) / N ) Prefix: /*+AB –CDN Postfix: AB+CD-*N/ Evaluation of PostFix Expression Step 1: If a character is an operand push it to Stack Step 2: If the character is an operator Pop two elements from the Stack. Operate on these elements according to the operator, and push the result back to the Stack Step 3: Step 1 and 2 will be repeated until the end has reached. Step 4: The Result is stored at the top of the Stack, return it Step 5: End For e.g. postexp= “3 4 + 7 3 - * 3 %” Stack: Empty Postexp[0]= 3 operand push(3) Stack: 3 Postexp[1]= 4 operand push(4) Stack: 3 4 Postexp[2]= + operator b=pop(),a=pop() c=a+b=3+4=7 push(c) Stack: 7 Postexp[3]= 7 operand push(7) Stack: 7 7 Postexp[4]= 3 operand push(3) Stack: 7 7 3 Postexp[5]= - operator b=pop(),a=pop()
  • 43. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 43 - c=a-b=7-3=4 push(c) Stack: 7 4 Postexp[6]= * operator b=pop(),a=pop() c=a*b=7*4=28 push(c) Stack: 28 Postexp[7]= 3 operand push(3) Stack: 28 3 Postexp[8]= % operator b=pop(),a=pop() c=a*b=28%3=1 push(c) Stack: 1 Result=1 Conversion of Infix to Postfix Step 1: Scan the Infix Expression from left to right. Step 2: If the scanned character is an operand, append it with final Infix to Postfix string. Step 3: Else, Step 3.1: If the precedence order of the scanned (incoming) operator is greater than the precedence order of the operator in the stack (or the stack is empty or the stack contains a ‘(‘ or ‘[‘ or ‘{‘), push it on stack. Step 3.2: Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you encounter parenthesis while popping then stop there and push the scanned operator in the stack.) Step 4: If the scanned character is an ‘(‘ or ‘[‘ or ‘{‘, push it to the stack. Step 5: If the scanned character is an ‘)’or ‘]’ or ‘}’, pop the stack and output it until a ‘(‘ or ‘[‘ or ‘{‘ respectively is encountered, and discard both the parenthesis. Step 6: Repeat steps 2-6 until infix expression is scanned. Step 7: Print the output Step 8: Pop and output from the stack until it is not empty. Sample Input and Output: Enter a infix expression: (3+4)*(7-3) Postfix expression: 3 4 + 7 3 - * Result: 28 Conclusion: Stack can efficiently be used to evaluate post fix expressions.
  • 44. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 44 - Experiment No. 17 Name of the Experiment: Application of Circular Linked List Aim: Write Implementation of Josephus Problem using circular linked list Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts, Stack, Queue Theory: There are N people standing in a circle numbered from 1 to N. Also given an integer K. First, count the K-th number starting from the first one and delete it. Then K numbers are counted starting from the next one and the K-th one is removed again, and so on. The process stops when one number remains. The task is to find the last number. For n = 7 and k = 2 Algorithm 1. Create a list containing integers from 1 to N. 2. Create a recursive function which deletes every Kth element from the list in each iteration in the clockwise direction. 3. Continue repeating the above steps until only one element is left. Sample Input and Output: Input: N = 6, K = 2 Output: 5 Conclusion: Josephus Problem can be used in Random Number generation
  • 45. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 45 - Experiment No. 18 Name of the Experiment: Implementation of traversal of a directed graph through BFS and DFS Aim: Given A connected graph G(V,E), write a program in java to visit all the vertices using Breadth First Traversal and Depth First Traversal technique. (Use Adjacency matrix representation for the graph) Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts, Stack, Queue Theory: A DFS algorithm, as the name implies, is used to search deeper in the graph, whenever possible. The edges are explored, out of the most recently discovered vertex v that still has unexplored edges leaving it. When all of v's edges have been explored, the search backtracks to explore edges leaving the vertex from which v was discovered. This process continues until we have discovered all the vertices that are reachable from the source vertex. DFS uses stack structure to maintain the order in which the vertices are to be processed. Algorithm: Step 1: Initialize all nodes to ready state (status = 1) Step 2: Push the starting node in stack and change its status to the waiting state (status = 2) Step 3: Repeat step 4 and 5 until stack is empty Step 4: pop the top node n of stack. Process n and change the status of n to the processed state (status = 3) Step 5: Push on to the stack, all the neighbor of n that are in ready state (status = 1), and change their status to the waiting state (status = 2) [End of the step 3 loop] Step 6: exit In graph theory, breadth-first search (BFS) is a graph search algorithm that begins at the root node and explores all the neighboring nodes. Then for each of those nearest nodes, it explores their unexplored neighbor nodes, and so on, until it finds the goal. BFS uses queue structure to maintain the order in which the vertices are to be processed. Algorithm: 1. Enqueue the root node. 2. Dequeue a node and examine it. 3. If the element sought is found in this node, quit the search and return a result. 4. Otherwise enqueue any successors (the direct child nodes) that have not yet been discovered.
  • 46. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 46 - 5. If the queue is empty, every node on the graph has been examined – quit the search and return "not found". 6. Repeat from Step 2. Sample Input and Output: Enter no. of vertices: 7 Enter no. of edges: 7 Enter Source and Destination for edge 1: A B Enter Source and Destination for edge 2: A C Enter Source and Destination for edge 3: A D Enter Source and Destination for edge 4: B E Enter Source and Destination for edge 5: B F Enter Source and Destination for edge 6: C G Enter Source and Destination for edge 7: D F Breadth First Traversal: A B C D E F G Depth First Traversal: A B E F D C G Conclusion: DFS(G, v) visits all the vertices and edges in the connected component of v. The discovery edges labeled by DFS(G, v) form a spanning tree of the connected component of v. The time and space analysis of DFS differs according to its application area. In theoretical computer science, DFS is typically used to traverse an entire graph, and takes time O(|V| + |E|), linear in the size of the graph. In these applications it also uses space O(|V|) in the worst case to store the stack of vertices on the current search path as well as the set of already-visited vertices. The time complexity can also be expressed as O( | E | + | V | ) where | E | is the cardinality of the set of edges (the number of edges), and | V | is the cardinality of the set of vertices, since every vertex and every edge will be explored in the worst case. A B C D E F G
  • 47. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 47 - Experiment No. 19 Name of the Experiment: Dijkstra’s algorithm Aim: Implementation of finding shortest distances using Dijkstra’s algorithm Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: Dijkstra's algorithm allows us to find the shortest path between any two vertices of a graph. Dijkstra's Algorithm works on the basis that any subpath B -> D of the shortest path A -> D between vertices A and D is also the shortest path between vertices B and D. The algorithm uses a greedy approach in the sense that we find the next best solution hoping that the end result is the best solution for the whole problem. function dijkstra(G, S) for each vertex V in G distance[V] <- infinite previous[V] <- NULL If V != S, add V to Priority Queue Q distance[S] <- 0 while Q IS NOT EMPTY U <- Extract MIN from Q for each unvisited neighbour V of U tempDistance <- distance[U] + edge_weight(U, V) if tempDistance < distance[V] distance[V] <- tempDistance previous[V] <- U return distance[], previous[]
  • 48. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 48 - Sample Input and Output: For following Graph Enter Adjacency Matrix 0 3 1 0 0 3 0 7 5 1 1 7 0 2 0 0 5 2 0 7 0 1 0 7 0 Adjacency Matrix 0 3 1 0 0 3 0 7 5 1 1 7 0 2 0 0 5 2 0 7 0 1 0 7 0 Enter the starting vertex:0 Distance of node1=3 Path=1<-0 Distance of node2=1 Path=2<-0 Distance of node3=3 Path=3<-2<-0 Distance of node4=4 Path=4<-1<-0 Conclusion: Time Complexity: O(E Log V) where, E is the number of edges and V is the number of vertices. Space Complexity: O(V) To find the shortest path, In social networking applications, In a telephone network, To find the locations in the map
  • 49. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 49 - Experiment No. 20 Name of the Experiment: Collision Resolution Techniques Aim: Implementation of hashing functions with different collision resolution techniques 1. Linear Probing 2. Quadratic Probing 3. Double Hashing Equipments / Components required: C/C++ Compiler Pre-requisite: C Programming Concepts Theory: Like separate chaining, open addressing is a method for handling collisions. In Open Addressing, all elements are stored in the hash table itself. So at any point, the size of the table must be greater than or equal to the total number of keys. This approach is also known as closed hashing. This entire procedure is based upon probing. We will understand types of probing ahead. Open Addressing is done in the following ways: a) Linear Probing: In linear probing, the hash table is searched sequentially that starts from the original location of the hash. If in case the location that we get is already occupied, then we check for the next location. The function used for rehashing is as follows: rehash(key) = (n+1)%table-size. For example, the typical gap between two probes is 1 as seen in the example below. Let hash(x) be the slot index computed using a hash function and S be the table size If slot hash(x) % S is full, then we try (hash(x) + 1) % S If (hash(x) + 1) % S is also full, then we try (hash(x) + 2) % S If (hash(x) + 2) % S is also full, then we try (hash(x) + 3) % S b) Quadratic Probing If you observe carefully, then you will understand that the interval between probes will increase proportionally to the hash value. Quadratic probing is a method with the help of which we can solve the problem of clustering that was discussed above. This method is also known as mid-square method. In this method we look for i2 ‘th slot in i’th iteration. We always start from the original hash location. If only the location is occupied then we check the other slots. Let hash(x) be the slot index computed using hash function. If slot hash(x) % S is full, then we try (hash(x) + 1*1) % S If (hash(x) + 1*1) % S is also full, then we try (hash(x) + 2*2) % S If (hash(x) + 2*2) % S is also full, then we try (hash(x) + 3*3) % S
  • 50. Laboratory Manual [SEIT Sem. III] Data Structures and Analysis Information Technology, BVCOE, Navi Mumbai - 50 - c) Double Hashing The intervals that lie between probes is computed by another hash function. Double hashing is a technique that reduces clustering in an optimized way. In this technique, the increments for the probing sequence are computed by using another hash function. We use another hash function hash2(x) and look for i*hash2(x) slot in i’th rotation. Let hash(x) be the slot index computed using hash function. If slot hash(x) % S is full, then we try (hash(x) + 1*hash2(x)) % S If (hash(x) + 1*hash2(x)) % S is also full, then we try (hash(x) + 2*hash2(x)) % S If (hash(x) + 2*hash2(x)) % S is also full, then we try (hash(x) + 3*hash2(x)) % S Sample Input and Output: Enter the size of the Hash Table: 7 Enter the No. of Keys: 5 Enter the Keys: 16 40 27 9 75 Linear Probing: 75 X 16 9 X 40 27 Enter the size of the Hash Table: 7 Enter the No. of Keys: 3 Enter the Keys: 15 23 85 Quadratic Probing: X 15 23 X X 85 X Enter the size of the Hash Table: 7 Enter the No. of Keys: 5 Enter the Keys: 37 25 12 40 75 Double Hashing: 47 X 37 40 25 12 X Conclusion: Linear probing has the best cache performance but suffers from clustering. One more advantage of Linear probing is easy to compute. Quadratic probing lies between the two in terms of cache performance and clustering. Double hashing has poor cache performance but no clustering. Double hashing requires more computation time as two hash functions need to be computed.