0% found this document useful (0 votes)
25 views113 pages

Data Structure Lab Manual

The document outlines the implementation of various data structures in C, including Stack, Queue, Circular Queue, and Singly Linked List using arrays and linked lists. It provides algorithms, sample programs, and explanations for each structure's operations such as push, pop, insert, delete, and display. Additionally, it includes a viva-voce section with questions and answers related to the concepts of linked lists and stacks.

Uploaded by

malarvizhi k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views113 pages

Data Structure Lab Manual

The document outlines the implementation of various data structures in C, including Stack, Queue, Circular Queue, and Singly Linked List using arrays and linked lists. It provides algorithms, sample programs, and explanations for each structure's operations such as push, pop, insert, delete, and display. Additionally, it includes a viva-voce section with questions and answers related to the concepts of linked lists and stacks.

Uploaded by

malarvizhi k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

EXP NO: 1A ARRAY IMPLEMENTATION OF STACK

DATE :

AIM:
To write a C program for the implementation of Stack using Array.

ALGORITHM:

Step 1: Start the program.


Step 2: Include the necessary header files.
Step 3: In main function, declare necessary variables and specify the size of stack.
Step 4: Display the options for push, pop, display, and exit and define the functions.
Step 5: If the option is 1, then a value is pushed into stack by the following steps:
(i) If the stack is full, then display as stack overflow.
(ii) If the stack is not full, increment the value of top.
(iii) Push the value into top of stack.
Step 6: If the option is 2, then a value is popped out of stack by the following steps:
(i) If the stack is empty, then display as stack underflow.
(ii) If the stack is not empty, then set the top value of stack as value to be popped.
(iii) Decrement the value of top.
Step 7: If the option is 3, then the values in the stack is displayed by the following steps:
(i) If the stack is empty, then display as stack is empty.
(ii) If the stack is not empty, then display the values from the top of stack.
Step 8: If the option is 4, then it exits from the program.
Step 9: Stop the program.

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:

Step 1: Start the program.


Step 2:Include the necessary header files.
Step 3:In main function, declare necessary variables and specify the size of queue.
Step 4:Display the options for insertion, deletion, display, exit and define the functions.
Step 5:If the option is 1, then a value is inserted into queue by the following steps:
(i) If rear points to n, then queue is full.
(ii) If the queue is not full, then insert the value and increment rear.
Step 6:If the option is 2, then a value is deleted from the queue by the following steps:
(i) If front and rear points the same, then queue is empty.
(ii) If the queue is not empty, then delete the value pointed by front and increment front.
(iii) Increment the value of n for further insertion of element.
Step 7:If the option is 3, then the values in the queue is displayed by the following steps:
(i) If the queue is empty, then display as stack is empty.
(ii) If the queue is not empty, then display the values in the order of first in first out manner.
Step 8:If the option is 4, then it exits from the program.
Step 9: Stop the program.

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:

Thus the program is written & executed successfully


EXP NO: 1C ARRAY IMPLEMENTATION OF CIRCULAR QUEUE ADTS

DATE :

AIM:
To write a C program for the implementation of Circular Queue using Array.

ALGORITHM:

Step 1: Check if the queue is full (Rear + 1 % Maxsize = Front)


Step 2: If the queue is full, there will be an Overflow error
Step 3: Check if the queue is empty, and set both Front and Rear to 0
Step 4: If Rear = Maxsize - 1 & Front != 0 (rear pointer is at the end of the queue and front is not
at 0th index), then set Rear = 0
Step 5: Otherwise, set Rear = (Rear + 1) % Maxsize
Step 6: Insert the element into the queue (Queue[Rear] = x)
Step 7: Exit

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 delete the element from the queue


int dequeue()
{

}
// function to display the elements of a queue
void display()
{

}
int main()
{
int choice=1,x; // variables declaration

while(choice<4 && choice!=0) // while loop


{
printf("\n Press 1: Insert an element");
printf("\nPress 2: Delete an element");
printf("\nPress 3: Display the element");
printf("\nEnter your choice");
scanf("%d", &choice);

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

1. How can a stack be implemented using a singly linked list? (TCS)


A stack can be implemented using a linked list by treating the head of the list as the top of the stack.
• Push: Insert a new node at the head.
• Pop: Remove the node from the head.

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

5. How can a linear queue be implemented using a linked list? (Infosys)


A queue can be implemented using a linked list with two pointers:
• Front (for dequeue)
• Rear (for enqueue)
New nodes are added at the rear and removed from the front.

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)

Feature Array Queue Linked List Queue


Size Fixed Dynamic
Overflow Risk Yes (if full) Only if memory is full
Shifting Needed Yes (linear queue) No
Memory Usage Contiguous Non-contiguous (extra for pointers)
9. In a linked list implementation of a queue, what condition indicates the queue is empty?
(L&T Infotech)
The queue is empty if front == NULL (i.e., there are no nodes in the list).

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:

Step 1: Start the program.


Step 2:Include the necessary header files.
Step 3:Create node and declare the variables using structure.
Step 4:In main function, declare necessary variables and functions.
Step 5: Display the options for insertion, deletion and traversal.
Step 6:In the case of Insertion, there are four cases:
Case 1: Insertion of node at the beginning of the linked list.
Case 2: Insertion of node at the end of the linked list.
Case 3: Insertion of node after a given node of the linked list.
Case 4: Insertion of node before a given node of the linked list.
Create a node and check the necessary conditions with temporary variables to find the
correct position to insert.
Step 7: In the case of Deletion, there are three cases:
Case 1: Deletion of node at the beginning of the linked list.
Case 2: Deletion of node at the end of the linked list.
Case 3: Deletion of node after a given node of the linked list.
Check whether the list contains elements and proceed for deleting a node at the
particularposition.
Step 8: Display the nodes present in the linked list by traversing the nodes.
Step 9: Stop the program.
PROGRAM:
#include
<stdio.h>
#include
<stdlib.h>
#include
<conio.h>

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

struct node *start =


NULL; void
insert_at_begin(int);
void insert_at_end(int);
void insert_after(int);
void
insert_before(int);
void traverse();
void
delete_from_begin();
void
delete_from_end();
void delete_after();

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:

Thus the program is written & executed successfully


VIVA - VOCE

1. What is a singly linked list? (TCS)


A singly linked list is a linear data structure where each element (called a node)
contains data and a pointer to the next node in the sequence. The last node points
to NULL.
2. What are the key components of a node in a singly linked list? (Wipro)
Each node contains:
• Data: Stores the actual value.
• Next: A pointer/reference to the next node in the list.

3. What is the advantage of a linked list over an array? (Infosys)


• Dynamic size: Can grow or shrink during runtime.
• Efficient insertions/deletions: No need to shift elements like in arrays.
• Flexible memory use: No need to allocate a fixed size up front.

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)

6. What are the limitations of a singly linked list? (Tech Mahindra)


• Cannot traverse backwards (only forward).
• Random access is not possible (unlike arrays).
• Requires extra memory for pointers.
• Slower access time (must traverse from head to reach a node).

7. How is memory allocated in a singly linked list? (Cognizant)


Memory is allocated dynamically (usually from the heap) for each new node as it's created. Each node
is independent and connected through pointers.

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:

Step 1: Start the program.


Step 2:Include the necessary header files.
Step 3:Create node and declare the variables using structure.
Step 4:In main function, declare necessary variables and functions.
Step 5: Display the options for push, popand display.
Step 6: Create an empty stack and push the values into the stack by the following steps:
(i) If the top is null, then create a memory and push the first element as top.
(ii) If the top is not null, then create a memory and push the elements one by one.
Step 7: The pop operation in the stack is done by the following steps:
(i) If the top is null, then the stack is empty.
(ii) If the top is not null, then pop out the top element.
Step 8: If the top is not null, then display the elements from the top of the stack.
Step 9: Stop the program.

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();
}

//Create empty stack


void create()
{
top = NULL;
}

//Push data into stack


void push(int data)
{

//Display stack elements


void display()
{

//Pop Operation
void pop()
{
}
//Return top element
int topelement()
{
return(top->info);
}

OUTPUT:

RESULT:

Thus the program is written & executed successfully


EXP NO : 3B LINKED LIST IMPLEMENTATION OF LINEAR QUEUE
DATE :

AIM:
To write a C program for the implementation of Queue using Linked List.

ALGORITHM:

Step 1: Start the program.


Step 2:Include the necessary header files.
Step 3:Create node and declare the variables using structure.
Step 4:In main function, declare necessary variables and functions.
Step 5: Display the options for insertion, deletionand display.
Step 6: Insert the elements into the queue by the following steps:
(i) If the front is null, then create a memory and insert the first element as front and rear.
(ii) If the front is not null, then create a memory and insert the elements one by one.
Step 7: Delete the elements from the queue by the following steps:
(i) If the front is null, then the queue is empty.
(ii) If the front is not null, then delete thefront element.
Step 8: If the front is not null, then display the elements in the queue.
Step 9: Stop the program.

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 insert(int value)


{

void delete()
{

}
void display()
{

OUTPUT:
RESULT:

Thus the program is written & executed successfully


VIVA-VOCE

1. What is a singly linked list? (TCS)


A singly linked list is a linear data structure where each element (called a node)
contains data and a pointer to the next node in the sequence. The last node points
to NULL.
2. What are the key components of a node in a singly linked list? (Wipro)
Each node contains:
• Data: Stores the actual value.
• Next: A pointer/reference to the next node in the list.

3. What is the advantage of a linked list over an array? (Infosys)


• Dynamic size: Can grow or shrink during runtime.
• Efficient insertions/deletions: No need to shift elements like in arrays.
• Flexible memory use: No need to allocate a fixed size up front.

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)

6. What are the limitations of a singly linked list? (Tech Mahindra)


• Cannot traverse backwards (only forward).
• Random access is not possible (unlike arrays).
• Requires extra memory for pointers.
• Slower access time (must traverse from head to reach a node).

7. How is memory allocated in a singly linked list? (Cognizant)


Memory is allocated dynamically (usually from the heap) for each new node as it's created. Each node
is independent and connected through pointers.

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;
};

struct link *poly1=NULL,*poly2=NULL,*poly=NULL;

void create(struct link *node)


{
char ch;
do
{
}
while(ch==’y’||ch==’y’);
}

void display(struct link*node)


{
while(node->next!=NULL)
{

}
}

void polyadd(struct link*poly1,struct link*poly2,struct link*poly)


{
while(poly1->next && poly2->next)
{
}
while(poly1->next || poly2->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:

Thus the program is written & executed successfully


VIVA-VOCE

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.

Advantages of Linked List:

 Efficient memory usage


 Dynamic size
 Easier insertion/deletion of 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)

 Initialize two pointers, one for each polynomial.


 Compare the powers:
o If equal, add the coefficients and create a node.
o If one is greater, copy that term to the result.
 Move the pointers accordingly.
 Append remaining terms if any.

Time Complexity: O(m + n)


Space Complexity: O(m + n)

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)

Operation Time Complexity Space Complexity


Addition O(m + n) O(m + n)
Multiplication O(m × n) O(m × n)

Where m and n are number of terms in each polynomial.


6. How can we evaluate a polynomial represented as a linked list for a given value of x?( IBM,
MAQ Software, TCS CodeVita)

Traverse the list and compute:


result += coeff * (x ^ exponent) for each term.

Use pow(x, exponent) or a loop for exponentiation.

7.How would you implement polynomial differentiation using linked lists?( Zoho, Infosys)

Apply differentiation rule to each term:


d/dx (a*x^n) = a*n*x^(n-1)

Steps:

 Traverse the list.


 For each node, update coeff = coeff * pow and decrement pow by 1.
 Skip constant terms (power 0 → derivative is 0).

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:

 Combining like terms


 Efficient traversal for operations

Without order, you'd need to sort the list or use hash maps.

9.What are some real-world applications of polynomial manipulation in computing?( IBM,


Accenture, HCL)

 Symbolic algebra systems


 Computer graphics (Bezier curves)
 Cryptography
 Control systems
 Signal processing

10. Compare array vs linked list implementation of polynomials.( TCS, Infosys, Wipro)

Feature Array Linked List


Memory Fixed & can be wasteful Dynamic, space-efficient
Insertion/Deletion Costly (shifting) Efficient
Sparse Support Poor Excellent
Performance Fast access via index Slower traversal
EXP NO : 5 IMPLEMENTATION OF INFIX TO POSTFIX CONVERSION
DATE :

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);

int prcd(char symbol)


{
switch(symbol)
{
case '+':
case '-':
return 2;
break;
case '*':
case '/'
:return 4;
break;
case '^':
case '$':
return 6;
break;
case '(':
case ')':
case '#':
return 1;
break;
}
}

int isoperator(char symbol)


{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
return 1;
break;
default:
return 0;
}
}

void convertip(char infix[],char postfix[])


{
}

void push(char item)


{
top++;
stack[top]=item;
}
char pop()
{
char a;
a=stack[top];
top--;
return a;
}

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:

Thus the program is written & executed successful


VIVA VOCE

1. What is a postfix expression and why is it preferred in computer evaluation? (TCS)

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.

2. Explain how a stack is used in evaluating a postfix expression. (Infosys)

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.

3. Describe the infix to postfix conversion algorithm. (Wipro)

1. Initialize an empty stack and output list.


2. For each token:
o Operand → add to output
o Operator → pop stack to output based on precedence, then push
o ( → push to stack
o ) → pop until (
3. Pop remaining operators to output after processing.

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.

5. Convert the infix expression (A + B) * C - D to postfix. (Tech Mahindra)


Infix: (A + B) * C - D
Postfix: A B + C * D -
Explanation:

 A B + handles the parentheses


 Then multiplied by C → A B + C *
 Then subtract D → A B + C * D -

6. What are the advantages of postfix evaluation over infix evaluation? (Capgemini)

 No need for parentheses


 Fewer rules to implement
 Can be evaluated in one left-to-right scan using a stack
 Simplifies compiler design

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)

 Time Complexity: O(n), where n is the number of tokens


 Space Complexity: O(n), due to the stack used for intermediate results

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)

Feature Array Implementation Linked List Implementation


Memory allocation Fixed-size, may waste memory Dynamic size, uses memory efficiently
Insertion/deletion Costly (requires shifting) Easy and efficient
Traversal Fast (index-based) Slower (node-by-node)
Flexibility Limited (size must be predefined) Highly flexible
Implementation ease Easier Slightly complex
EXP NO : 6 IMPLEMENTATION OF BINARY SEARCH TREE
DATE :

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()
{

//Function to search the appropriate position to insert the new node


void search(struct btnode *t)
{

//recursive function to perform inorder traversal


void inorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display");
return;
}

if (t->l != NULL)
inorder(t->l);
printf("%d -> ", t->value);
if (t->r != NULL)
inorder(t->r);
}

//To check for the deleted node


void delete()
{

//To find the preorder traversal


void preorder(struct btnode *t)
{

//To find the postorder traversal


void postorder(struct btnode *t)
{
}

//Search for the appropriate position to insert the new node


void search1(struct btnode *t, int data)
{
if ((data>t->value))
{
t1 = t;
search1(t->r, data);
}
else if ((data < t->value))
{
t1 = t;
search1(t->l, data);
}
else if ((data==t->value))
{
delete1(t);
}
}

//To delete a node


void delete1(struct btnode *t)
{
int k;
//To delete leaf node
if ((t->l == NULL) && (t->r == NULL))
{
if (t1->l == t)
{
t1->l = NULL;
}
else
{
t1->r = NULL;
}
t = NULL;
free(t);
return;
}
//To delete node having one left hand child
else if ((t->r == NULL))
{
if (t1 == t)
{
root = t->l;
t1 = root;
}
else if (t1->l == t)
{
t1->l = t->l;

}
else
{
t1->r = t->l;
}
t = NULL;
free(t);
return;
}

//To delete node having right hand child


else if (t->l == NULL)
{
if (t1 == t)
{
root = t->r;
t1 = root;
}
else if (t1->r == t)
t1->r = t->r;
else
t1->l = t->r;
t == NULL;
free(t);
return;
}

//To delete node having two child


else if ((t->l != NULL) && (t->r != NULL))
{
t2 = root;
if (t->r != NULL)
{
k = smallest(t->r);
flag = 1;
}
else
{
k =largest(t->l);
flag = 2;
}
search1(root, k);
t->value = k;
}

//To find the smallest element in the right sub tree


int smallest(struct btnode *t)
{
t2 = t;
if (t->l != NULL)
{
t2 = t;
return(smallest(t->l));
}
else
return (t->value);
}

//To find the largest element in the left sub tree


int largest(struct btnode *t)
{
if (t->r != NULL)
{
t2 = t;
return(largest(t->r));
}
else
return(t->value);
}
OUTPUT:
RESULT:

Thus the program is written & executed successfully


VIVA-VOCE

1. What is a Binary Search Tree (BST)? (TCS)

A Binary Search Tree is a special kind of binary tree where:

 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.

2. How is insertion performed in a BST? (Infosys)


Insertion in a BST is done by comparing the value to be inserted with the current node.
 If the value is smaller, move to the left child.
 If greater, move to the right child.
 The process continues recursively until the correct empty position is found, and the node is
inserted.

3. How do you search for a value in a BST? (Wipro)

Searching in a BST uses the property that left < root < right.

 Start at the root.


 If the value matches, return success.
 If it's smaller, search the left subtree.
 If it's larger, search the right subtree.
 If a null node is reached, the value is not in the tree.

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.

5. How is deletion handled in a BST? (Wipro)

Deletion in BST involves three cases:

1. Leaf node: Simply remove it.


2. One child: Replace the node with its child.
3. Two children: Replace the node’s value with its inorder successor (smallest value in the right
subtree), then delete the successor node.

6. What is inorder traversal in BST and what is its significance? (TCS)

Inorder traversal visits nodes in the order: left → root → right.


In a BST, this results in all the values being visited in ascending (sorted) order.

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.

8. Can a BST handle duplicate values? If yes, how? (Wipro)

 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>

typedef struct node


{
int data;
struct node *left,*right;
int ht;
}node;

node *insert(node *,int);


node *Delete(node *,int);
void preorder(node *);
void inorder(node *);
int height( node *);
node *rotateright(node *);
node *rotateleft(node *);
node *RR(node *);
node *LL(node *);
node *LR(node *);
node *RL(node *);
int BF(node *);

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;
}

node * insert(node *T,int x)


{
}

node * Delete(node *T,int x)


{
}

int height(node *T)


{
int lh,rh;
if(T==NULL)
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);
}

node * rotateright(node *x)


{
node *y;
y=x->left;
x->left=y->right;
y->right=x;
x- >ht=height(x);
y- >ht=height(y);
return(y);
}

node * rotateleft(node *x)


{
node *y;
y=x->right;
x->right=y->left;
y->left=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}

node * RR(node *T)


{
T=rotateleft(T);
return(T);
}

node * LL(node *T)


{
T=rotateright(T);
return(T);
}

node * LR(node *T)


{
T->left=rotateleft(T->left);
T=rotateright(T);
return(T);
}

node * RL(node *T)


{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}

int BF(node *T)


{
int lh,rh;
if(T==NULL)
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;
return(lh-rh);
}

void preorder(node *T)


{
if(T!=NULL)
{
printf("%d(Bf=%d)",T->data,BF(T));
preorder(T->left);
preorder(T->right);
}
}

void inorder(node *T)


{
if(T!=NULL)
{
inorder(T->left);
printf("%d(Bf=%d)",T->data,BF(T));
inorder(T->right);
}
}
OUTPUT:
RESULT:

Thus the program is written & executed successfully


VIVA - VOCE

1. What is an AVL Tree? (TCS)

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.

2. Why is balancing important in a BST? (Infosys)

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).

3. What is the balance factor in AVL Trees? (Wipro)

The balance factor of a node is calculated as:


Height of left subtree – Height of right subtree
For an AVL Tree, the balance factor must be -1, 0, or +1 for every node.

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 Rotation (LL)


 Right Rotation (RR)
 Left-Right Rotation (LR)
 Right-Left Rotation (RL)
Each rotation is used based on the structure of imbalance after insertion or deletion.

5. When do we perform Left-Right and Right-Left rotations in AVL Trees? (Infosys)

 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)

Feature BST AVL Tree


Balancing Not guaranteed Always balanced
Worst-case time O(n) O(log n)
Feature BST AVL Tree
Rotations Not required Required after insert/delete
Performance Stability Unpredictable Consistent

8. What happens during deletion in an AVL Tree? (TCS)


After deleting a node, the tree may become unbalanced. The AVL Tree must be rebalanced by
checking balance factors from the deletion point up to the root and applying appropriate rotations.

9. Is it possible for an AVL Tree to be unbalanced after insertion? (Infosys)

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)

 More complex to implement due to rotations.


 Slightly slower insertions and deletions than plain BSTs due to rebalancing.
EXP NO : 8 IMPLEMENTATION OF HEAPS USING PRIORITY QUEUES
DATE :

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 isFull(struct heapnode *h)


{

}
int isEmpty(struct heapnode *h)
{

void display(struct heapnode *h)


{

struct heapnode *initialize()


{
struct heapnode *t;
int maxelements;
printf("\nEnter the Size of the Priority queue :");
scanf("%d",&maxelements);
t=(struct heapnode *)malloc(sizeof(struct heapnode *));
if(t==NULL)
{
printf("Out of space!");
getch();
exit(0);
}
t->elements=(int *)malloc((maxelements+1)*sizeof(int));
if(t->elements==NULL)
{
printf("Out of space");
getch();
exit(0);
}
t->capacity=maxelements;
t->size=0;
t->elements=0;
return t;
}
void insert(int x,struct heapnode *h)
{
int i;
if(isFull(h))
{
printf("Priority queue is full");
return;
}
for(i=++h->size;h->elements[i/2]>x;i/=2)
h->elements[i]=h->elements[i/2];
h->elements[i]=x;
}

int deletMin(struct heapnode *h)


{
int i,child;
int MinElement,LastElement;
if(isEmpty(h))
{
printf("Priority queue is empty");
return 0;
}
MinElement=h->elements[1];
LastElement=h->elements[h->size--];
for(i=1;i*2<=h->size;i=child)
{
child=i*2;
if(child!=h->size&&h->elements[child+1]<h->elements[child])
child++;
if(LastElement>h->elements[child])
h->elements[i]=h->elements[child];
else
break;
}
h->elements[i]=LastElement;
return MinElement;
}

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)
{

printf("\nEnter your choice :");


scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the element:");
scanf("%d",&ins);
insert(ins,h);
break;
case 2:
del=deletMin(h);
printf("\nDeletd element is %d",del);
getch();
break;
case 3:
display(h);
getch();
break;
case 4:
exit(0);
}
}
getch();
}

OUTPUT:
RESULT:

Thus the program is written & executed successfully


VIVA - VOCE

1. What is a Heap? (TCS)

A Heap is a complete binary tree that satisfies the heap property:

 In a Max-Heap, every parent node is greater than or equal to its children.


 In a Min-Heap, every parent node is less than or equal to its children.

2. What is a Priority Queue and how is it related to a Heap? (Infosys)

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.

3. What are the main operations supported by a Heap? (Wipro)

1. Insert (push) – Adds an element while maintaining the heap property.


2. Delete/Extract (pop) – Removes the root element (highest or lowest priority).
3. Peek/Top – Returns the root element without removing it.
All operations have O(log n) time complexity due to tree re-structuring.

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.

5. How is insertion done in a Heap? (Wipro)

 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.

6. How is deletion handled in a Heap (i.e., extract-max or extract-min)? (TCS)

 Remove the root (top element).


 Replace it with the last element in the heap.
 Heapify-down: Compare with children and swap with the appropriate child until the heap
property is restored.

7. What is the time complexity of Heap operations? (Infosys)

Operation Time Complexity


Insert O(log n)
Operation Time Complexity
Delete O(log n)
Peek/Top O(1)
Build Heap O(n)

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)

Feature Regular Queue Priority Queue


Ordering FIFO Based on priority
Data Structure Linked list or array Usually implemented via heap
Removal Front of queue Element with highest priority

10. What are the advantages and limitations of using a Heap for Priority Queue implementation?
(TCS, Infosys, Wipro)

Advantages:

 Efficient insertion and deletion (O(log n))


 Memory-efficient (stored in arrays)
 Suitable for dynamic priority changes
EXP NO : 9 IMPLEMENTATION OF DIJKSTRA’S ALGORITHM
DATE :

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

void dijkstra(int G[MAX][MAX],int n,int startnode);

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;
}

void dijkstra(int G[MAX][MAX],int n,int startnode)


{
}

OUTPUT:

RESULT:
Thus the program is written & executed successfully
VIVA-VOCE

1. What is Dijkstra’s Algorithm used for? (TCS)

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.

3. How does Dijkstra’s Algorithm work conceptually? (Wipro)

1. Initialize all node distances as infinity except the source (0).


2. Use a priority queue to pick the node with the smallest tentative distance.
3. For each neighbor, update the distance if a shorter path is found.
4. Repeat until all nodes are visited or the queue is empty.

4. Why can’t Dijkstra’s Algorithm handle negative weights? (TCS, Wipro)


Dijkstra’s Algorithm assumes that once a node's shortest distance is finalized, it cannot be improved.
With negative weights, a shorter path may be discovered after finalization, which violates this
assumption.
For such cases, Bellman-Ford is preferred.

5. What is the time complexity of Dijkstra’s Algorithm? (Infosys)

 Using Min-Heap (Binary Heap) and Adjacency List: O((V + E) log V)


 Using simple array: O(V²)
Where V = number of vertices, E = number of edges.

6. What is the role of a Priority Queue in Dijkstra’s Algorithm? (TCS)

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.

7. How is Dijkstra’s Algorithm different from BFS? (Wipro)

Feature Dijkstra’s Algorithm BFS


Graph Type Weighted (non-negative) Unweighted
Goal Shortest path (based on weights) Shortest path (based on hops)
Data Structure Priority Queue (Min-Heap) Queue
8. What are some real-world applications of Dijkstra’s Algorithm? (Infosys)

 GPS & navigation systems


 Network routing protocols (e.g., OSPF)
 Logistics and delivery services
 Flight or public transport scheduling systems

9. Can Dijkstra’s Algorithm be used on directed graphs? (TCS, Infosys)

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)

 Cannot handle negative edge weights.


 Not optimal for very large graphs unless optimized with advanced data structures like
Fibonacci Heaps.
 Does not work for graphs where shortest path needs to be updated frequently in real time
(dynamic graphs).
EXP NO : 10 IMPLEMENTATION OF PRIM’S ALGORITHM
DATE :

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>

#define infinity 9999


#define MAX 20

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

1. What is Prim’s Algorithm used for? (TCS)

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.

3. How does Prim’s Algorithm work conceptually? (Wipro)

1. Start from any vertex and add it to the MST set.


2. Pick the smallest weighted edge connecting the MST set to a vertex outside the MST.
3. Add the chosen vertex to the MST set.
4. Repeat until all vertices are included.

4. What is the time complexity of Prim’s Algorithm? (TCS, Infosys)

 Using adjacency matrix: O(V²), where V = number of vertices.


 Using adjacency list with Min-Heap: O(E log V), where E = number of edges.

5. How is Prim’s Algorithm different from Kruskal’s Algorithm? (Wipro)

Aspect Prim’s Algorithm Kruskal’s Algorithm


Greedy, grows MST by adding edges from a Greedy, adds edges in increasing order
Approach
starting vertex without cycles
Data
Priority queue, adjacency list Disjoint set (union-find)
Structure
Graph Type Works well for dense graphs Works well for sparse graphs

6. Can Prim’s Algorithm be used on disconnected graphs? (TCS)

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.

7. What is the role of the priority queue in Prim’s Algorithm? (Infosys)

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)

 Requires the graph to be connected.


 Performance depends heavily on the choice of data structure; inefficient implementations can
be slow.
EXP NO : 11a IMPLEMENTATION OF LINEAR SEARCH
DATE :

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:

Thus the program is written & executed successfully


VIVA -VOCE

1. What is Linear Search? (TCS)

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.

2. What is Binary Search? (Infosys)

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)

Feature Linear Search Binary Search


Data Requirement Works on unsorted data Requires sorted data
Time Complexity O(n) O(log n)
Search Method Sequential Divide and conquer
Efficiency Less efficient for large data More efficient for large data

4. What is the time complexity of Linear Search and Binary Search? (TCS, Infosys)

 Linear Search: O(n) in worst and average case


 Binary Search: O(log n) in worst and average case

5. When is Linear Search preferred over Binary Search? (Wipro)

Linear Search is preferred when the list is unsorted, or when the dataset is small or when the
overhead of sorting is not justified.

6. What conditions must be met to use Binary Search? (TCS)

The array or list must be sorted beforehand; otherwise, Binary Search will not work correctly.

7. How does Binary Search algorithm work conceptually? (Infosys)

Binary Search compares the target value with the middle element of the array:

 If equal, the search is successful.


 If target is less, search the left half.
 If target is greater, search the right half.
This repeats until the element is found or the interval is empty.

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)

 Linear Search: Searching in small or unsorted datasets, simple lookups.


 Binary Search: Efficient searching in databases, dictionaries, and systems where sorted data is
maintained.
EXP NO: 12a INSERTION SORT
DATE :

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:

Thus the program is written & executed successfully


EXP NO : 12b SELECTION SORT
DATE :

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:

Thus the program is written & executed successfully


EXP NO : 13 MERGE SORT
DATE :

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];

void merging(int low, int mid, int high)


{

void sort(int low, int high)


{
}

int main() {
int i;

printf("List before sorting\n");

for(i = 0; i <= max; i++)


printf("%d ", a[i]);

sort(0, max);

printf("\nList after sorting\n");

for(i = 0; i <= max; i++)


printf("%d ", a[i]);
}

OUTPUT:

RESULT:

Thus the program is written & executed successfully.


VIVA-VOCE

1. What is Insertion Sort?

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.

2. What is Selection Sort? (Infosys)

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;

int hasht(int key)


{
int i ;
i = key%tsize ;
return i;
}

//-------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]);
}

printf("\nThe elements in the array are: ");


for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}

getch() ;
}
OUTPUT:

RESULT:

Thus the program is written & executed successfully


VIVA-VOCE

1. What is Open Addressing in Hashing? (TCS)

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.

2. What are Linear Probing and Quadratic Probing? (Infosys)

 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.

3. How does Linear Probing work? (Wipro)

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.

5. What is primary clustering? (Infosys)

Primary clustering occurs in Linear Probing when consecutive slots are filled, leading to long
sequences of probes for new insertions and searches, degrading performance.

6. What is secondary clustering? Does Quadratic Probing solve it? (Wipro)

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.

7. How do you compute the probe sequence in Quadratic Probing? (TCS)

The probe sequence for a key k is:


(h(k) + c1*i + c2*i²) % table_size
where i is the probe number and c1, c2 are constants (often 0 and 1), reducing clustering.

8. What are the advantages of Open Addressing over Chaining? (Infosys)

 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 structure for chaining


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

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);

Node* newNode = (Node*)malloc(sizeof(Node));


newNode->data = key;
newNode->next = hashTable[index];

hashTable[index] = newNode;
}

// Display the hash table


void display() {
printf("\nHash Table using Chaining:\n");
for (int i = 0; i < TABLE_SIZE; i++) {
printf("Index %d:", i);
Node* current = hashTable[i];
while (current != NULL) {
printf(" %d ->", current->data);
current = current->next;
}
printf(" NULL\n");
}
}

// Main function
int main() {
// Initialize hash table
for (int i = 0; i < TABLE_SIZE; i++) {
hashTable[i] = NULL;
}

// Insert sample elements


insert(15);
insert(25);
insert(35);
insert(20);
insert(10);
insert(30);

// Display hash table


display();

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

1. What is a hash collision?


A hash collision is when a hashing algorithm produces the same hash value for two
different pieces of data.
2. What is linear probing?
Linear probing is a collision resolution technique that involves placing a collided
element in the next available slot in the hash table. If that slot is occupied, it continues to
search for an empty slot in a linear fashion. Linear probing can lead to clustering, where
consecutive elements form clusters in the hash table.
3. What is chaining?
Chaining is a popular collision resolution technique that implements a linked
list. When using chaining, inserting or deleting items with the hash table is fairly simple and
high performing. Chaining can also use dynamic arrays instead of linked lists.
4. What is the load factor in hashing?
The load factor is the number of elements in a hash table divided by the number of
slots. It's usually written as alpha (α). A higher load factor means slower retrieval

You might also like