DS Lab Manual by Prof Abhijeet Jadhav
DS Lab Manual by Prof Abhijeet Jadhav
DS Lab Manual by Prof Abhijeet Jadhav
AURANGABAD
PRACTICAL EXPERIMENT INSTRUCTION SHEET
Experiment Title: Write a program to demonstrate insertion, deletion, search and
displaying of an element in anArray.
a[4]=23
a[4] a[4]=21
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
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
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
if (position == -1) {
printf("Element not found. Deletion failed.\n");
return 0; // Deletion failed
}
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.
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).
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.
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
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) {
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:
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.
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
Search:
Search()
Read key from the user
Program:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
free(temp);
}
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");
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>
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;
}
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
Algorithm:
Insert:
insert(root, value)
if root is NULL
return createNode(value)
Program:
#include <stdio.h>
#include <stdlib.h>
return root;
}
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
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.
Null-terminate postfix[j]
Print "Postfix: " followed by the postfix expression
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Stack Operations
void push(struct Stack* s, char x) {
s->items[++s->top] = x;
}
int precedence(char x) {
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
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++]);
}
}
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
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: "
struct Queue {
int items[MAX_NODES];
int front;
int rear;
};
visited[source] = 1;
enqueue(queue, source);
while (!isEmpty(queue)) {
current = dequeue(queue);
printf("%d ", current);
int main() {
int adjacencyMatrix[MAX_NODES][MAX_NODES];
int nodes, edges, source;
int i, j;
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
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: "
(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.
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.
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 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];
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.
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
(End of insertionSort)
Program:
#include <stdio.h>
// 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;
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6};
int arr_size = sizeof(arr) / sizeof(arr[0]);
insertionSort(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
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;
};
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