Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DS Lab Manual by Prof Abhijeet Jadhav

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

MARATHWADA INSTITUTE OF TECHNOLOGY, LABORATORY

AURANGABAD
PRACTICAL EXPERIMENT INSTRUCTION SHEET
Experiment Title: Write a program to demonstrate insertion, deletion, search and
displaying of an element in anArray.

DEPARTMENT: CS&IT[PG] LABORATORY: PG LAB


Experiment No: 01 YEAR:2023-24
Class:MSc[IT] FY PART:I SUBJECT: Data Structure Lab

Aim:-Write a program to demonstrate insertion, deletion, search and displaying of an


element in anArray.
Theory:-
– Insertion of new element in an array can be done in two ways.
1) Insertion at the end of an array.
2) Insertion at required position.
Insertion an element at the end of an array can be easily done provided the memory space
allocated for the array is large enough to accommodate the additional element.
Consider the array a[10]={2, 6, 8, 7, 23, 91}.

a[0]=2 a[0]=2 a[0]=2


a[1]=6 a[1]=6 a[1]=6

a[2]=8 a[2]=8 a[2]=8

a[3]=7 a[3]=7 a[3]=7

a[4]=23
a[4] a[4]=21

a[5]=91 a[5]=23 a[5]=23


a[6]=91 a[6]=91
a) Original array b) Elements shifted c) Array after insertion
Downwards

Algorithm:
Insertion Operartion:
Insert(arr[], size, elementToInsert)
if size >= MAX_SIZE
print "Array is full. Insertion failed."
return 0 // Insertion failed

arr[size] = elementToInsert
size++
print "Element inserted successfully."
return 1 // Insertion successful
Deletion Operation:
DeleteElement(arr[], size, elementToDelete)
position = Search(arr, size, elementToDelete)

if position == -1
print "Element not found. Deletion failed."
return 0 // Deletion failed

// Shift elements to the left to fill the gap created by deletion


for i = position to size - 2
arr[i] = arr[i + 1]

size--
print "Element deleted successfully."
return 1 // Deletion successful

Search Operation:
Search(arr[], size, key)
for i = 0 to size - 1
if arr[i] == key
return i // Element found at position i

return -1 // Element not found

Display Operation:
Display(arr[], size)
print "Array elements: "
for i = 0 to size - 1
print arr[i], " "

print newline

Program:
/* Write a program to demonstrate insertion, deletion, search and displaying of an element in an array.*/
#include <stdio.h>
#define MAX_SIZE 100

// Function to display the elements of the array


void display(int arr[], int size) {
printf("Array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

// Function to search for an element in the array


int search(int arr[], int size, int key) {
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
return i;
}
}
return -1; // Element not found
}

// Function to insert an element at the end of the array


int insert(int arr[], int *size, int element) {
if (*size >= MAX_SIZE) {
printf("Array is full. Insertion failed.\n");
return 0; // Insertion failed
}
arr[*size] = element;
(*size)++;
printf("Element inserted successfully.\n");
return 1; // Insertion successful
}
// Function to delete an element from the array
int deleteElement(int arr[], int *size, int element) {
int position = search(arr, *size, element);

if (position == -1) {
printf("Element not found. Deletion failed.\n");
return 0; // Deletion failed
}

// Shift elements to the left to fill the gap created by deletion


for (int i = position; i < *size - 1; i++) {
arr[i] = arr[i + 1];
}
(*size)--;
printf("Element deleted successfully.\n");
return 1; // Deletion successful
}

int main() {
int arr[MAX_SIZE];
int size = 0;
int choice;

while (1) {
printf("\nMenu:\n");
printf("1. Insert an element\n");
printf("2. Delete an element\n");
printf("3. Search for an element\n");
printf("4. Display elements\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the element to insert: ");
int elementToInsert;
scanf("%d", &elementToInsert);
insert(arr, &size, elementToInsert);
break;

case 2:
printf("Enter the element to delete: ");
int elementToDelete;
scanf("%d", &elementToDelete);
deleteElement(arr, &size, elementToDelete);
break;

case 3:
printf("Enter the element to search: ");
int key;
scanf("%d", &key);
int position = search(arr, size, key);
if (position != -1) {
printf("Element %d found at position %d\n", key, position);
} else {
printf("Element %d not found\n", key);
}
break;

case 4:
display(arr, size);
break;

case 5:
printf("Exiting program.\n");
return 0;

default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
Output:
Menu:
1. Insert an element
2. Delete an element
3. Search for an element
4. Display elements
5. Exit
Enter your choice: 1
Enter the element to insert: 6
Element inserted successfully.

Menu:
1. Insert an element
2. Delete an element
3. Search for an element
4. Display elements
5. Exit
Enter your choice: 4
Array elements: 2 23 12 20 6

Menu:
1. Insert an element
2. Delete an element
3. Search for an element4. Display elements
5. Exit
Enter your choice: 2
Enter the element to delete: 20
Element deleted successfully.

Menu:
1. Insert an element
2. Delete an element
3. Search for an element
4. Display elements
5. Exit
Enter your choice: 4
Array elements: 2 23 12 6

Menu:
1. Insert an element
2. Delete an element
3. Search for an element
4. Display elements
5. Exit
Enter your choice: 3
Enter the element to search: 23
Element 23 found at position 1
MARATHWADA INSTITUTE OF TECHNOLOGY, LABORATORY
AURANGABAD
PRACTICAL EXPERIMENT INSTRUCTION SHEET
Experiment Title: Write a program in C to demonstrate operation performed on
stack.

DEPARTMENT: CS&IT[PG] LABORATORY: PG LAB


Experiment No: 02 YEAR:2023-24
Class:MSc[IT] FY PART:I SUBJECT: Data Structure Lab

Aim:- Write a program in C to demonstrate operation performed on stack.

Theory: - Stack is a linear data structure that follows a particular order in which the operations are
performed. The order may be LIFO (Last In First Out) or FILO (First In Last Out).

Basic features of Stack:

1. Stack is an ordered list of similar data type.


2. Stack is a LIFO(Last in First out) structure or we can say FILO(First in Last out).
3. push() function is used to insert new elements into the Stack and pop() function is
used to remove an element from the stack. Both insertion and removal are allowed at only one end of Stack
called Top.
4. Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state
if it is completely empty.
Applications of Stack:

The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter -
and then pop letters from the stack.
There are other uses also like:

1. Parsing
2. Expression Conversion(Infix to Postfix, Postfix to Prefix etc)

Algorithm:
Push:
Push(A[], x)
if top == MAX_SIZE - 1
print "Error: Stack overflow"
return
top++
A[top] = x

Pop:
Pop(A[ ])
if top == -1
print "Error: No elements to pop"
return
top--
Display:
Display(A[ ])
if top == -1
print "Stack is empty"
return
for i from top to 0
print A[i], " "
print newline

Program:
#include <stdio.h>
#define MAX_SIZE 101

int A[MAX_SIZE];
int top = -1;
void Push(int x) {
if(top == MAX_SIZE-1) {
printf("Error: Stack overflow\n");
return;
}
A[++top] = x; //initially top = -1 means there no element in the stack, so firstly increase the size then
pushes the element to the stack
}
void Pop() {
if(top == -1) {
printf("Error: No elements to pop\n");
return;
}
top--; // if the size of the stack is greater than -1 then it decrease the size of top by 1 means it pops the
element from the stack
}
void Display() {
if(top == -1) {
printf("Stack is empty\n");
return;
}
for(int i=top; i>=0; i--) {
printf("%d ", A[i]);
}
printf("\n");
}
int main() {
int choice, x;

while(1) {
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch(choice) {
case 1:
printf("Enter element to push: ");
scanf("%d", &x);
Push(x);
break;
case 2:
Pop();
break;
case 3:
Display();
break;
case 4:
return 0;
default:
printf("Invalid choice\n");
}
}
}

Output:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter element to push: 20

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter element to push: 23

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter element to push: 06
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter element to push: 12
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
12 6 23 20

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter element to push: 19

1. Push
2. Pop3. Display
4. Exit
Enter your choice: 3
19 12 6 23 20

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
12 6 23 20

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
6 23 20
MARATHWADA INSTITUTE OF TECHNOLOGY, LABORATORY
AURANGABAD
PRACTICAL EXPERIMENT INSTRUCTION SHEET
Experiment Title: Write a program in C to demonstrate operations on Queue.

DEPARTMENT: CS&IT[PG] LABORATORY: PG LAB


Experiment No: 3 YEAR:2023-24
Class: MSc[IT] FY PART:I SUBJECT: Data Structure Lab

Aim:- Write a program in C to demonstrate operations on Queue.

Theory: - A Queue is a linear structure which follows a particular order in which the operations are performed. The
order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the
consumer that came first is served first. The difference between stacks and queues is in removing. In a stack we
remove the item the most recently added; in a queue, we remove the item the least recently added.
Applications of Queue:
1) Applied as waiting lists for a single shared resource like CPU, Disk, and Printer.
2) Applied as buffers on MP3 players and portable CD players.
3) Applied on Operating system to handle interruption.
4) Applied to add song at the end or to play from the front.

Algorithm:
Insert :
Insert(A[], x)
if rear == MAX_SIZE - 1
print "Queue Overflow"
return

if front == -1
front = 0

rear++
A[rear] = x

Delete:
Delete(A[])
if front == -1 or front > rear
print "Queue Underflow"
return

front++

Display:
Display(A[])
if front == -1
print "Queue is empty"
return

for i from front to rear


print A[i], " "
print newline

Program:
#include <stdio.h>
#define MAX_SIZE 101

int A[MAX_SIZE];
int rear = -1;
int front = -1;

void Insert(int x) {
if(rear == MAX_SIZE-1) {
printf("Queue Overflow\n");
return;
}
if(front == -1)
front = 0;
A[++rear] = x;
}

void Delete() {
if(front == -1 || front > rear) {
printf("Queue Underflow\n");
return ;
}
front++;
}

void Display() {
if(front == -1) {
printf("Queue is empty\n");
return;
}
for(int i = front; i <= rear; i++) {
printf("%d ", A[i]);
}
printf("\n");
}

int main() {
int choice, x;

while(1) {

printf("1. Insert element to queue \n");


printf("2. Delete element from queue \n");
printf("3. Display all elements of queue \n");
printf("4. Quit \n");

printf("Enter your choice : ");


scanf("%d", &choice);

switch(choice) {
case 1:
printf("Enter element to insert: ");
scanf("%d", &x);
Insert(x);
break;
case 2:
Delete();
break;
case 3:
Display();
break;
case 4:
return 0;
default:
printf("Wrong choice \n");
}
}
}

Output:

1. Insert element to queue


2. Delete element from queue
3. Display all elements of queue
4. Quit
Enter your choice : 1
Enter element to insert: 22
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4. Quit
Enter your choice : 1
Enter element to insert: 6
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4. Quit
Enter your choice : 1
Enter element to insert: 12
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4. Quit
Enter your choice : 1
Enter element to insert: 19
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4. Quit
Enter your choice : 3
22 6 12 19
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4. Quit
Enter your choice : 2
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4. Quit
Enter your choice : 3
6 12 19
MARATHWADA INSTITUTE OF TECHNOLOGY, LABORATORY
AURANGABAD
PRACTICAL EXPERIMENT INSTRUCTION SHEET
Experiment Title: Write a program in C to demonstrate operations on Linked
List.

DEPARTMENT: CS&IT[PG] LABORATORY: PG LAB


Experiment No: 4 YEAR:2023-24
Class:MSc[IT] FY PART:I SUBJECT: Data Structure Lab

Aim: Write a program in C to demonstrate operations on Linked List.

Theory:
A linked list is a linear data structure. It is defines as the collection of objects called nodes that are
randomly stored in memory. These nodes are connected together via links.
• A node contains two fields:
-Data part: This part of the node holds the value/element.
-Link part: This part of the node holds the address of the next node.
• The last node of the linked list contains pointer to the null/end of list.

Types of linked list


1. Singly Linked list

2. Doubly Linked list

3. Circular Lined List


Program 1: Operations on Singly Linked list
Algorithm:

Insert:
Insert()
Read new_data from the user
Create a new_node
Set new_node->data to new_data
Set new_node->next to head
Set head to new_node

Delete:
Delete()
Read key from the user

Set temp to head, prev to NULL

If temp is not NULL and temp->data is equal to key


Set head to temp->next
Free temp
Return

While temp is not NULL and temp->data is not equal to key


Set prev to temp
Set temp to temp->next

If temp is NULL, return

Set prev->next to temp->next


Free temp

Search:
Search()
Read key from the user

Set current to head, index to 0

While current is not NULL


If current->data is equal to key
Print "Element found at index ", index
Return

Set current to current->next


Increment index

Print "Element not found"


Display:
Display()
Set ptr to head

Print "Linked list Elements : "


While ptr is not NULL
Print ptr->data, " "
Set ptr to ptr->next

Program:
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node *next;
};

struct Node* head = NULL;

// Insert node at beginning


void insert() {
int new_data;
printf("Enter element to insert: ");
scanf("%d", &new_data);

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));


new_node->data = new_data;
new_node->next = head;
head = new_node;
}

// Delete node by key


void delete() {
int key;
printf("Enter element to delete: ");
scanf("%d", &key);

struct Node *temp = head, *prev;


if (temp != NULL && temp->data == key) {
head = temp->next;
free(temp);
return;
}

while (temp != NULL && temp->data != key) {


prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;

free(temp);
}

// Search element by key


void search() {
int key, index=0;
printf("Enter element to search: ");
scanf("%d", &key);

struct Node* current = head;


while (current != NULL) {
if (current->data == key) {
printf("Element found at index %d", index);
return;
}
current = current->next;
index++;
}

printf("Element not found");


}

// Display linked list


void display() {
struct Node* ptr;
ptr = head;
printf("Linked list Elements : ");
while (ptr != NULL) {
printf("%d ", ptr->data);
ptr = ptr->next;
}
}

int main() {
// Menu based operations
int choice;
while(1) {
printf("\n1. Insert\n");
printf("2. Delete\n");
printf("3. Search\n");
printf("4. Display\n");
printf("5. Exit\n");

printf("Enter your choice: ");


scanf("%d", &choice);
if (choice == 5)
break;

switch(choice) {
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
search();
break;
case 4:
display();
break;
default:
printf("Invalid choice\n");
}
}
return 0;
}

Output:

1. Insert
2. Delete
3. Search
4. Display
5. Exit
Enter your choice: 1
Enter element to insert: 22
1. Insert
2. Delete
3. Search
4. Display
5. Exit
Enter your choice: 1
Enter element to insert: 55
1. Insert
2. Delete
3. Search
4. Display
5. Exit
Enter your choice: 1
Enter element to insert: 19
1. Insert
2. Delete
3. Search
4. Display
5. Exit
Enter your choice: 1
Enter element to insert: 6
1. Insert
2. Delete
3. Search
4. Display
5. Exit
Enter your choice: 1
Enter element to insert: 13
1. Insert
2. Delete
3. Search
4. Display
5. Exit
Enter your choice: 4
Linked list Elements : 13 6 19 55 22
1. Insert
2. Delete
3. Search
4. Display
5. Exit
Enter your choice: 2
Enter element to delete: 55
1. Insert
2. Delete
3. Search
4. Display
5. Exit
Enter your choice: 4
Linked list Elements : 13 6 19 22
1. Insert
2. Delete
3. Search
4. Display
5. Exit
Enter your choice: 3
Enter element to search: 23
Element not found
Program 2: Operation on doubly linked list
Program:
#include <stdio.h>
#include <stdlib.h>

// Structure for a node in the doubly linked list


struct Node {
int data;
struct Node* prev;
struct Node* next;
};

// Function to create a new node


struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the beginning of the list


struct Node* insertAtBeginning(struct Node* head, int value) {
struct Node* newNode = createNode(value);
if (head == NULL) {
head = newNode;
} else {
newNode->next = head;
head->prev = newNode;
head = newNode;
}
return head;
}

// Function to insert a node at the end of the list


struct Node* insertAtEnd(struct Node* head, int value) {
struct Node* newNode = createNode(value);
if (head == NULL) {
head = newNode;
} else {
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}
return head;
}
// Function to delete a node with a given value from the list
struct Node* deleteNode(struct Node* head, int value) {
struct Node* current = head;
struct Node* temp;

if (current != NULL && current->data == value) {


temp = current;
head = current->next;
if (head != NULL) {
head->prev = NULL;
}
free(temp);
return head;
}

while (current != NULL && current->data != value) {


temp = current;
current = current->next;
}

if (current == NULL) {
printf("Value not found in the list.\n");
return head;
}

temp->next = current->next;
if (current->next != NULL) {
current->next->prev = temp;
}
free(current);
return head;
}

// Function to display the doubly linked list


void displayList(struct Node* head) {
printf("Doubly Linked List: ");
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}

int main() {
struct Node* head = NULL;
int choice, value;

do {
printf("\nSelect an operation:\n");
printf("1. Insert at the beginning\n");
printf("2. Insert at the end\n");
printf("3. Delete a node\n");
printf("4. Display the list\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the value to insert at the beginning: ");
scanf("%d", &value);
head = insertAtBeginning(head, value);
break;
case 2:
printf("Enter the value to insert at the end: ");
scanf("%d", &value);
head = insertAtEnd(head, value);
break;
case 3:
printf("Enter the value to delete: ");
scanf("%d", &value);
head = deleteNode(head, value);
break;
case 4:
displayList(head);
break;
case 5:
printf("Exiting the program. Goodbye!\n");
break;
default:
printf("Invalid choice. Please enter a valid option.\n");
}
} while (choice != 5);

return 0;
}

Output:
Select an operation:
1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Exit
Enter your choice: 1
Enter the value to insert at the beginning: 19
Select an operation:
1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Exit
Enter your choice: 4
Doubly Linked List: 19 -> 25 -> NULL

Select an operation:
1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Exit
Enter your choice: 2
Enter the value to insert at the end: 6
Select an operation:
1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Exit
Enter your choice: 4
Doubly Linked List: 19 -> 25 -> 6 -> NULL

Select an operation:
1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Exit
Enter your choice: 3
Enter the value to delete: 25
Select an operation:
1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Exit
Enter your choice: 4
Doubly Linked List: 19 -> 6 -> NULL

Select an operation:
1. Insert at the beginning
2. Insert at the end
3. Delete a node
4. Display the list
5. Exit
Enter your choice:
MARATHWADA INSTITUTE OF TECHNOLOGY, LABORATORY
AURANGABAD
PRACTICAL EXPERIMENT INSTRUCTION SHEET
Experiment Title: Write a program in C to perform operations on
BST

DEPARTMENT: CS&IT[PG] LABORATORY: PG LAB


Experiment No: 5 YEAR:2023-24
Class:MSc[IT] FY PART:I SUBJECT: Data Structure Lab

Aim: Write a program in C to perform operations on BST


Binary Search Tree | Set 1 (Search and Insertion)
The following is the definition of Binary Search Tree(BST)
Binary Search Tree is a node-based binary tree data structure which has the following
properties:
• The left subtree of a node contains only nodes with keys lesser than the node’s key.
• The right subtree of a node contains only nodes with keys greater than the node’s key.
• The left and right subtree each must also be a binary search
tree. There must be no duplicate nodes.

Algorithm:
Insert:
insert(root, value)
if root is NULL
return createNode(value)

if value < root->data


root->left = insert(root->left, value)
else
root->right = insert(root->right, value)
return root
Traverse(Inorder):
inorderTraversal(root)
if root is not NULL
inorderTraversal(root->left)
print root->data
inorderTraversal(root->right)

Program:
#include <stdio.h>
#include <stdlib.h>

// Structure for a node in the Binary Search Tree


struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Function to create a new node


struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Function to insert a new node in the Binary Search Tree


struct Node* insert(struct Node* root, int value) {
if (root == NULL) {
return createNode(value);
}

if (value < root->data) {


root->left = insert(root->left, value);
} else {
root->right = insert(root->right, value);
}

return root;
}

// Function to perform inorder traversal in the Binary Search Tree


void inorderTraversal(struct Node* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d -> ", root->data);
inorderTraversal(root->right);
}
}

int main() {
struct Node* root = NULL;
int choice, value;

do {
printf("\nSelect an operation:\n");
printf("1. Insert an element\n");
printf("2. Traverse the tree (Inorder)\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &value);
root = insert(root, value);
break;
case 2:
printf("Inorder Traversal (Sorted Order): ");
inorderTraversal(root);
printf("\n");
break;
case 3:
printf("Exiting the program. Goodbye!\n");
break;
default:
printf("Invalid choice. Please enter a valid option.\n");
}
} while (choice != 3);

return 0;
}

Output:
Select an operation:
1. Insert an element
2. Traverse the tree (Inorder)
3. Exit
Enter your choice: 1
Enter the value to insert: 8
Select an operation:
1. Insert an element
2. Traverse the tree (Inorder)
3. Exit
Enter your choice: 1
Enter the value to insert: 3
Select an operation:
1. Insert an element
2. Traverse the tree (Inorder)
3. Exit
Enter your choice: 1
Enter the value to insert: 10
Select an operation:
1. Insert an element
2. Traverse the tree (Inorder)
3. ExitEnter your choice: 1
Enter the value to insert: 1
Select an operation:
1. Insert an element
2. Traverse the tree (Inorder)
3. Exit
Enter your choice: 1
Enter the value to insert: 6
Select an operation:
1. Insert an element
2. Traverse the tree (Inorder)
3. Exit
Enter your choice: 1
Enter the value to insert: 14
Select an operation:
1. Insert an element
2. Traverse the tree (Inorder)
3. Exit
Enter your choice: 1
Enter the value to insert: 4
Select an operation:
1. Insert an element
2. Traverse the tree (Inorder)
3. Exit
Enter your choice: 1
Enter the value to insert: 7
Select an operation:
1. Insert an element
2. Traverse the tree (Inorder)
3. Exit
Enter your choice: 1
Enter the value to insert: 13
Select an operation:
1. Insert an element
2. Traverse the tree (Inorder)
3. Exit
Enter your choice: 2
Inorder Traversal (Sorted Order): 1 -> 3 -> 4 -> 6 -> 7 -> 8 -
> 10 -> 13 -> 14 ->
MARATHWADA INSTITUTE OF TECHNOLOGY, LABORATORY
AURANGABAD
PRACTICAL EXPERIMENT INSTRUCTION SHEET
Experiment Title: Write a program in C to convert infix expression to postfix
expression

DEPARTMENT: CS&IT[PG] LABORATORY: PG LAB


Experiment No: 6 YEAR:2023-24
Class:MSc[IT] FY PART:I SUBJECT: Data Structure Lab

Aim: Write a program in C to convert infix expression to postfix expression


Infix, Postfix and Prefix notations are three different but equivalent ways of writing expressions. It is
easiest to demonstrate the differences by looking at examples of operators that take two operands.

Infix notation: X + Y
Operators are written in-between their operands. This is the usual way we write expressions. An expression
such as A * ( B + C ) / D is usually taken to mean something like: "First add B and C together, then
multiply the result by A, then divide by D to give the final answer."
Infix notation needs extra information to make the order of evaluation of the operators clear: rules built
into the language about operator precedence and associativity, and brackets ( ) to allow users to override
these rules. For example, the usual rules for associativity say that we perform operations from left to right,
so the multiplication by A is assumed to come before the division by D. Similarly, the usual rules for
precedence say that we perform multiplication and division before we perform addition and subtraction.

Postfix notation (also known as "Reverse Polish notation"): X Y +


Operators are written after their operands. The infix expression given above is equivalent to A B C + * D /
The order of evaluation of operators is always left-to-right, and brackets cannot be used to change this
order. Because the "+" is to the left of the "*" in the example above, the addition must be performed before
the multiplication.
Operators act on values immediately to the left of them. For example, the "+" above uses the "B" and "C".
We can add (totally unnecessary) brackets to make this explicit:
( (A (B C +) *) D /)
Thus, the "*" uses the two values immediately preceding: "A", and the result of the addition. Similarly, the
"/" uses the result of the multiplication and the "D".

Prefix notation (also known as "Polish notation"): + X Y


Operators are written before their operands. The expressions given above are equivalent to / * A + B C D
As for Postfix, operators are evaluated left-to-right and brackets are superfluous. Operators act on the two
nearest values on the right. I have again added (totally unnecessary) brackets to make this clear:
(/ (* A (+ B C) ) D)
Algorithm:
infixToPostfix(exp)
Create an empty stack s
Allocate memory for the postfix expression postfix
Initialize i to 0 (infix traversal) and j to 0 (postfix addition)
Initialize temp as a temporary character

While exp[i] is not '\0'


If exp[i] is an operand (alphabets)
Add exp[i] to postfix[j]
Increment i and j
Else if exp[i] is an opening parenthesis '('
Push '(' onto the stack s
Increment i
Else if exp[i] is a closing parenthesis ')'
While the top of stack s is not '('
Pop from stack s and add the popped character to postfix[j]
Increment j
Pop '(' from stack s
Increment i
Else (exp[i] is an operator)
While stack s is not empty and precedence(exp[i]) <= precedence(s->items[s->top])
Pop from stack s and add the popped character to postfix[j]
Increment j
Push exp[i] onto stack s
Increment i

While stack s is not empty


Pop from stack s and add the popped character to postfix[j]
Increment j

Null-terminate postfix[j]
Print "Postfix: " followed by the postfix expression

Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 100


// Stack type
struct Stack {
int top;
char items[MAX];
};

// Stack Operations
void push(struct Stack* s, char x) {
s->items[++s->top] = x;
}

char pop(struct Stack* s) {


return s->items[s->top--];
}

int precedence(char x) {
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}

// Infix to Postfix conversion


void infixToPostfix(char* exp) {

struct Stack* s = (struct Stack*)malloc(sizeof(struct Stack));


s->top = -1;

char* postfix = (char*)malloc((strlen(exp) + 1) * sizeof(char));

int i = 0; // Track infix traversal


int j = 0; // Track postfix addition

char temp; // Temporary character

while(exp[i] != '\0') {
// If operand, add to postfix
if(exp[i] >= 'a' && exp[i] <= 'z' || exp[i] >= 'A' && exp[i] <= 'Z') {
postfix[j++] = exp[i++];
}
// If opening brace, push to stack
else if(exp[i] == '(') {
push(s, exp[i]);
i++;
}
// If closing brace, pop from stack until matching opening brace
else if(exp[i] == ')') {
while((temp = pop(s)) != '(')
postfix[j++] = temp;
i++;
}
// If operator
else {
while(s->top != -1 && precedence(exp[i]) <= precedence(s->items[s->top]))
postfix[j++] = pop(s);
push(s, exp[i++]);
}
}

// Pop any remaining operators from stack


while(s->top != -1) {
postfix[j++] = pop(s);
}

postfix[j] = '\0'; // Null terminate postfix expression

printf("Postfix: %s", postfix);

int main() {

char* infix[100];
printf("Enter the infix Expression: \n");
scanf("%s",&infix);
infixToPostfix(infix);

return 0;
}

Output:
Enter the infix Expression:
a+b-c
Postfix: ab+c-
MARATHWADA INSTITUTE OF TECHNOLOGY, LABORATORY
AURANGABAD
PRACTICAL EXPERIMENT INSTRUCTION SHEET
Experiment Title: write a program to traverse a graph using BFS with an
adjacency matrix

DEPARTMENT: CS&IT[PG] LABORATORY: PG LAB


Experiment No: 7 YEAR:2023-24
Class:MSc[IT] FY PART:I SUBJECT: Data Structure Lab

Aim: Write a program to traverse a graph using BFS with an adjacency matrix

Breadth First Search is a traversal technique in which we traverse all the nodes of the graph in a breadth-
wise motion. In BFS, we traverse one level at a time and then jump to the next level. In a graph, the
traversal can start from any node and cover all the nodes level-wise. The BFS algorithm makes use of the
queue data structure for implementation.

The breadth-first search or BFS algorithm is used to search a tree or graph data structure for a node that
meets a set of criteria. It begins at the root of the tree or graph and investigates all nodes at the current
depth level before moving on to nodes at the next depth level.

Algorithm:
BFS(adjacencyMatrix, source, nodes)
Create an empty queue using createQueue()
Initialize an array 'visited' of size nodes to keep track of visited nodes, initially set all values to 0
Enqueue the source node into the queue and mark it as visited
Print "Breadth First Search Traversal: "

While the queue is not empty


Dequeue a node 'current' from the queue
Print 'current'

For each adjacent node 'i' of 'current' in the adjacency matrix


If there is an edge from 'current' to 'i' and 'i' is not visited
Mark 'i' as visited
Enqueue 'i' into the queue
(End of While loop)
(End of BFS)
Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NODES 100

struct Queue {
int items[MAX_NODES];
int front;
int rear;
};

struct Queue* createQueue() {


struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = -1;
queue->rear = -1;
return queue;
}

int isFull(struct Queue* queue) {


return (queue->rear == MAX_NODES - 1);
}

int isEmpty(struct Queue* queue) {


return (queue->front == -1 || queue->front > queue->rear);
}

void enqueue(struct Queue* queue, int value) {


if (isFull(queue))
return;
if (queue->front == -1)
queue->front = 0;
queue->items[++queue->rear] = value;
}

int dequeue(struct Queue* queue) {


if (isEmpty(queue))
return -1;
return queue->items[queue->front++];
}

void BFS(int adjacencyMatrix[MAX_NODES][MAX_NODES], int source, int nodes) {


struct Queue* queue = createQueue();
int visited[MAX_NODES] = {0};
int i, current;

visited[source] = 1;
enqueue(queue, source);

printf("Breadth First Search Traversal: ");

while (!isEmpty(queue)) {
current = dequeue(queue);
printf("%d ", current);

for (i = 0; i < nodes; i++) {


if (adjacencyMatrix[current][i] && !visited[i]) {
visited[i] = 1;
enqueue(queue, i);
}
}
}
}

int main() {
int adjacencyMatrix[MAX_NODES][MAX_NODES];
int nodes, edges, source;
int i, j;

printf("Enter the number of nodes: ");


scanf("%d", &nodes);

printf("Enter the adjacency matrix:\n");


for (i = 0; i < nodes; i++) {
for (j = 0; j < nodes; j++) {
scanf("%d", &adjacencyMatrix[i][j]);
}
}

printf("Enter the source node for BFS traversal: ");


scanf("%d", &source);

BFS(adjacencyMatrix, source, nodes);

return 0;
}

Output:
Enter the number of nodes: 5
Enter the adjacency matrix:
0 1 0 0 0
1 0 1 0 1
0 1 0 1 0
0 0 1 0 1
0 1 0 1 0
Enter the source node for BFS traversal: 3
Breadth First Search Traversal: 3 2 4 1 0
MARATHWADA INSTITUTE OF TECHNOLOGY, LABORATORY
AURANGABAD
PRACTICAL EXPERIMENT INSTRUCTION SHEET
Experiment Title: Write a program to traverse a graph using DFS with an
adjacency matrix

DEPARTMENT: CS&IT[PG] LABORATORY: PG LAB


Experiment No: 08 YEAR:2023-24
Class:MSc[IT] FY PART:I SUBJECT: Data Structure Lab

Aim: Write a program to traverse a graph using DFS with an adjacency matrix

The depth-first search (DFS) algorithm starts with the initial node of graph G and goes deeper until we find
the goal node or the node with no children. Because of the recursive nature, stack data structure can be
used to implement the DFS algorithm
Depth First Search is an algorithm used to search the Tree or Graph. DFS search starts from root node then
traversal into left child node and continues, if item found it stops otherwise it continues.

Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. The
algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and
explores as far as possible along each branch before backtracking.

Algorithm:
DFS(adjacencyMatrix, source, nodes)
Create an empty stack using createStack()
Initialize an array 'visited' of size nodes to keep track of visited nodes, initially set all values to 0
Push the source node onto the stack and mark it as visited
Print "Depth First Search Traversal: "

While the stack is not empty


Pop a node 'current' from the stack
Print 'current'

For each adjacent node 'i' of 'current' in the adjacency matrix


If there is an edge from 'current' to 'i' and 'i' is not visited
Mark 'i' as visited
Push 'i' onto the stack
Print 'i'
Break (exit the loop to explore the next node)

If no unvisited adjacent node is found, pop from the stack (backtrack)

(End of While loop)

(End of DFS)

Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NODES 100
struct Stack {
int items[MAX_NODES];
int top;
};
struct Stack* createStack() {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->top = -1;
return stack;
}
int isFull(struct Stack* stack) {
return stack->top == MAX_NODES - 1;
}
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
void push(struct Stack* stack, int value) {
if (isFull(stack))
return;
stack->items[++stack->top] = value;
}
int pop(struct Stack* stack) {
if (isEmpty(stack))
return -1;
return stack->items[stack->top--];
}
void DFS(int adjacencyMatrix[MAX_NODES][MAX_NODES], int source, int nodes) {
struct Stack* stack = createStack();
int visited[MAX_NODES] = {0};
int i, current;
printf("Depth First Search Traversal: ");
visited[source] = 1;
push(stack, source);
printf("%d ", source);
while (!isEmpty(stack)) {
current = stack->items[stack->top];
int flag = 0;
for (i = 0; i < nodes; i++) {
if (adjacencyMatrix[current][i] && !visited[i]) {
visited[i] = 1;
push(stack, i);
printf("%d ", i);
flag = 1;
break;
}
}
if (!flag)
pop(stack);
}
}
int main() {
int adjacencyMatrix[MAX_NODES][MAX_NODES];
int nodes, edges, source;
int i, j;
printf("Enter the number of nodes: ");
scanf("%d", &nodes);
printf("Enter the adjacency matrix:\n");
for (i = 0; i < nodes; i++) {
for (j = 0; j < nodes; j++) {
scanf("%d", &adjacencyMatrix[i][j]);
}
}
printf("Enter the source node for DFS traversal: ");
scanf("%d", &source);
DFS(adjacencyMatrix, source, nodes);
return 0;
}

Output:
Enter the number of nodes: 5
Enter the adjacency matrix:
0 1 0 0 0
1 0 1 0 1
0 1 0 1 0
0 0 1 0 1
0 1 0 1 0
Enter the source node for DFS traversal: 3
Depth First Search Traversal: 3 2 1 0 4
MARATHWADA INSTITUTE OF TECHNOLOGY, LABORATORY
AURANGABAD
PRACTICAL EXPERIMENT INSTRUCTION SHEET
Experiment Title: Write a program to implement the Bubble sort, Insertion
sort techniques.

DEPARTMENT: CS&IT[PG] LABORATORY: PG LAB


Experiment No: 09 YEAR:2023-24
Class:MSc[IT] FY PART:I SUBJECT: Data Structure Lab

Aim: Write a program to implement the Bubble sort, Insertion sort techniques.

A Sorting Algorithm is used to rearrange a given array or list of elements according to a comparison
operator on the elements. The comparison operator is used to decide the new order of elements in the
respective data structure.

Bubble Sort:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if
they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case
time complexity is quite high.

Bubble Sort Algorithm


In Bubble Sort algorithm,
 Traverse from left and compare adjacent elements and the higher one is placed at right side.
 In this way, the largest element is moved to the rightmost end at first.
 This process is then continued to find the second largest and place it and so on until the data is
sorted.

bubbleSort(array, size)
Repeat the following steps for i = 0 to size - 2
Repeat the following steps for j = 0 to size - i - 2
If array[j] > array[j + 1]
Swap array[j] and array[j + 1]

(End of outer loop)

(End of bubbleSort)

Program:
/*Program to implement the bubble sort*/
#include <stdio.h>
void bubbleSort(int array[], int size) {
int temp, i, j;
for (i = 0; i < size - 1; i++) {
for (j = 0; j < size - i - 1; j++) {
if (array[j] > array[j + 1]) {
// Swap the elements
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}

int main() {
int size;
printf("Enter the number of elements: ");
scanf("%d", &size);

int array[size];

printf("Enter %d elements:\n", size);


for (int i = 0; i < size; i++) {
scanf("%d", &array[i]);
}
printf("Original array: ");
printArray(array, size);
bubbleSort(array, size);
printf("Sorted array (in ascending order): ");
printArray(array, size);

return 0;
}

Output:
Enter the number of elements: 10
Enter 10 elements:
55
-2
98
5
6
3
45
15
22
1
Original array: 55 -2 98 5 6 3 45 15 22 1
Sorted array (in ascending order): -2 1 3 5 6 15 22 45 55 98
Insertion Sort:
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your
hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are
picked and placed at the correct position in the sorted part.

Insertion Sort Algorithm


To sort an array of size N in ascending order iterate over the array and compare the current element (key)
to its predecessor, if the key element is smaller than its predecessor, compare it to the elements before.
Move the greater elements one position up to make space for the swapped element.

insertionSort(arr, size)
Repeat the following steps for i = 1 to size - 1
Set key as arr[i]
Set j as i - 1

// Move elements of arr[0..i-1] that are greater than key to one position ahead of their current position
Repeat the following steps while j >= 0 and arr[j] > key
Set arr[j + 1] as arr[j]
Decrement j by 1

Set arr[j + 1] as key

(End of outer loop)

(End of insertionSort)

Program:
#include <stdio.h>

void insertionSort(int arr[], int size) {


int i, key, j;
for (i = 1; i < size; i++) {
key = arr[i];
j = i - 1;

// Move elements of arr[0..i-1] that are greater than key to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {12, 11, 13, 5, 6};
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is: ");


printArray(arr, arr_size);

insertionSort(arr, arr_size);

printf("Sorted array is: ");


printArray(arr, arr_size);

return 0;
}

Output:
Given array is: 12 11 13 5 6
Sorted array is: 5 6 11 12 13
MARATHWADA INSTITUTE OF TECHNOLOGY, LABORATORY
AURANGABAD
PRACTICAL EXPERIMENT INSTRUCTION SHEET
Experiment Title: Write a program to implement Hashing functions

DEPARTMENT: CS&IT[PG] LABORATORY: PG LAB


Experiment No: 10 YEAR:2023-24
Class:MSc[IT] FY PART:I SUBJECT: Data Structure Lab

Aim: Write a program to implement Hashing

Hashing is the process of generating a value from a text or a list of numbers using a mathematical
function known as a hash function.

A Hash Function is a function that converts a given numeric or alphanumeric key to a small practical
integer value. The mapped integer value is used as an index in the hash table. In simple terms, a hash
function maps a significant number or string to a small integer that can be used as the index in the hash
table.

The pair is of the form (key, value), where for a given key, one can find a value using some kind of a
“function” that maps keys to values. The key for a given object can be calculated using a function called a
hash function. For example, given an array A, if i is the key, then we can find the value by simply looking
up A[i].

Algorithm:
1. Define SIZE constant for table size
2. Define Data struct to store key-value pairs
3. Declare hashArray of SIZE to store pointers to Data
4. Define hashCode() function: 4.1 Accept key as parameter 4.2 Calculate hash using key%SIZE 4.3
Return hash index
5. Define search() function: 5.1 Calculate hash index of key 5.2 Traverse linked list at that index 5.3 If
key matches return Data pointer 5.4 Else return NULL
6. Define insert() function: 6.1 Create new Data item
6.2 Set key and value 6.3 Calculate hash index 6.4 Traverse chain to find empty slot 6.5 Insert item at
empty slot
7. Define display(): 7.1 Iterate over hashArray 7.2 Print index, key and value
8. In main(): 8.1 Insert items 8.2 Display table 8.3 Search for key 8.4 Print search result
9. End

Program:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10

struct Data {
int key;
int value;
};

struct Data* hashArray[SIZE];


struct Data* dummyItem;
struct Data* item;

int hashCode(int key) {


return key % SIZE;
}

struct Data *search(int key) {


int hashIndex = hashCode(key);

while (hashArray[hashIndex] != NULL) {


if (hashArray[hashIndex]->key == key) {
return hashArray[hashIndex];
}
++hashIndex;
hashIndex %= SIZE;
}
return NULL;
}

void insert(int key, int value) {


struct Data *item = (struct Data*) malloc(sizeof(struct Data));
item->value = value;
item->key = key;

int hashIndex = hashCode(key);

while (hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1) {


++hashIndex;
hashIndex %= SIZE;
}
hashArray[hashIndex] = item;
}

void display() {
int i;
printf("Index\tKey\tValue\n");
for (i = 0; i < SIZE; i++) {
if (hashArray[i] != NULL) {
printf("%d\t%d\t%d\n", i, hashArray[i]->key, hashArray[i]->value);
} else {
printf("%d\t---\t---\n", i);
}
}
}

int main() {
dummyItem = (struct Data*) malloc(sizeof(struct Data));
dummyItem->value = -1;
dummyItem->key = -1;

insert(1, 20);
insert(2, 70);
insert(42, 80);
insert(4, 25);
insert(12, 44);
insert(14, 32);
insert(17, 11);
insert(13, 78);
insert(37, 97);

display();

int keyToSearch;
printf("Enter the key to search: ");
scanf("%d", &keyToSearch);

item = search(keyToSearch);
if (item != NULL) {
printf("Element found: %d\n", item->value);
} else {
printf("Element not found\n");
}

return 0;
}

Output:
Index Key Value Index Key Value
0 --- --- 0 --- ---
1 1 20
1 1 20
2 2 70
2 2 70 3 42 80
3 42 80 4 4 25
4 4 25 5 12 44
5 12 44 6 14 32
6 14 32 7 17 11
7 17 11 8 13 78
8 13 78 9 37 97
9 37 97 Enter the key to search: 12
Enter the key to search: Element
22 found: 44
Element not found

You might also like