Data Structure Lab Manual
Data Structure Lab Manual
DATE :
AIM:
To write a C program for the implementation of Stack using Array.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
void main()
{
clrscr();
top=-1;
printf("Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\nSTACK OPERATIONS USING ARRAY");
printf("\n1.PUSH\t 2.POP\t 3.DISPLAY\t 4.EXIT");
do
{
printf("\nEnter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\nEXIT POINT ");
break;
}
default:
{
printf ("\nPlease Enter a Valid Choice(1/2/3/4)");
}
}
}
while(choice!=4);
}
void push()
{
}
void pop()
{
}
void display()
{
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully
EXP NO: 1B ARRAY IMPLEMENTATION OF QUEUE
DATE :
AIM:
To write a C program for the implementation of Queue using Array.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,queue[100],ch=1,front=0,rear=0,i,j=1;
clrscr();
printf("Enter the size of Queue : \n");
scanf("%d",&n);
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
}
}
}
getch();
}
OUTPUT:
RESULT:
DATE :
AIM:
To write a C program for the implementation of Circular Queue using Array.
ALGORITHM:
PROGRAM:
#include <stdio.h>
# define max 6
int queue[max]; // array declaration
int front=-1;
int rear=-1;
// function to insert an element in a circular queue
void enqueue(int element)
{
}
// function to display the elements of a queue
void display()
{
}
int main()
{
int choice=1,x; // variables declaration
switch(choice)
{
case 1:
printf("Enter the element which is to be inserted");
scanf("%d", &x);
enqueue(x);
break;
case 2:
dequeue();
break;
case 3:
display();
}}
return 0;
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully
VIVA-VOCE
2. What are the advantages of implementing a stack using a linked list over an array? (Wipro)
• Dynamic size: No fixed limit; grows as needed.
• No overflow (unless system memory is full).
• Efficient push/pop: Constant time operations (O(1)).
3. What is the time and space complexity of stack operations using a linked list? (Capgemini)
• Push / Pop / Peek: O(1) time
• Space: O(n), where n is the number of elements
4. What challenges might arise when using a linked list for stack implementation? (Cognizant)
• Requires extra memory for pointers in each node
• Slight overhead due to dynamic memory allocation
• Risk of memory leaks if nodes are not properly freed
6. What are the benefits of using a linked list to implement a queue? (HCL Technologies)
• Dynamic size: No need to define max size in advance
• No shifting or wasted space (as in arrays)
• Efficient O(1) enqueue and dequeue using rear and front pointers
7. What is the time complexity of queue operations using a linked list? (Tech Mahindra)
• Enqueue: O(1)
• Dequeue: O(1)
• Traversal (optional): O(n)
8. What is the difference between array and linked list implementations of a queue? (Mindtree)
10. Give a real-world application where a linked list-based queue is preferred. (IBM)
Job/task scheduling systems, where the number of jobs is unknown and may vary widely, benefit
from a dynamically resizing queue—ideal for linked list implementation.
EXP NO : 2 IMPLEMENTATION OF SINGLY LINKED LIST
DATE :
AIM:
To write a C program for the implementation of List using Linked List.
ALGORITHM:
struct node
{
int data;
struct node *next;
};
int main ()
{
int input,
data;clrscr();
for (;;)
{
printf("1. Insert an element at beginning of linked
list.\n");printf("2. Insert an element at end of linked
list.\n"); printf("3. Insert an element after a given
node.\n"); printf("4. Insert an element before a given
node.\n"); printf("5. Traverse linked list.\n");
printf("6. Delete element from
beginning.\n"); printf("7. Delete element
from end.\n"); printf("8. Delete element
after given node.\n"); printf("9. Exit\n");
printf("Enter option
:\n"); scanf("%d",
&input);
if (input == 1)
{
printf("Enter value of
element\n"); scanf("%d",
&data); insert_at_begin(data);
}
else if (input == 2)
{
printf("Enter value of
element\n"); scanf("%d",
&data); insert_at_end(data);
}
else if (input == 3)
{
printf("Enter
data:");
scanf("%d",&data)
; insert_after(data);
}
else if (input == 4)
{
printf("Enter
data:");
scanf("%d",&data)
;
insert_before(data)
;
}
else if (input ==
5)traverse();
else if (input == 6)
delete_from_begin();
else if (input == 7)
delete_from_end(
);
else if (input ==
8)
delete_after()
;
else if (input ==
9)break;
else
printf("Please enter valid input.\n");
}
getch();
return
0;
}
void insert_at_begin(int x)
{
}
void insert_at_end(int x)
{
void insert_after(int x)
{
}
void insert_before(int x)
{
void traverse()
{
}
void delete_from_begin()
{
}
void delete_from_end()
{
void delete_after()
{
}
OUTPUT:
RESULT:
4. What are the main operations supported by a singly linked list? (Capgemini)
• Insertion: At beginning, end, or specific position.
• Deletion: From beginning, end, or a specific node.
• Traversal: Visiting each node to access or print data.
• Search: Finding a node with a specific value.
5. What is the time complexity of insertion and deletion operations in a singly linked list? (HCL
Technologies)
• Insertion at beginning: O(1)
• Insertion at end or at specific position: O(n)
• Deletion at beginning: O(1)
• Deletion at specific position or end: O(n)
8. What happens if you try to access the next pointer of the last node? (Mindtree)
You get a NULL pointer, as the last node’s next points to NULL, indicating the end of the list.
9. How can you detect the end of a singly linked list during traversal? (L&T Infotech)
By checking if the next pointer of a node is NULL. This condition means you've reached the last
node.
10. Give a real-life example where a singly linked list would be useful. (IBM)
A music playlist where each song points to the next one, or a chain of web pages in browsing history,
where only the forward path is tracked
EXP NO : 3A LINKED LIST IMPLEMENTATION OF STACK
DATE :
AIM:
To write a C program for the implementation of Stack using Linked List.
ALGORITHM:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
int topelement();
void push(int data);
void pop();
void display();
void create();
void main()
{
int no, ch, e;
clrscr();
printf("Linked list Representation of Stack");
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Dipslay");
printf("\n 4 - Top_Element");
printf("\n 5 - Exit");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
if (top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 5:exit(0);
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
getch();
}
//Pop Operation
void pop()
{
}
//Return top element
int topelement()
{
return(top->info);
}
OUTPUT:
RESULT:
AIM:
To write a C program for the implementation of Queue using Linked List.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
struct Node
{
int data;
struct Node *next;
}*front = NULL,*rear = NULL;
void insert(int);
void delete();
void display();
void main()
{
int choice, value;
clrscr();
printf("Queue Implementation using Linked List\n");
while(1)
{
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the value to be insert: ");
scanf("%d", &value);
insert(value);
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\nWrong selection..Please try again\n");
}
}
getch();
}
void delete()
{
}
void display()
{
OUTPUT:
RESULT:
4. What are the main operations supported by a singly linked list? (Capgemini)
• Insertion: At beginning, end, or specific position.
• Deletion: From beginning, end, or a specific node.
• Traversal: Visiting each node to access or print data.
• Search: Finding a node with a specific value.
5. What is the time complexity of insertion and deletion operations in a singly linked list? (HCL
Technologies)
• Insertion at beginning: O(1)
• Insertion at end or at specific position: O(n)
• Deletion at beginning: O(1)
• Deletion at specific position or end: O(n)
8. What happens if you try to access the next pointer of the last node? (Mindtree)
You get a NULL pointer, as the last node’s next points to NULL, indicating the end of the list.
9. How can you detect the end of a singly linked list during traversal? (L&T Infotech)
By checking if the next pointer of a node is NULL. This condition means you've reached the last
node.
10. Give a real-life example where a singly linked list would be useful. (IBM)
A music playlist where each song points to the next one, or a chain of web pages in browsing history,
where only the forward path is tracked.
EXP NO : 4 IMPLEMENTATION OF POLYNOMIAL MANIPULATION USING
LINKED LIST
DATE :
AIM:
To write a C program for the implementation of polynomial representation as the application of
list ADT.
ALGORITHM:
Step 1: Start the program.
Step 2:Include the necessary header files.
Step 3:Create a structure with coefficient, power and link.
Step 4:In main function, declare necessary variables and functions.
Step 5: Create memory for two polynomials to get necessary coefficient and power values.
Step 6: Perform addition with two polynomials where the power values are same and store it in
another location.
Step 7: Display the values with necessary operators.
Step 8: Stop the program.
PROGRAM:
#include<stdio.h>
#include<stdio.h>
#include<stdlib.h>
struct link
{
int coeff;
int pow;
struct link *next;
};
}
}
}
}
int main()
{
clrscr();
poly1=(struct link*)malloc(sizeof(struct link));
poly2=(struct link*)malloc(sizeof(struct link));
poly=(struct link*)malloc(sizeof(struct link));
printf(“\n Enter the first polynomial:\n”);
create(poly1);
printf(“\n First polynomial:\n”);
display(poly1);
printf(“\n Enter the second polynomial:\n”);
create(poly2);
printf(“\n Second polynomial:\n”);
display(poly2);
polyadd(poly1,poly2,poly);
printf(“\n Addition of two polynomial: \n”);
display(poly);
getch();
return 0;
}
OUTPUT:
RESULT:
1.What is the need to represent polynomials using linked lists instead of arrays? ( TCS)
Arrays require a fixed size and store every exponent index, even if the coefficient is zero (sparse
data). Linked lists allow dynamic memory usage and efficient representation of only non-zero terms.
2. How do you represent a polynomial using a singly linked list? ( Cognizant, Capgemini, Tech
Mahindra)
Each term of the polynomial is represented as a node containing:
Coefficient (coeff)
Power (exp)
Pointer to the next node (next)
Example for 4x³ + 3x + 2:
[4, 3] -> [3, 1] -> [2, 0] -> NULL
3. Explain the algorithm to add two polynomials using linked lists.(HCL, IBM)
4.What are the challenges in polynomial multiplication using linked list?( Mindtree, MAQ
Software, Zoho)
Requires nested traversal: for each term in the first list, multiply with each term in the second.
Need to manage insertion in sorted order and combine like terms (same exponent).
Performance bottleneck due to repeated insertions.
5.What is the time and space complexity of polynomial addition and multiplication using linked
lists?( Infosys, Hexaware, Virtusa)
7.How would you implement polynomial differentiation using linked lists?( Zoho, Infosys)
Steps:
8. Why is insertion order important in polynomial linked list representation?( Capgemini, TCS
Ninja)
For correct addition and multiplication, the polynomial must be stored in descending order of
powers. This simplifies:
Without order, you'd need to sort the list or use hash maps.
10. Compare array vs linked list implementation of polynomials.( TCS, Infosys, Wipro)
AIM:
To write a C program for the conversion of infix to postfix expression.
ALGORITHM:
Step 1: Start the program.
Step 2:Include the necessary header files.
Step 3:In main function, declare necessary variables and functions.
Step 4: Get the infix expression as input from the user.
Step 5: Push the values and symbols into the stack based on the conditions.
Step 6: Pop out the symbols to be eliminated based on the conditions.
Step 7: Display the postfix expression obtained by the push and pop operations.
Step 8: Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 20
int top=-1;
char pop();
char stack[MAX];
void push(char item);
void main()
{
char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string:\n");
gets(infix);
convertip(infix,postfix);
printf("The corresponding postfix string is:\n");
puts(postfix);
getch();
}
OUTPUT:
RESULT:
A postfix expression places operators after operands (e.g., AB+ instead of A+B). It removes the need
for parentheses and respects operator precedence naturally, making it easier for machines to evaluate
using stacks.
Operands are pushed onto the stack. When an operator is encountered, the top two operands are
popped, the operation is performed, and the result is pushed back. This continues until the entire
expression is evaluated.
4. How do precedence and associativity influence the conversion from infix to postfix?
(Cognizant)
Precedence determines the order of operations (^ > * / > + -). Associativity resolves conflicts for
same-precedence operators (e.g., ^ is right-associative; *, + are left-associative). This affects whether
we pop from the stack or not during conversion.
6. What are the advantages of postfix evaluation over infix evaluation? (Capgemini)
7. How would you handle multi-digit numbers or variables in postfix expressions? (HCL)
Use tokenization (e.g., split by space or delimiter) instead of character-by-character scanning. This
ensures that values like 12, 100, or variable names like X1 are processed correctly as whole tokens.
8. What is the time and space complexity of evaluating a postfix expression? (IBM)
9. Can infix to postfix conversion be done without using a stack? Why or why not? (TCS,
Infosys)
It's possible but inefficient. A stack offers the ideal LIFO structure for managing operators and
parentheses. Without it, simulating operator precedence and associativity would require more
complex logic and data structures.
10. Compare array vs linked list implementation of polynomials. (TCS, Infosys, Wipro)
AIM:
To write a C program for the implementation of Binary Search Tree operations.
ALGORITHM:
Step 1: Start the program.
Step 2:Include the necessary header files.
Step 3:Declare necessary variables and functions.
Step 4: Create a node structure with data, left link and right link.
Step 5: Display the options for insertion, deletion and traversal.
Step 6:Create nodes dynamically and insert values into the nodes by the following steps:
(i) Insert the root node and input the data.
(ii) If the value is less than the root value, then insert it to the left sub tree.
(iii) If the value is greater than the root value, then insert it to the right sub tree.
Step 7:Delete a node based on the following four cases:
(i) Node containing zero child.
(ii) Node containing one left child.
(iii) Node containing one right child.
(iv) Node containing two child.
Step 8: Traverse the nodes and display it by the following steps:
(i) Inorder Traversal – Visit left subtree, root node and right sub tree.
(ii) Preorder Traversal – Visit root node, left sub tree and right sub tree.
(iii) Postorder Traversal – Visit left sub tree, right sub tree and root node.
Step 9: Stop the program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;
void delete1();
void insert();
void delete();
void inorder(struct btnode *t);
void create();
void search(struct btnode *t);
void preorder(struct btnode *t);
void postorder(struct btnode *t);
void search1(struct btnode *t,int data);
int smallest(struct btnode *t);
int largest(struct btnode *t);
int flag = 1;
void main()
{
int ch;
printf("\nOPERATIONS ---");
printf("\n1 - Insert an element into tree\n");
printf("2 - Delete an element from the tree\n");
printf("3 - Inorder Traversal\n");
printf("4 - Preorder Traversal\n");
printf("5 - Postorder Traversal\n");
printf("6 - Exit\n");
while(1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
inorder(root);
break;
case 4:
preorder(root);
break;
case 5:
postorder(root);
break;
case 6:
exit(0);
default :
printf("Wrong choice, Please enter correct choice ");
break;
}
}
getch();
}
// To insert a node in the tree
void insert()
{
// To create a node
void create()
{
if (t->l != NULL)
inorder(t->l);
printf("%d -> ", t->value);
if (t->r != NULL)
inorder(t->r);
}
}
else
{
t1->r = t->l;
}
t = NULL;
free(t);
return;
}
The left subtree of a node contains only nodes with values less than the node’s value.
The right subtree contains only nodes with values greater than the node’s value.
This property enables fast search, insertion, and deletion.
Searching in a BST uses the property that left < root < right.
4. What are the time complexities of various operations in BST? (TCS, Infosys)
Best/Average Case: O(log n) for search, insertion, and deletion in a balanced BST.
Worst Case: O(n), which happens when the BST becomes skewed like a linked list.
7. What are the advantages of a BST over arrays and linked lists? (Infosys)
Faster search and insert/delete operations compared to arrays and linked lists.
Maintains elements in sorted order.
Efficient for dynamic sets of data with frequent insertions and deletions.
BSTs typically do not allow duplicates, but they can be handled by modifying the insertion
logic:
o Store duplicates in a specific subtree (e.g., always to the right), or
o Add a counter in the node to track occurrences.
9. What is the difference between a Binary Tree and a Binary Search Tree? (TCS, Wipro)
A Binary Tree is a general tree structure where each node has up to two children and no
specific order.
A Binary Search Tree maintains a sorted structure where left < root < right, allowing
efficient operations.
10. What are the limitations of using a simple BST? (TCS, Infosys, Wipro)
In worst cases (e.g., sorted input), a BST becomes skewed and behaves like a linked list.
Operations degrade to O(n).
Balancing is not automatic, so self-balancing trees (like AVL or Red-Black Trees) are
preferred for consistent performance.
EXP NO : 7 IMPLEMENTATION OF AVL TREE
DATE :
AIM:
To write a C program for the implementation of AVL Tree operations.
ALGORITHM:
Step 1: Start the program.
Step 2:Include the necessary header files.
Step 3:Declare necessary variables and functions.
Step 4: Create a node structure with data, left link and right link.
Step 5: Display the options for insertion, deletion and traversal.
Step 6: Create nodes dynamically and insert values into the nodes by the following steps:
(i) Insert the root node and input the data.
(ii) If the value is less than the root value, then insert it to the left sub tree.
(iii) If the value is greater than the root value, then insert it to the right sub tree.
Check the height of each node during insertion and if the height is not 1, 0, -1, then perform
rotations to balance the tree.
Step 7: Delete the node and balance the tree by rotations.
Step 8:The categories of rotations to be performed are as follows:
(i) LL Rotation
(ii) RR Rotation
(iii) LR Rotation
(iv) RL Rotation
Step 9: Traverse the nodes and display it by the following steps:
(i) Inorder Traversal – Visit left sub tree, root node and right sub tree.
(ii) Preorder Traversal – Visit root node, left sub tree and right sub tree.
(iii) Postorder Traversal – Visit left sub tree, right sub tree and root node.
Step 10: Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
int main()
{
node *root=NULL;
int x,n,i,op;
clrscr();
do
{
printf("\n1)Create:");
printf("\n2)Insert:");
printf("\n3)Delete:");
printf("\n4)Print:");
printf("\n5)Quit:");
printf("\n\nEnter Your Choice:");
scanf("%d",&op);
switch(op)
{
case 1:
printf("\nEnter no. of elements:");
scanf("%d",&n);
printf("\nEnter tree data:");
root=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
break;
case 2:
printf("\nEnter a data:");
scanf("%d",&x);
root=insert(root,x);
break;
case 3:
printf("\nEnter a data:");
scanf("%d",&x);
root=Delete(root,x);
break;
case 4:
printf("\nPreorder sequence:\n");
preorder(root);
printf("\n\nInorder sequence:\n");
inorder(root);
printf("\n");
break;
}
}
while(op!=5);
getch();
return 0;
}
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
if(lh>rh)
return(lh);
return(rh);
}
An AVL Tree is a self-balancing binary search tree where the difference in height between the left
and right subtrees (called the balance factor) of any node is at most 1. It maintains O(log n)
performance for insertion, deletion, and search.
In an unbalanced BST, operations like search, insert, and delete can degrade to O(n) in worst-case
scenarios (e.g., sorted data). AVL Trees ensure the tree remains balanced, keeping operations efficient
at O(log n).
4. What are the types of rotations used in AVL Trees? (TCS, Wipro)
There are four types of rotations used to restore balance in AVL Trees:
Left-Right (LR) Rotation: Used when a node is inserted into the right subtree of the left
child.
Right-Left (RL) Rotation: Used when a node is inserted into the left subtree of the right
child.
6. What is the time complexity of insertion and deletion in an AVL Tree? (TCS, Infosys)
Insertion: O(log n)
Deletion: O(log n)
This is because AVL Trees maintain balance, and tree height stays logarithmic in size.
7. What is the difference between a Binary Search Tree and an AVL Tree? (Wipro)
Yes. Insertion can cause the balance factor of one or more nodes to become less than -1 or greater
than +1. When this happens, rotations are used to restore the AVL property.
10. What are the limitations of AVL Trees? (TCS, Infosys, Wipro)
AIM:
To write a C program for the implementation of Heaps using Priority Queues.
ALGORITHM:
Step 1: Start the program.
Step 2:Include the necessary header files.
Step 3:Declare necessary variables and functions.
Step 4: Create a node structure with necessary data and link.
Step 5: Display the options for insertion, deletion of minimum and display.
Step 6:Initialize the priority queue with size and insert the elements based on the below condition:
Heap Order Property –Value of Parent(root) node should be less than child node.
Step 7: Delete the minimal node and balance it based on the Heap order property.
Step 8: Traverse the nodes and display the elements in the queue.
Step 9: Stop the program.
PROGRAM:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
struct heapnode
{
int capacity;
int size;
int *elements;
};
}
int isEmpty(struct heapnode *h)
{
void main()
{
int ch,ins,del;
struct heapnode *h;
clrscr();
printf("\nPriority Queue using Heap");
h=initialize();
printf("\nOPTIONS\n");
printf("\n1. Insert\n2. DeletMin\n3. Display\n4. Exit");
while(1)
{
OUTPUT:
RESULT:
A Priority Queue is an abstract data structure where each element has a priority. Elements with higher
priority are dequeued before others.
Heaps (usually Min or Max Heaps) are used as the underlying structure to efficiently implement
priority queues.
4. What are the types of Heaps used in Priority Queues? (TCS, Infosys)
Min-Heap: Lower priority number = higher priority. Used when the smallest element is
needed first.
Max-Heap: Higher priority number = higher priority. Used when the largest element is needed
first.
Insert the element at the end of the heap (last position in array).
Heapify-up (bubble-up): Compare with parent and swap until the heap property is restored.
8. What are real-life applications of Priority Queues implemented with Heaps? (Wipro)
CPU scheduling
Dijkstra’s shortest path algorithm
A search algorithm*
Load balancing systems
Event-driven simulations
9. What is the difference between a Priority Queue and a regular Queue? (TCS, Wipro)
10. What are the advantages and limitations of using a Heap for Priority Queue implementation?
(TCS, Infosys, Wipro)
Advantages:
AIM:
To write a C program for the Implementation of Dijkstra’s Algorithm.
.
ALGORITHM:
Step 1 : Create a set shortPath to store vertices that come in the way of the shortest path tree.
Step 2 : Initialize all distance values as INFINITE and assign distance values as 0 for source
vertex so that it is picked first.
Step 3 : Loop until all vertices of the graph are in the shortPath.
Step 3.1 : Take a new vertex that is not visited and is nearest.
Step 3.2 : Add this vertex to shortPath.
Step 3.3 : For all adjacent vertices of this vertex update distances. Now check every
adjacent vertex of V, if sum of distance of u and weight of edge is elss the update it.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10
int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully
VIVA-VOCE
Dijkstra’s Algorithm is used to find the shortest path from a single source node to all other nodes in a
weighted graph with non-negative edge weights. It is commonly applied in routing and navigation
systems.
2. What are the key data structures used in Dijkstra’s Algorithm? (Infosys)
Priority Queue or Min-Heap: To select the vertex with the smallest tentative distance
efficiently.
Distance Array: Stores the shortest known distances from the source to each vertex.
Visited Set (or Boolean array): Tracks whether the shortest path to a node has been finalized.
The priority queue ensures we always process the vertex with the smallest tentative distance. This
improves efficiency over scanning all vertices in each step, especially in sparse graphs.
Yes, Dijkstra’s Algorithm works on both directed and undirected graphs, as long as all edge weights
are non-negative.
10. What are the limitations of Dijkstra’s Algorithm? (TCS, Infosys, Wipro)
AIM:
To write a C program for the Implementation of Prim’s Algorithm.
.
ALGORITHM:
Step 1: Begin
Step 2: Create edge list of given graph, with their weights.
Step 3: Draw all nodes to create skeleton for spanning tree.
Step 4: Select an edge with lowest weight and add it to skeleton and delete edge from edge list.
Step 5: Add other edges. While adding an edge take care that the one end of the edge should
always be in the skeleton tree and its cost should be minimum.
Step 6: Repeat step 5 until n-1 edges are added.
Step 7: Return.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int G[MAX][MAX],spanning[MAX][MAX],n;
int prims();
int main()
{
int i,j,total_cost;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
printf("\nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of spanning tree=%d",total_cost);
return 0;
}
int prims()
{
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully
VIVA VOCE
A: Prim’s Algorithm is used to find a Minimum Spanning Tree (MST) for a weighted, connected,
undirected graph. The MST connects all vertices with the minimum total edge weight and no cycles.
2. What data structures are typically used to implement Prim’s Algorithm? (Infosys)
Priority Queue (Min-Heap): To select the edge with the minimum weight efficiently.
Adjacency List or Matrix: To represent the graph.
Visited Set or Boolean Array: To track vertices already included in MST.
A: No, Prim’s Algorithm requires the graph to be connected because MST is defined only for
connected graphs. For disconnected graphs, it produces a minimum spanning forest.
The priority queue helps efficiently select the next vertex with the minimum edge weight connecting
to the MST, reducing the overall time complexity of the algorithm.
8. What happens if all edges have the same weight in Prim’s Algorithm? (Wipro)
If all edges have the same weight, any spanning tree will have the same total weight, so Prim’s
Algorithm will produce one of many possible MSTs, depending on the order vertices and edges are
processed.
9. How does Prim’s Algorithm ensure no cycles are formed in the MST? (TCS, Infosys)
Prim’s Algorithm only adds edges connecting vertices not already in the MST set, so cycles are
naturally avoided.
10. What are the limitations of Prim’s Algorithm? (TCS, Infosys, Wipro)
AIM:
To write a C program for the implementation of linear search in an array.
ALGORITHM:
Step 1: Start the program.
Step 2:Include the necessary header files.
Step 3:In main function, declare necessary variables.
Step 4: The linear or sequential search is carried out for unordered list of elements.
Step 5: The initial value of position is set to null, then the search is done by the following steps:
(i) If the match is found between the value and the array element, then the position of the
element is displayed.
(ii) If the match is not found, then the value is not present in the array.
Step 6: Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int pos=-1, i=1, a[100], val, n;
clrscr();
printf("Enter the no of elements :");
scanf("%d",&n);
printf("Enter the elements:");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("Enter the value to be searched :");
scanf("%d",&val);
getch();
}
OUTPUT:
RESULT:
Thus the program is written & executed successfully
EXP NO : 11b IMPLEMENTATION OF BINARY SEARCH
DATE :
AIM:
To write a C program for the implementation of binary search in an array.
ALGORITHM:
Step 1: Start the program.
Step 2:Include the necessary header files.
Step 3:In main function, declare necessary variables.
Step 4: The binary search is carried out for sorted list of elements.
Step 5: The binary search starts from the middle and the steps are mentioned below:
(i) If the value is less than the mid value, then the element is present in the first half of the
array.
(ii) If the value is greater than the mid value, then the element is present in the second half
of the array.
Step 6: Display the location of the element if it is present in the array.
Step 7: Stop the program.
PROGRAM:
#include <stdio.h>
#include <conio.h>
int main()
{
}
OUTPUT:
RESULT:
Linear Search is a simple search algorithm that checks each element in a list sequentially until the
desired element is found or the list ends.
Binary Search is a search algorithm that finds the position of a target value within a sorted array by
repeatedly dividing the search interval in half.
3. What are the main differences between Linear Search and Binary Search? (Wipro)
4. What is the time complexity of Linear Search and Binary Search? (TCS, Infosys)
Linear Search is preferred when the list is unsorted, or when the dataset is small or when the
overhead of sorting is not justified.
The array or list must be sorted beforehand; otherwise, Binary Search will not work correctly.
Binary Search compares the target value with the middle element of the array:
8. Can Linear Search be used on linked lists? Why or why not? (Wipro)
Yes, Linear Search can be used on linked lists because it does not require random access; it can
sequentially traverse nodes.
9. Why is Binary Search not suitable for linked lists? (TCS, Infosys)
Binary Search requires random access to elements to jump to the middle, which linked lists do not
support efficiently, making it unsuitable.
10. What are the practical applications of Linear and Binary Search? (TCS, Infosys, Wipro)
AIM:
To write a C program to sort the elements of an array by insertion sort algorithm.
ALGORITHM:
Step 1: Start the program.
Step 2:Include the necessary header files.
Step 3:In main function, declare necessary variables.
Step 4: The insertion sort algorithm divides the array (list) into two sets.
(i) The first set contains the sorted values.
(ii) The second set contains the unsorted values.
Step 5: The unsorted values are placed at correct position in the sorted set one by one.
Step 6: This process will proceed till the unsorted values are moved to the sorted set.
Step 7: The sorted elements of the array are displayed.
Step 8: Stop the program.
PROGRAM:
#include <stdio.h>
#include <conio.h>
int main()
{
int n, array[1000], c, d, t;
clrscr();
printf(“Insertion Sort”);
printf("\nEnter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++)
printf("%d\n", array[c]);
getch();
return 0;
}
OUTPUT:
RESULT:
AIM:
To write a C program to sort the elements of an array by selection sort algorithm.
ALGORITHM:
Step 1: Start the program.
Step 2:Include the necessary header files.
Step 3:In main function, declare necessary variables.
Step 4: The selection sorting process is done by the following steps:
(i) First, the smallest value in the array is found and placed at index 0.
(ii) Next, another smallest value is compared with the first value and swapping process is
carried out to place the values in the correct position.
Step 5: This process will proceed till all the values are sorted.
Step 6: The sorted elements of the array are displayed.
Step 7: Stop the program.
PROGRAM:
#include <stdio.h>
#include <conio.h>
void selection_sort();
int a[30], n;
void main()
{
int i;
clrscr();
printf(“Selection Sort”);
printf("\nEnter size of an array: ");
scanf("%d", &n);
printf("\nEnter elements of an array:\n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
selection_sort();
printf("\n\nAfter sorting:\n");
for(i=0; i<n; i++)
printf("\n%d", a[i]);
getch();
}
void selection_sort()
{
OUTPUT:
RESULT:
AIM:
To write a C program to sort the elements of an array by merge sort algorithm.
ALGORITHM:
Step 1: Start
Step 2: Declare Array, left, right and mid variables
Step 3: Find mid by formula mid = (left+right)/2
Step 4: Call MergeSort for the left to mid
Step 5: Call MergeSort for mid+1 to right
Step 6: Continue step 2, 3, and 4 while the left is less than the right
Step 7: Then Call the Merge function
Step 8: End
PROGRAM:
#include <stdio.h>
#define max 10
int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];
int main() {
int i;
sort(0, max);
OUTPUT:
RESULT:
Insertion Sort is a simple sorting algorithm that builds the final sorted array one element at a time by
repeatedly inserting the next element into its correct position among the previously sorted elements.
Selection Sort is a sorting algorithm that divides the list into two parts: the sorted part at the front and
the unsorted part at the back. It repeatedly selects the minimum element from the unsorted part and
swaps it with the first unsorted element.
3. How do Insertion Sort and Selection Sort differ in their approach? (Wipro)
Insertion Sort inserts elements into their correct position in the sorted sublist.
Selection Sort selects the minimum element from the unsorted sublist and swaps it with the
first unsorted element.
4. What is the time complexity of Insertion Sort and Selection Sort? (TCS, Infosys)
Both Insertion Sort and Selection Sort have an average and worst-case time complexity of O(n²),
where n is the number of elements.
5. Which algorithm performs better on nearly sorted data: Insertion Sort or Selection Sort?
Why? (Wipro)
Insertion Sort performs better on nearly sorted data because it requires fewer shifts. Its best-case time
complexity is O(n) when the data is already sorted.
6. What is the space complexity of Insertion Sort and Selection Sort? (TCS)
Both algorithms have a space complexity of O(1), as they sort the array in-place without needing
extra space.
7. How many swaps does Selection Sort perform compared to Insertion Sort? (Infosys)
Selection Sort performs at most n-1 swaps, whereas Insertion Sort can perform up to O(n²) swaps in
the worst case.
8. Which sorting algorithm is more efficient for small datasets, Insertion Sort or Selection Sort?
(Wipro)
Both can work efficiently for small datasets, but Insertion Sort is generally preferred because it is
adaptive and faster on nearly sorted data.
9. Is Selection Sort a stable sorting algorithm? How about Insertion Sort? (TCS, Infosys)
Insertion Sort is stable because it maintains the relative order of equal elements.
Selection Sort is not stable because swapping the minimum element may change the relative
order of equal elements.
10. What are some practical applications of Insertion Sort and Selection Sort? (TCS, Infosys,
Wipro)
Insertion Sort: Useful for small or nearly sorted datasets, online sorting, or as part of more
complex algorithms like Timsort.
Selection Sort: Rarely used in practice due to inefficiency but useful for educational purposes
and when memory writes are costly.
EXP NO : 14 IMPLEMENTATION OF OPEN ADDRESSING
DATE :
AIM:
To write a C program for the implementation of Open Addressing to resolve collisions.
ALGORITHM:
Step 1: Start the program.
Step 2:Include the necessary header files.
Step 3:In main function, declare necessary variables.
Step 4: Specify the size of hash table to be used for inserting the key values.
Step 5:Insert the keys into the table using the formula:
h(k, i) = [h‘(k) + i] mod m
h’(k) = k mod m
where, i is the probe number that varies from0 to m–1, m is the size of hast table and k is
the key value.
Step 6:Display all the elements with the positions obtained by applying the above method.
Step 7: Stop the program.
PROGRAM:
#include <stdio.h>
#include <conio.h>
int tsize;
//-------LINEAR PROBING-------
int rehashl(int key)
{
}
void main()
{
int key,arr[20],hash[20],i,n,s,j,k ;
clrscr() ;
printf ("Enter the size of the hash table: ");
scanf ("%d",&tsize);
printf ("\nEnter the number of elements: ");
scanf ("%d",&n);
for (i=0;i<tsize;i++)
hash[i]=-1 ;
printf ("Enter Elements: ");
for (i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
getch() ;
}
OUTPUT:
RESULT:
Open Addressing is a collision resolution technique in hashing where, upon collision, the algorithm
probes (checks) other slots in the hash table using a systematic method until an empty slot is found.
Linear Probing: The next slot checked is the next sequential slot (index + 1, index + 2, etc.)
Quadratic Probing: The next slot checked is based on a quadratic function of the probe number
(index + 1², index + 2², etc.) to reduce clustering.
In Linear Probing, if a collision occurs at index h, subsequent indices checked are (h+1) % table_size,
(h+2) % table_size, (h+3) % table_size, and so forth until an empty slot is found.
4. What problem is Quadratic Probing trying to solve compared to Linear Probing? (TCS)
Quadratic Probing tries to reduce primary clustering, a problem in Linear Probing where clusters of
occupied slots build up, causing longer probe sequences.
Primary clustering occurs in Linear Probing when consecutive slots are filled, leading to long
sequences of probes for new insertions and searches, degrading performance.
Secondary clustering happens when keys that hash to the same initial index follow the same probe
sequence. Quadratic Probing reduces primary clustering but does not completely eliminate secondary
clustering.
Better cache performance since all data is stored in one contiguous array.
Simpler data structure (no linked lists).
Avoids overhead of pointers and memory allocation.
9. What are the disadvantages of Open Addressing? (Wipro)
Table must not be too full (load factor < 0.7) to maintain performance.
Deletion is complex because removing an element can break probe sequences.
Performance degrades with high load factor.
10. How do you handle deletion in Open Addressing? (TCS, Infosys, Wipro)
Deletion is handled by marking the deleted slot with a special marker (e.g., "deleted") rather than
clearing it, so that the probe sequence remains intact for future searches.
CONTEND BEYOND SYLLABUS
EXP NO : 15 IMPLEMENTATION OF HASHING USING CHAINING
COLLISION RESOLUTION TECHNIQUE
DATE :
AIM:
To implement a hash table using the chaining technique for collision resolution in C.
ALGORITHM
Step 1: Start
Step 2: Define a structure 'Node' that represents each element in the hash table.
Each node should contain:
- an integer 'data'
- a pointer 'next' to another node (for chaining)
Step 3: Create a hash table as an array of pointers to 'Node' (initially all NULL).
Let the size of the hash table be 10.
Step 4: Define the hash function:
- hashcode = key % size
- where 'key' is the value to be inserted and 'size' is 10
Step 5: To insert a key:
- Call the hash function to compute index
- Create a new node with the key
- If the index is empty (i.e., NULL), insert the node directly
- If the index already contains nodes (collision occurred),
insert the new node at the beginning of the linked list
- This technique of resolving collision using linked list is called **Chaining**
Step 6: Repeat step 5 for all keys to be inserted.
Step 7: To display the hash table:
- Traverse each index from 0 to size - 1
- For each index, traverse the linked list and print all elements
Step 8: Stop
PROGRAM
#include <stdio.h>
#include <stdlib.h>
#define TABLE_SIZE 10
Node* hashTable[TABLE_SIZE];
// Hash function
int hashFunction(int key) {
return key % TABLE_SIZE;
}
// Insert key into hash table using chaining
void insert(int key) {
int index = hashFunction(key);
hashTable[index] = newNode;
}
// Main function
int main() {
// Initialize hash table
for (int i = 0; i < TABLE_SIZE; i++) {
hashTable[i] = NULL;
}
return 0;
}
Output:
Hash Table using Chaining:
Index 0: 30 -> 10 -> 20 -> NULL
Index 1: NULL
Index 2: NULL
Index 3: NULL
Index 4: NULL
Index 5: 35 -> 25 -> 15 -> NULL
Index 6: NULL
Index 7: NULL
Index 8: NULL
Index 9: NULL
Result:
The program for demonstrating hashing and collision resolution is executed and verified.
VIVA-VOCE