Updated Dsa Lab Manual 2022-23

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

List of Experiments

Sr. No. Experiments Name


1. Implementation of nested structure in C.
2. Implementation of self-referential structure in C.
3. C Program to Check if a Matrix is a Sparse Matrix
4. Implementation of following sorting algorithms: Insertion Sort, Selection,
Bubble Sort, Quick Sort, Merge Sort, Heap Sort.
5. Implementation of Binary Search Trees(BST) and perform Insertion and
Deletion in BST
6. Implementing our Own Hash Table with Separate Chaining in C
Implementation of following operations on Singly Linked List, Doubly Linked List
and Circular Linked List
 Create
7.
 Insert at beginning, at end and at given position.
 Delete a node from beginning, from end and from a given position.
 Display
8. Create new linked list from two given linked list with greater element at each
node
Stack and Queue
Linked List and Array implementation of stack considering following operations:
 Push
9.
 Pop
 Peek
 Reverse
Linked List and Array implementation of queue, double ended queue and
circular queue considering following operations:
10.
 Enqueue
 Dequeue
Implementation of tree Traversal techniques as given below:
 Preorder
11.
 Post order
 Inorder
Implement AVL tree perform following operations:
12.  Insert an element
 Delete an element
Implementation of graph using :
13.  Adjacency Matrix
 List
14. Implementation of Graph Traversal using BFS and DFS.
Data Structure and Information Retrieval

Experiment No. : 1

Implementation of nested Structure in C


Experiment No. 1
1. Aim: Implementation of nested structure in C.

2. Algorithm
If one of the members of structure is also a structure, then such a structure is called as a
nested structure.
The syntax of a nested structure can be as given below :
struct structure_name
{
data_type variable_name;
struct { data_type variable_name;
} internal_structure_name;
};
For example to describe a circle we need its radius and centre. The centre requires x and
y co–ordinates. Hence, this can be described by a nested structure as shown below :
struct circle
{
float radius;
struct
{
float x,y;
}centre;
}
To access the element of an internal structure the syntax is as given below:
structure_variable name.internal_structure_name.element_name;
For example if we make an variable of structure circle as struct circle c, then to access the
“x” coordinate of the structure we will have the syntax as “c.centre.x”

3. Conclusion and Discussion: Hence we have implemented nested structure in C.


Data Structure and Information Retrieval

Experiment No. : 2

Implementation of self-referential
structure in C.
Experiment No. 2
1. Aim: Implementation of self-referential structure in C.

2. Algorithm
▪ Self Referential structures are those structures that have one or more pointers which
point to the same type of structure, as their member. In other words, structures pointing
to the same type of structures are self-referential in nature.

Example:
struct node {
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob;
return 0;
}
▪ In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the
structure ‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before
accessing, as by default it contains garbage value.
Types of Self Referential Structures
1. Self Referential Structure with Single Link
2. Self Referential Structure with Multiple Links
Self Referential Structure with Single Link: These structures can have only one self-
pointer as their member. The following example will show us how to connect the
objects of a self-referential structure with the single link and access the corresponding
data members. The connection formed is shown in the following figure.

▪ Self Referential Structure with Multiple Links: Self referential structures with
multiple links can have more than one self-pointers. Many complicated data structures
can be easily constructed using these structures. Such structures can easily connect to
more than one nodes at a time. The following example shows one such structure with
more than one links.
▪ The connections made in the above example can be understood using the following
figure.

3. Conclusion and Discussion: Hence we have implemented self referential structure in C.


Data Structure and Information Retrieval

Experiment No. : 3

C Program to Check if a Matrix is a


Sparse Matrix
Experiment No. 3
1. Aim: C Program to Check if a Matrix is a Sparse Matrix

2. Algorithm
1. Declare and initialize a two-dimensional array a.
2. Calculate the number of rows and columns present in the given array and store it in
variables rows and cols respectively.
3. Loop through the array and count the number of zeroes present in the given array and
store in the variable count.
4. Calculate the size of the array by multiplying the number of rows with many columns of
the array.
5. If the count is greater than size/2, given matrix is the sparse matrix. That means, most of
the elements of the array are zeroes.
6. Else, the matrix is not a sparse matrix.

3. Conclusion and Discussion: Hence we have implemented C Program to Check if a


Matrix is a Sparse Matrix.
Data Structure and Information Retrieval

Experiment No. : 4

Implementation of following sorting


algorithms: Insertion Sort, Selection,
Bubble Sort, Quick Sort, Merge Sort,
Heap Sort.
Experiment No. 4
1. Aim: Implementation of following sorting algorithms: Insertion Sort, Selection, Bubble
Sort, Quick Sort, Merge Sort, Heap Sort.

2. Algorithm
Insertion Sort

Step 1 - If the element is the first element, assume that it is already sorted. Return 1.

Step2 - Pick the next element, and store it separately in a key.

Step3 - Now, compare the key with all elements in the sorted array.

Step 4 - If the element in the sorted array is smaller than the current element, then move
to the next element. Else, shift greater elements in the array towards the right.

Step 5 - Insert the value.

Step 6 - Repeat until the array is sorted.

Selection Sort
1. SELECTION SORT(arr, n)
2.
3. Step 1: Repeat Steps 2 and 3 for i = 0 to n-1
4. Step 2: CALL SMALLEST(arr, i, n, pos)
5. Step 3: SWAP arr[i] with arr[pos]
6. [END OF LOOP]
7. Step 4: EXIT
8.
9. SMALLEST (arr, i, n, pos)
10. Step 1: [INITIALIZE] SET SMALL = arr[i]
11. Step 2: [INITIALIZE] SET pos = i
12. Step 3: Repeat for j = i+1 to n
13. if (SMALL > arr[j])
14. SET SMALL = arr[j]
15. SET pos = j
16. [END OF if]
17. [END OF LOOP]
18. Step 4: RETURN pos

Bubble Sort
1. bubbleSort(array)
2. n = length(array)
3. repeat
4. swapped = false
5. for i = 1 to n - 1
6. if array[i - 1] > array[i], then
7. swap(array[i - 1], array[i])
8. swapped = true
9. end if
10. end for
11. n=n-1
12. until not swapped
13. end bubbleSort

Quick Sort
1. QUICKSORT (array A, start, end)
2. {
3. 1 if (start < end)
4. 2{
5. 3 p = partition(A, start, end)
6. 4 QUICKSORT (A, start, p - 1)
7. 5 QUICKSORT (A, p + 1, end)
8. 6}
9. }

Partition Algorithm:

The partition algorithm rearranges the sub-arrays in a place.


1. PARTITION (array A, start, end)
2. {
3. 1 pivot ? A[end]
4. 2 i ? start-1
5. 3 for j ? start to end -1 {
6. 4 do if (A[j] < pivot) {
7. 5 then i ? i + 1
8. 6 swap A[i] with A[j]
9. 7 }}
10. 8 swap A[i+1] with A[end]
11. 9 return i+1
12. }

Merge Sort
1. MERGE_SORT(arr, beg, end)
2.
3. if beg < end
4. set mid = (beg + end)/2
5. MERGE_SORT(arr, beg, mid)
6. MERGE_SORT(arr, mid + 1, end)
7. MERGE (arr, beg, mid, end)
8. end of if
9.
10. END MERGE_SORT

Heap Sort
1. HeapSort(arr)
2. BuildMaxHeap(arr)
3. for i = length(arr) to 2
4. swap arr[1] with arr[i]
5. heap_size[arr] = heap_size[arr] ? 1
6. MaxHeapify(arr,1)
7. End

BuildMaxHeap(arr)
1. BuildMaxHeap(arr)
2. heap_size(arr) = length(arr)
3. for i = length(arr)/2 to 1
4. MaxHeapify(arr,i)
5. End

MaxHeapify(arr,i)

1. MaxHeapify(arr,i)
2. L = left(i)
3. R = right(i)
4. if L ? heap_size[arr] and arr[L] > arr[i]
5. largest = L
6. else
7. largest = i
8. if R ? heap_size[arr] and arr[R] > arr[largest]
9. largest = R
10. if largest != i
11. swap arr[i] with arr[largest]
12. MaxHeapify(arr,largest)
13. End

3. Conclusion and Discussion: Hence we have implemented Insertion Sort, Selection,


Bubble Sort, Quick Sort, Merge Sort, Heap Sort algorithms in C.
Data Structure and Information Retrieval

Experiment No. : 5

Implementation of Binary Search


Trees(BST) and perform Insertion and
Deletion in BST
Experiment No. 5
1. Aim: Implementation of Binary Search Trees(BST) and perform Insertion and Deletion in
BST

2. Algorithm
Insert (TREE, ITEM)

Step 1: IF TREE = NULL


Allocate memory for TREE
SET TREE -> DATA = ITEM
SET TREE -> LEFT = TREE -> RIGHT = NULL
ELSE
IF ITEM < TREE -> DATA
Insert(TREE -> LEFT, ITEM)
ELSE
Insert(TREE -> RIGHT, ITEM)
[END OF IF]
[END OF IF]
Step 2: END

Delete (TREE, ITEM)


Step 1: IF TREE = NULL
Write "item not found in the tree" ELSE IF ITEM < TREE -> DATA
Delete(TREE->LEFT, ITEM)
ELSE IF ITEM > TREE -> DATA
Delete(TREE -> RIGHT, ITEM)
ELSE IF TREE -> LEFT AND TREE -> RIGHT
SET TEMP = findLargestNode(TREE -> LEFT)
SET TREE -> DATA = TEMP -> DATA
Delete(TREE -> LEFT, TEMP -> DATA)
ELSE
SET TEMP = TREE
IF TREE -> LEFT = NULL AND TREE -> RIGHT = NULL
SET TREE = NULL
ELSE IF TREE -> LEFT != NULL
SET TREE = TREE -> LEFT
ELSE
SET TREE = TREE -> RIGHT
[END OF IF]
FREE TEMP
[END OF IF]
Step 2: END

3. Conclusion and Discussion: Hence we have implemented C Program to insert and


deletion operation in Binary Search Tree.
Data Structure and Information Retrieval

Experiment No. : 6

Implementing our Own Hash Table with


Separate Chaining in C
Experiment No. 6
1. Aim: Implementing our Own Hash Table with Separate Chaining in C

2. Algorithm:

1. Read the value of ‘table’ which contained keys and records


2. Read the key to be searched using hashing, say KEY
3. Apply hash function to find the index at which record with the key may present.
4. If key is not found then performed step 4.1 else go to step 4.2.
4.1 Continuously apply rehash function to find next empty position and insert record with
the key.
4.2 print position of the key as well as display information of record associated with the
key.
5. Stop
Conclusion: In this way, we have minimized the no of unnecessary comparisons by using hash
function.
Data Structure and Information Retrieval

Experiment No. : 7

Implementation of following operations


on Singly Linked List, Doubly Linked
List and Circular Linked List
Experiment No. 6
1. Aim: Implementation of following operations on Singly Linked List, Doubly Linked List
and Circular Linked List

2. Algorithm:

Singly Linked List

Inserting a node at the beginning


1. Check if ptr = NULL then print : “overflow” and return else create a new node
from memory and assign its addressto ptr
2. Set ptr.info = item
3. Set ptr.next = start
4. Set start = ptr
5. Return

Inserting a node at the end


1. Check if ptr = NULL then print : “overflow” and return else
create a new node from memory and assign its address to ptr
2. Set ptr.info = item
3. Set ptr.next = NULL
4. Check if start = NULL then set start = p
5. Set loc = start
6. Repeat step 7 until loc.next != NULL
7. Set loc = loc.next
8. Set loc.next = p
9. Return
Inserting a new node at specified position
1. Check if ptr = NULL then print : “overflow” and return else
create a new node from memory and assign its address to ptr
2. Set ptr.info = item
3. Check if start = NULL then set start = p and
set p.next = NULL
4. Set temp = start and i = 0
5. Repeat step 6 and 7 until i<loc
6. Set temp = temp.next
7. Set i = i +1
8. Set p.next = temp.next
9. Set temp.next = p
10. Return.

Deleting first node


1. Check, if start = NULL then print: “Linked list is empty”
and return
2. Set ptr = start
3. Set start = start.next
4. Print the deleted item
5. Return

Deleting last node


1. Check, if start = NULL then print: “Linked list is empty”
and return
2. if start -> next = NULL then
2.1. Set ptr = start
2.2. Set start = NULL
2.3. print, element deleted i.e., ptr.info
3. Set ptr = start
4. Repeat steps 5 to 6 till ptr.next != NULL
5. Set loc = ptr
6. Set ptr = ptr.next
7. Set loc.next = NULL
Deleting the node from specified position
1. Check if ptr = NULL then print: “Linked list is empty”
and return
2. Set i = 0 and set ptr = start
3. Repeat step 4 to 9 until i<=loc
4. Set temp = ptr
5. Set ptr = ptr.next
6. Set i = i +1
7. Print element deleted
8. Set temp.next = ptr.next
9. Return

Display(Traverse) Operation
1: [Initialize] Set Ptr = Start
2: Repeat Steps 3 And 4 While Ptr != Null
3: Apply Process To Ptr Data
4: Set Ptr = Ptr Next
[End Of Loop]
Step 5: EXIT
Doubly Linked List

Inserting a node at the Beginning


1. Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 9
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL-> NEXT
Step 4: SET NEW_NODE ->DATA = VAL
Step 5: SET NEW_NODE ->PREV = NULL
Step 6: SET NEW_NODE->NEXT = START
Step 7: SET START -> PREV = NEW_NODE
Step 8: SET START = NEW_NODE
Step 9: EXIT
Inserting a node at the End
Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 11
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL-> NEXT
Step 4: SET NEW_NODE ->DATA = VAL
Step 5: SET NEW_NODE ->NEXT= NULL
Step 6: SET PTR = START
Step 7: Repeat Step 8 while PTR NEXT != NULL
Step 8: SET PTR = PTR NEXT
[END OF LOOP]
Step 9: SET PTR->NEXT = NEW_NODE
Step 10 : SET NEW_NODE ->PREV = PTR
Step 11: EXIT

Inserting a node at the specific position


Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 12
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL-> NEXT
Step 4: SET NEW_NODE->DATA = VAL
Step 5: SET PTR = START
Step 6: Repeat Step 7 while PTR-> DATA != NUM
Step 7: SET PTR = PTR-> NEXT
[END OF LOOP]
Step 8: SET NEW_NODE-> NEXT = PTR ->NEXT
Step 9: SET NEW_NODE-> PREV = PTR
Step 10 : SET PTR -> NEXT = NEW_NODE
Step 11 : SET PTR -> NEXT->PREV = NEW_NODE
Step 12: EXIT

Deleting a node from the Beginning


Step 1: IF START = NULL
Write UNDERFLOW
Go to Step 6
[END OF IF]
Step 2: SET PTR = START
Step 3: SET START = START-> NEXT
Step 4: SET START-> PREV = NULL
Step 5: FREE PTR
Step 6: EXIT

Deleting a node from the End


Step 1: IF START = NULL
Write UNDERFLOW
Go to Step 7
[END OF IF]
Step 2: SET PTR = START
[END OF LOOP]
Step 3: Repeat Step 4 while PTR-> NEXT != NULL
Step 4: SET PTR = PTR ->NEXT
Step 5: SET PTR-> PREV->NEXT = NULL
Step 6: FREE PTR
Step 7: EXIT

Deleting a node from specific position


Step 1: IF START = NULL
Write UNDERFLOW
Go to Step 9
[END OF IF]
Step 2: SET PTR = START
[END OF LOOP]
Step 3: Repeat Step 4 while PTR DATA != NUM
Step 4: SET PTR = PTR-> NEXT
Step 5: SET TEMP = PTR->NEXT
Step 6: SET PTR ->NEXT = TEMP->NEXT
Step 7: SET TEMP ->NEXT->PREV = PTR
Step 8: FREE TEMP
Step 9: EXIT

Circular Linked List

Inserting a node at the Beginning


Step 1: IF PTR = NULL
Write OVERFLOW
Go to Step 11
[END OF IF]
Step 2: SET NEW_NODE = PTR
Step 3: SET PTR = PTR -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET TEMP = HEAD
Step 6: Repeat Step 8 while TEMP -> NEXT != HEAD
Step 7: SET TEMP = TEMP -> NEXT
[END OF LOOP]
Step 8: SET NEW_NODE -> NEXT = HEAD
Step 9: SET TEMP → NEXT = NEW_NODE
Step 10: SET HEAD = NEW_NODE
Step 11: EXIT

Inserting a node at the end

Step 1: IF PTR = NULL


Write OVERFLOW
Go to Step 1
[END OF IF]
Step 2: SET NEW_NODE = PTR
Step 3: SET PTR = PTR -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> NEXT = HEAD
Step 6: SET TEMP = HEAD
Step 7: Repeat Step 8 while TEMP -> NEXT != HEAD
Step 8: SET TEMP = TEMP -> NEXT
[END OF LOOP]
Step 9: SET TEMP -> NEXT = NEW_NODE
Step 10: EXIT

Deleting a node from the Beginning


Step 1: IF HEAD = NULL
Write UNDERFLOW
Go to Step 8
[END OF IF]
Step 2: SET PTR = HEAD
Step 3: Repeat Step 4 while PTR → NEXT != HEAD
Step 4: SET PTR = PTR → next
[END OF LOOP]
Step 5: SET PTR → NEXT = HEAD → NEXT
Step 6: FREE HEAD
Step 7: SET HEAD = PTR → NEXT
Step 8: EXIT

Deleting a node from the end

Step 1: IF HEAD = NULL


Write UNDERFLOW
Go to Step 8
[END OF IF]
Step 2: SET PTR = HEAD
Step 3: Repeat Steps 4 and 5 while PTR -> NEXT != HEAD
Step 4: SET PREPTR = PTR
Step 5: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 6: SET PREPTR -> NEXT = HEAD
Step 7: FREE PTR
Step 8: EXIT

Traversing a circular linked List

STEP 1: SET PTR = HEAD


STEP 2: IF PTR = NULL
WRITE "EMPTY LIST"
GOTO STEP 8
END OF IF
STEP 4: REPEAT STEP 5 AND 6 UNTIL PTR → NEXT != HEAD
STEP 5: PRINT PTR → DATA
STEP 6: PTR = PTR → NEXT
[END OF LOOP]
STEP 7: PRINT PTR→ DATA
STEP 8: EXIT

Conclusion: Hence we have implemented all the operations of single linked list, Doubly Linked
List and circular Linked List.
Data Structure and Information
Representation

Experiment No. : 8

Create new linked list from two given


linked list with greater element at each
node.
Experiment No. 8
1. Aim: Create new linked list from two given linked list with greater element at each node.
2. Algorithm
We have given two linked lists of the same size and we have to create a new linked list
from the two linked lists with the max numbers from the two linked lists.

Let's see the steps to solve the problem.

Write a struct node.

Create two linked lists of the same size.

Iterate over the linked list.

Find the max number from the two linked lists nodes.

Create a new node with the max number.

Add the new node to the new linked list.

Print the new linked list.

3. Conclusion and Discussion:


In this way, we have implemented new linked list from two given linked list with greater element
at each node. .
Data Structure and Information
Representation

Experiment No. : 9

Array and Linked List Implementation of


Stack and Queue
Experiment No. 9
4. Aim: Array and Linked List Implementation of Stack and Queue.

5. Algorithm

Array Implementation of Stack and Queue.

Algorithm for Inserting an item into the stack (PUSH)


PUSH (maxsize, item)
Let stack [maxsize] is an array for implementing the stack. 1.
Check for stack overflow
If top= maxsize – 1, then print: “Stack Overflow” and return.
2. Set top=top+1
3. Set stack [top] =item
4. return.

Algorithm for Deleting an item from the stack (POP)


POP (maxsize)
1. Check if top < 0 then print: “Stack Underflow” and return.
Else set item = stack [top]
2. Set top = top – 1
3. Return the deleted item from the stack

Algorithm for Inserting an item into a Queue


Step 1: IF REAR = MAX-1
Write OVERFLOW
Goto step 4
[END OF IF]
Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR =0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: SET QUEUE[REAR] = NUM
Step 4: EXIT
Algorithm for Deleting an item from a Queue

Step 1: IF FRONT = -1 OR FRONT > REAR


Write UNDERFLOW
ELSE
SET VAL = QUEUE[FRONT]
SET FRONT = FRONT + 1
[END OF IF]
Step 2: EXIT
Linked List Implementation of Stack and Queue
Algorithm for Inserting an item into the stack (PUSH)

1. Check if ptr = NULL then print: “Stack overflow” and return


2. Else create a new node from memory and assign its address to ptr
3. Set ptr->next = top
4. Set top = ptr

Algorithm for Deleting an item from the stack (POP)

1. Check if top ==NULL then print: “Stack Underflow” and return


Else set t = top-> data
2. Set top = top->next

3. Return the deleted item from the stack

Algorithm for Inserting an item into the Queue

1. Check if ptr = NULL then print: “overflow” and return


2. Else create a new node from memory and assign its address to ptr
3. Set rear->Next=ptr
4. Set rear=ptr

Algorithm for Deleting an item from the Queue


5. Check, if front = NULL then print: “Queue is Underflow”
Else Set item = queue[front]
6. Set t=front-> data
7. Set front=front-> next
8. Return the deleted item from the queue.

6. Conclusion and Discussion:


We can insert and delete element only at one end using stack data structures and can insert an
element at one end and delete an element from other end using queue data structures.In linked
list implementation of stack and queue, We can overcome the drawbacks of array
implementation of stack and using linked list.
Data Structure and Information
Representation

Experiment No. : 10

Implementation of Linked List and Array


implementation of queue, double ended
queue and circular queue considering
following operations:

• Enqueue

• Dequeue
Experiment No. 10
1. Aim: Linked List and Array implementation of queue, double ended queue and circular queue
considering following operations:
 Enqueue
 Dequeue

2. Algorithm

Algorithm for inserting an item in a Circular queue.

Let MAXSIZE be the maximum number of elements in queue. CQ [] is array. 1. If

(front== (rear+1) % MAXSIZE) then print queue is full

Else accept the value

2. If (front==-1) then set rear=front=0 rear =(

(rear+1) % MAXSIZE)

3. Set CQ [rear] =value

Algorithm for deleting an item from a Circular queue.

1. If (front==-1) then print queue is empty Else


item=CQ [front]
2. If (front==rear) then set front=-1 rear=-1
3. Else (front== (front+1) % MAXSIZE)
3.1.1. If (front==-1) then set rear=front=0
3.1.2. rear =( (rear+1) % MAXSIZE)
4. Set CQ [rear] =value

Algorithm for Inserting an item at Rear end of the Double Ended Queue

Let MAXSIZE be the maximum number of elements in queue. DQ [] is array.


1. If (rear== MAXSIZE-1) then print queue is full Else
accept the value
2. Set rear=rear+1
3. Set DQ [rear] =value

Algorithm for Deleting an item from front end of the Double Ended Queue

1. If (rear<front) then print queue is empty

2. Else Set front=front+1

3. Set Item= DQ [front]

Algorithm for Inserting an item at front end of the Double Ended Queue

4. If (front==0) then print queue is full

5. Else accept the value of an item Set

front=front-1

6. Set DQ [front] =item

Algorithm for Deleting an item from a rear end of Double Ended Queue

2. If (front==rear) then print queue is empty


3. Else Set rear=rear-1
4. Item=DQ [rear]

3. Conclusion and Discussion:


Thus Circular queue have less memory consumption as compared to linear queue because while
doing insertion after deletion operation it allocate an extra space the first remaining vacant but in
circular queue the first is used as it comes immediate after the last. we can insert and delete data
at both (rear and front) ends by using double ended queue data structure
.
Data Structure and Information
Representation

Experiment No. : 11

Implementation of tree Traversal


techniques as given below:

• Preorder

• Post order

• Inorder
Experiment No. 11
1. Aim:. Implementation of tree Traversal techniques as given below:
• Preorder
• Post order
• Inorder

2. Algorithm

Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)

Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
3. Conclusion and Discussion:
Thus we have implemented creation of Binary Tree and its traversal methods.
Data Structure and Information
Representation

Experiment No. : 12

Implementation Implement AVL tree


perform following operations:
• Insert an element
• Delete an element
Experiment No. 12
1. Aim: Implement AVL tree perform following operations:
• Insert an element
• Delete an element

2. Algorithm
Algorithm for inserting an item in AVL Tree.
A newNode is always inserted as a leaf node with balance factor equal to 0.
1. Let the initial tree be:
Let the node to be inserted be:
2. Go to the appropriate leaf node to insert a newNode using the following recursive
steps. Compare newKey with rootKey of the current tree.
 If newKey < rootKey, call insertion algorithm on the left subtree of the current
node until the leaf node is reached.
 Else if newKey > rootKey, call insertion algorithm on the right subtree of current
node until the leaf node is reached.
 Else, return leafNode.

3. Compare leafKey obtained from the above steps with newKey:

 If newKey < leafKey, make newNode as the leftChild of leafNode.

 Else, make newNode as rightChild of leafNode.

4. Update balanceFactor of the nodes

5. If the nodes are unbalanced, then rebalance the node.


 If balanceFactor > 1, it means the height of the left subtree is greater than
that of the right subtree. So, do a right rotation or left-right rotation
 If newNodeKey < leftChildKey do right rotation.
 Else, do left-right rotation.

 If balanceFactor < -1, it means the height of the right subtree is greater than
that of the left subtree. So, do right rotation or right-left rotation

 If newNodeKey > rightChildKey do left rotation.

 Else, do right-left rotation


Algorithm for Deleting an item from AVL Tree.
A node is always deleted as a leaf node. After deleting a node, the balance factors of the
nodes get changed. In order to rebalance the balance factor, suitable rotations are
performed.

5. Locate nodeToBeDeleted
6. There are three cases for deleting a node:
a. If nodeToBeDeleted is the leaf node (ie. does not have any child), then
remove nodeToBeDeleted.
b. If nodeToBeDeleted has one child, then substitute the contents of
nodeToBeDeleted with that of the child. Remove the child.
c. If nodeToBeDeleted has two children, find the inorder successor w of
nodeToBeDeleted (ie. node with a minimum value of key in the right
subtree).
7. Update balanceFactor of the nodes
8. Rebalance the tree if the balance factor of any of the nodes is not equal to -1, 0 or
1.
 If balanceFactor of currentNode > 1,
 If balanceFactor of leftChild >= 0, do right rotation
 Else do left-right rotation.
 If balanceFactor of currentNode < -1,
 If balanceFactor of rightChild <= 0, do left rotation.
 Else do right-left rotation.

3. Conclusion and Discussion:


An AVL tree is a self-balancing binary search tree. It was the first such data structure to
be invented. In an AVL tree, the heights of the two child subtrees of any node differ by at
most one; if at any time they differ by more than one, rebalancing is done to restore this
property
Data Structure and Information
Representation

Experiment No. : 13

Implementation of graph using:


• Adjacency Matrix
• List.
Experiment No. 13
1. Aim: Implementation of graph using :
• Adjacency Matrix
• List

2. Theory
There are two ways in which we represent graphs, these are:

Adjacency Matrix

Adjacency List

Both these have their advantages and disadvantages. In this tutorial, we will cover both of these
graph representation along with how to implement them.

Adjacency Matrix
Adjacency matrix representation makes use of a matrix (table) where the first row and first
column of the matrix denote the nodes (vertices) of the graph. The rest of the cells contains either
0 or 1 (can contain an associated weight w if it is a weighted graph).

Each row X column intersection points to a cell and the value of that cell will help us in
determining that whether the vertex denoted by the row and the vertex denoted by the column are
connected or not. If the value of the cell for v1 X v2 is equal to 1, then we can conclude that
these two vertices v1 and v2 are connected by an edge, else they aren't connected at all.
Consider the given graph below:
The graph shown above is an undirected one and the adjacency matrix for the same looks
as:

3. Conclusion and Discussion:


In this way, we have studied adjacency list and matrix representation of graph.
Data Structure and Information
Representation

Experiment No. : 14

Implementation of Graph Traversal using


BFS and DFS.
Experiment No. 14
1. Aim: Implementation of Graph Traversal Techniques.
 Depth First Search(DFS)
 Breadth First Search(BFS)

2. Algorithm
Algorithm (Depth First Search)

1. Select any node in the graph. Mark this node as visited, push this node on the stack.

2. Find the adjacent node to the node on top of stack, and which, and which is not yet
visited. (We can use adjacency matrix for it). Make this new node as visited and push
onto the stack.

3. Repeat step 2, until no new adjacent node to the top of the stack, node can be found.
When no new adjacent node can be found, pop the top of the stack.

4. Repeat step 2 and 3 till stack becomes empty.

5. Repeat above steps, if there are any more nodes which are still unvisited.

Algorithm (Breadth First Search)


1. Select any node in the graph. Mark this node as visited.

2. Find the adjacent node, add them to the queue.

3. Visit this node, which is at the front of the queue. Delete this node form queue and place
it’s adjacent in node in queue. (We can use adjacency matrix for it). Make this new node
as visited.
4. Repeat step 2 and 3 till queue becomes empty.

3. Conclusion and Discussion:


In this way, we have studied depth wise graph traversal technique which uses stack and breadth
wise graph traversal technique which uses queue for its implementation.

You might also like