DS Final Record WORD
DS Final Record WORD
LAB MANUAL
4. Implementation of polynomial
manipulation Using linked list
Date:
Aim
To implement stack operations using array.
Algorithm
1. Start
2. Define a array stack of size max = 5
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
If top < max -1
Increment top
Store element at current position of top
Else
Print Stack overflow
Else If choice = 2 then
If top < 0 then
Print Stack underflow
Else
Display current top
element Decrement top
Else If choice = 3 then
Display stack elements starting from top
7. Stop
Program
#include <stdio.h>
#include <stdlib.h> // Include for exit function
#define MAX 5
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return stack[top--];
}
void view()
{
int i;
if (top < 0)
{
printf("\nStack Empty\n");
}
else
{
printf("\nTop -->");
for (i = top; i >= 0; i--)
{
printf("%4d", stack[i]);
}
printf("\n");
}
}
int main()
{ // Corrected the return type of main
int ch = 0, val;
while (ch != 4) {
printf("\nSTACK OPERATION\n");
printf("1. PUSH\n");
printf("2. POP\n");
printf("3. VIEW\n");
printf("4. QUIT\n");
printf("Enter Choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1:
if (top < MAX - 1) {
printf("\nEnter Stack element: ");
scanf("%d", &val);
push(val);
}
else
{
printf("\nStack Overflow\n");
}
break;
case 2:
if (top < 0)
{
printf("\nStack Underflow\n");
}
else {
val = pop();
printf("\nPopped element is %d\n", val);
}
break;
case 3:
view();
break;
case 4:
exit(0);
default:
printf("\nInvalid Choice\n");
}
}
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
Enter Stack element : 45
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 3
Top--> 45 34 23 12
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 2 Popped
element is 45
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 3
Top--> 34 23 12
STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 4
Result
Thus the operations of a stack were implemented using arrays.
Ex. No. 1b Queue - Array Implementation
Date:
Aim
To implement queue operations using array.
Algorithm
1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
6. If choice = 1
then If rear <
max -1
Increment rear
Store element at current position of rear
Else
Print Queue Full
Else If choice = 2
then If front = –1
then
Print Queue empty
Else
Display current front element
Increment front
Else If choice = 3 then
Display queue elements starting from front to rear.
7. Stop
Program
#include <stdio.h>
#include <stdlib.h> // Include for exit function
#define MAX 5
void insert(int x) {
if (rear < MAX - 1) { // Check for queue overflow before inserting
queue[++rear] = x;
if (front == -1) // Set front to 0 when first element is inserted
front = 0;
} else {
printf("\nQueue Full\n");
}
}
int Remove() {
int val;
if (front == -1) { // Check for queue underflow
printf("\nQueue Empty\n");
return -1; // Return an error value
}
val = queue[front];
if (front == rear) { // If this was the last element
front = rear = -1; // Reset the queue
} else {
front++;
}
return val;
}
void view() {
int i;
if (front == -1) {
printf("\nQueue Empty\n");
} else {
printf("\nFront --> ");
for (i = front; i <= rear; i++) {
printf("%4d", queue[i]);
}
printf(" <-- Rear\n");
}
}
printf("4. QUIT\n");
printf("Enter Choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter element to be inserted: ");
scanf("%d", &val);
insert(val);
break;
case 2:
val = Remove();
if (val != -1) { // Check if removal was successful
printf("\nElement deleted: %d\n", val);
break;
case 3:
view();
break;
case 4:
exit(0);
default:
printf("\nInvalid Choice\n");
}
}
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted : 23
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted : 34 QUEUE
OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Queue Full
QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 3
Front--> 12 23 34 45 56 <--Rear
Result
Thus insert and delete operation of queue was demonstrated using arrays.
Ex. No. 1c Circular Queue - Array Implementation
Date:
Aim
Algorithm
1. Start
2. Initialize the variable like a[size], rear= -1 and front = 0
3. Front variable is used to get the front item from the queue.
4. Rear variable is used to get the last item from the queue.
5. Enqueue element is always inserted at rear position.
6. Check whether queue is full-check((rear == size-1 && front==0) ||(rear==front-
1)
7. If it is full then display Queue is full.If queue is not then, check
(rear==Size-1 && front!=0) if it is true then set rear=0 and insert element.
8. Dequeue element delete the element at the front position.
9. Check whether queue is Empty means check (front==-1)
10. Check if(front==rear)if it is true then set front=rear=-1 else check
if(front==size-1),if it is true then set front=0 and return the element.
11. End the Program.
Program
#include <stdio.h>
#define MAX 5
int cqueue_arr[MAX];
printf("Queue Overflow\n");
return;
front = 0;
rear = 0;
cqueue_arr[rear] = item;
void del()
if (front == -1)
{
printf("Queue Underflow\n");
return;
front = -1;
rear = -1;
} else {
void display() {
if (front == -1) {
printf("Queue is empty\n");
return;
printf("Queue elements:\n");
int i = front;
while (1) {
if (i == rear) {
break;
printf("\n");
/* Begin of main */
int main() {
do {
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Display\n");
printf("4. Quit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
scanf("%d", &item);
insert(item);
break;
case 2:
del();
break;
case 3:
display();
break;
case 4:
break;
default:
printf("Wrong choice\n");
return 0;
Output
Result
Thus insert and delete operation of circular queue was demonstrated using arrays.
Ex. No. 2 Singly Linked List
Date:
Aim
To define a singly linked list node and perform operations such as insertions
and deletions dynamically.
Algorithm
1. Start
2. Define single linked list node as self referential structure
3. Create Head node with label = -1 and next = NULL using
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
Locate node after which insertion is to be
done Create a new node and get data part
Insert new node at appropriate position by manipulating
address Else if choice = 2
Get node's data to be deleted.
Locate the node and delink the
node Rearrange the links
Else
Traverse the list from Head node to node which points to null
7. Stop
Program
#include <stdio.h>
#include <stdlib.h> // Use stdlib for malloc and free
#include <string.h>
struct node {
int label;
struct node *next;
};
int main() {
int ch, k, newLabel;
struct node *head;
switch (ch) {
case 1: // Add a node
printf("\nEnter label after which to add: ");
scanf("%d", &k);
printf("Enter label for new node: ");
scanf("%d", &newLabel);
addNode(head, k, newLabel);
break;
case 4: // Exit
free(head); // Free allocated memory for head
exit(0);
default:
printf("Invalid choice, please try again.\n");
}
}
}
Output
Result
Thus the operations on single linked list were performed.
Ex. No. 3a Stack Using Linked List
Date:
Aim
To implement stack operations using linked list.
Algorithm
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to first
node Make head node point to
new node
Else If choice = 2 then
Make temp node point to first node
Make head node point to next of temp
node Release memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop
Program
#include <stdio.h>
#include <stdlib.h> // Use stdlib.h instead of alloc.h and conio.h
struct node
{
int label;
struct node *next;
};
int main()
{
int ch = 0;
struct node *h, *temp, *head;
while (1)
{
printf("\n Stack using Linked List \n");
printf("1->Push ");
printf("2->Pop ");
printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
/* Create a new node */
temp = (struct node*) malloc(sizeof(struct node));
if (temp == NULL) { // Check if memory allocation was successful
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter label for new node: ");
scanf("%d", &temp->label);
temp->next = head->next; // Insert at the beginning
head->next = temp; // Update head to point to new node
break;
case 2:
/* Pop the first node */
if (head->next == NULL) { // Check if the stack is empty
printf("Stack is empty! Cannot pop.\n");
break;
}
h = head->next; // Get the node to pop
head->next = h->next; // Update head to point to the next node
printf("Node %d deleted\n", h->label); // Use %d for integer
free(h); // Free the memory
break;
case 3:
printf("\n HEAD -> ");
h = head->next; // Start from the first actual node
/* Loop till last node */
while (h != NULL) {
printf("%d -> ", h->label);
h = h->next; // Move to the next node
}
printf("NULL \n");
break;
case 4:
// Free the remaining nodes before exiting
while (head->next != NULL) {
h = head->next;
head->next = h->next;
free(h);
}
free(head); // Free the head node
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0; // Return 0 for successful execution
}
Output
Result
Thus push and pop operations of a stack was demonstrated using linked list.
Ex. No. 3b Queue Using Linked List
Date:
Aim
To implement queue operations using linked list.
Algorithm
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to first
node Make head node point to
new node
Else If choice = 2 then
Make temp node point to first node
Make head node point to next of temp
node Release memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop
Program
<stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch=0; int k;
struct node *h, *temp, *head;
while(1)
{
printf("\n Queue using Linked List \n"); printf("1-
>Insert ");
printf("2->Delete ");
printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node))); printf("Enter
label for new node : "); scanf("%d", &temp->label);
case 3:
printf("\n\nHEAD -> "); h=head;
while (h->next!=NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n");break;
case 4:
exit(0);
}
}
}
Output
Result
Thus insert and delete operations of a queue was demonstrated using linked
list.
Ex. No. 4 Polynomial Addition
Date:
Aim
To add any two given polynomial using linked lists.
Algorithm
1. Create a structure for polynomial with exp and coeffterms.
2. Read the coefficient and exponent of given two polynomials p and q.
3. While p and q are not null, repeat step 4.
If powers of the two terms are equal then
Insert the sum of the terms into the sum
Polynomial Advance p and q
Else if the power of the first polynomial> power of second
then Insert the term from first polynomial into sum
polynomial Advance p
Else
Insert the term from second polynomial into sum polynomial
Advance q
4. Copy the remaining terms from the non empty polynomial into
the sum polynomial
5. Stop
Program
/* Polynomial Addition */
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
struct link
{
int coeff; int
pow;
struct link *next;
};
struct link *poly1=NULL,*poly2=NULL,*poly=NULL;
Output
Result
Thus the two given polynomials were added using lists.
Ex. No. 5a Infix To Postfix Conversion
Date:
Aim
To convert infix expression to its postfix form using stack operations.
Algorithm
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expressioncharacter-by-
character If character is an operand
printit
If character is an operator
Compare the operator’s priority with the stack[top] operator.
If the stack [top] has higher/equal priority than the input
operator, Pop it from the stack and print it.
Else
Push the input operator onto the stack
If character is a left parenthesis, then push it onto the stack.
If character is a right parenthesis, pop all operators from stack
and print it until a left parenthesis is encountered. Do not print the
parenthesis.
If character = $ then Pop out all operators, Print them and Stop
.
Program
#include <stdio.h>
#include <string.h>
#define MAX 20
{
int i, symbol, j = 0;
stack[++top] = '#'; // Initialize stack with a bottom marker
else
{
while (top != -1 && prcd(symbol) <= prcd(stack[top]))
{
postfix[j++] = pop(); // Pop operators from stack
}
push(symbol); // Push the current operator onto the stack
}
}
}
int main()
{
char infix[20], postfix[20];
printf("Enter the valid infix string: ");
fgets(infix, sizeof(infix), stdin);
infix[strcspn(infix, "\n")] = 0; // Remove newline character if present
convertip(infix, postfix);
printf("The corresponding postfix string is: %s\n", postfix);
return 0; // Return 0 for successful execution
}
void push(char item)
{
if (top < MAX - 1) { // Check for stack overflow
stack[++top] = item;
}
else
{
printf("Stack overflow! Cannot push %c\n", item);
}
}
char pop() {
if (top != -1)
{ // Check for stack underflow
return stack[top--];
}
else
{
printf("Stack underflow! Cannot pop.\n");
return '\0'; // Return null character on underflow
}
}
Output
Result
Thus the given infix expression was converted into postfix form using stack.
Ex. No. 5b Postfix Expression Evaluation
Date:
Aim
To evaluate the given postfix expression using stack operations.
Algorithm
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the postfix expression character-by-character
If character is an operand push it onto the
stack If character is an operator
Pop topmost two elements from stack.
Apply operator on the elements and push the result onto the
stack,
5. Eventually only result will be in the stack at end of the expression.
6. Pop the result and print it.
7. Stop
Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 50 // For isdigit function
}
break;
default:
printf("Error: Invalid character '%c' in expression.\n", pf[i]);
return 1; // Exit with error code for invalid character
}
}
}
printf("\nExpression value is %.2f\n", s.a[s.top]); // Output the result
return 0; // Return 0 for successful execution
Output
Result
Thus the given postfix expression was evaluated using stack.
Ex. No. 6 Binary Search Tree
Date:
Aim
To insert and delete nodes in a binary search tree.
Algorithm
1. Create a structure with key and 2 pointer variable left and right.
2. Read the node to be inserted.
If(root==NULL)
root=node
else if (root->key<node-
>key) root-
>right=NULL
else
Root->left=node
3. For
Deletion
if it is a leaf node
Remove immediately
Remove pointer between del node &
child if it is having one child
Remove link between del
node&child Link delnode is child with
delnodes parent
If it is a node with a children
Find min value in right subtree
4. Stop Copy min value to delnode
place Delete the duplicate
Program
#include <stdio.h>
#include <stdlib.h>
struct node
{
int key;
struct node *left;
struct node *right;
};
main()
{
struct node *root = NULL; root
= insert(root, 50); root =
insert(root, 30); root =
insert(root, 20); root =
insert(root, 40); root =
insert(root, 70); root =
insert(root, 60); root =
insert(root, 80);
printf("Inorder traversal of the given tree \n"); inorder(root);
printf("\nDelete 20\n"); root =
deleteNode(root, 20);
printf("Inorder traversal of the modified tree \n"); inorder(root);
printf("\nDelete 30\n"); root =
deleteNode(root, 30);
printf("Inorder traversal of the modified tree \n"); inorder(root);
printf("\nDelete 50\n");
root = deleteNode(root, 50);
printf("Inorder traversal of the modified tree \n"); inorder(root);
}
Output
Result
Thus nodes were inserted and deleted from a binary search tree.
Ex. No. 7 AVL Trees
Date:
Aim
To perform insertion operation on an AVL tree and to maintain balance
factor.
Algorithm
1. Start
2. Perform standard BST insert for w
3. Starting from w, travel up and find the first unbalanced node. Let z be
the first unbalanced node, y be the child of z that comes on the path
from w to z and x be the grandchild of z that comes on the path from w
to z.
4. Re-balance the tree by performing appropriate rotations on the subtree
rooted with z. There can be 4 possible cases that needs to be handled as
x, y and z can be arranged in 4 ways.
a) y is left child of z and x is left child of y (Left Left Case)
b) y is left child of z and x is right child of y (Left Right Case)
c) y is right child of z and x is right child of y (Right Right Case)
d) y is right child of z and x is left child of y (Right Left Case)
5. Stop
Program
/* AVL Tree */
#include <stdio.h>
#include <stdlib.h>
#define CHANGED 0 // For malloc and free
#define BALANCED 1
typedef struct bnode
{
int data, bfactor;
struct bnode *left;
struct bnode *right;
}
node;
int height;
void displaymenu()
{
printf("\nBasic Operations in AVL tree");
printf("\n0.Display menu list");
printf("\n1.Insert a node in AVL tree");
printf("\n2.View AVL tree");
printf("\n3.Exit");
}
node* getnode()
{
node *newnode = (node*)malloc(sizeof(node));
if (newnode == NULL)
{ printf("Memory allocation failed\n");
exit(1);
}
return newnode;
}
void copynode(node *r, int data)
{
r->data = data;
r->left = NULL;
r->right = NULL;
r->bfactor = 0;
}
void releasenode(node *p)
{
if (p != NULL)
{
releasenode(p->left);
releasenode(p->right);
free(p);
}
}
node* searchnode(node *root, int data)
{
if (root == NULL || root->data == data)
return root;
if (data < root->data)
return searchnode(root->left, data);
else
return searchnode(root->right, data);
}
void lefttoleft(node **pptr, node **aptr)
{
node *p = *pptr;
node *a = *aptr;
printf("\nLeft to Left AVL rotation");
p->left = a->right;
a->right = p;
if (a->bfactor == 0)
{
p->bfactor = 1;
a->bfactor = -1;
height = BALANCED;
}
else
{
p->bfactor = 0;
a->bfactor = 0;
}
*pptr = a;
}
void lefttoright(node **pptr, node **aptr, node **bptr)
{
node *p = *pptr;
node *a = *aptr;
node *b = *bptr;
printf("\nLeft to Right AVL rotation");
b = a->right;
a->right = b->left;
b->left = a;
p->left = b->right;
b->right = p;
if (b->bfactor == 1)
{
p->bfactor = -1;
}
else
{
p->bfactor = 0;
}
if (b->bfactor == -1)
{
a->bfactor = 0;
}
else
{
a->bfactor = 1;
}
b->bfactor = 0;
*pptr = b;
}
void righttoright(node **pptr, node **aptr)
{
*a = *aptr;
printf("\nRight to Right AVL rotation");
p->right = a->left;
a->left = p;
if (a->bfactor == 0)
{
p->bfactor = -1;
a->bfactor = 1;
height = BALANCED;
}
else
{
p->bfactor = 0;
a->bfactor = 0;
}
*pptr = a;
}
void righttoleft(node **pptr, node **aptr, node **bptr)
{
node *p = *pptr;
node *a = *aptr;
node *b = *bptr;
printf("\nRight to Left AVL rotation");
b = a->left;
a->left = b->right;
b->right = a;
p->right = b->left;
b->left = p;
if (b->bfactor == -1)
{
p->bfactor = 1;
}
else
{
p->bfactor = 0;
}
if (b->bfactor == 1)
{
a->bfactor = 0;
}
else
{
a->bfactor = -1;
}
b->bfactor = 0;
*pptr = b;
}
void inorder(node *root)
{
if (root == NULL)
return;
inorder(root->left);
printf("\n%4d", root->data);
inorder(root->right);
}
void view(node *root, int level)
{
int k;
if (root == NULL)
return;
view(root->right, level + 1);
printf("\n");
for (k = 0; k < level; k++)
printf(" ");
printf("%d", root->data);
view(root->left, level + 1);
}
node* insertnode(int data, node *p)
{
node *a, *b;
if (p == NULL)
{
p = getnode();
copynode(p, data);
height = CHANGED; return p;
}
if (data < p->data)
{
p->left = insertnode(data, p->left);
if (height == CHANGED)
{
switch (p->bfactor)
{
case -1:
p->bfactor = 0;
height = BALANCED;
break;
case 0:
p->bfactor = 1;
break;
case 1:
a = p->left;
if (a->bfactor == 1)
{
lefttoleft(&p, &a);
}
else
{
lefttoright(&p, &a, &b);
}
height = BALANCED;
break;
}
}
}
else if (data > p->data)
{
p->right = insertnode(data, p->right);
if (height == CHANGED)
{
switch (p->bfactor)
{
case 1:
p->bfactor = 0;
height = BALANCED;
break;
case 0:
p->bfactor = -1;
break;
case -1:
a = p->right;
if (a->bfactor == -1)
{
righttoright(&p, &a);
}
else
{
righttoleft(&p, &a, &b);
}
height = BALANCED;
break;
}
}
}
return p;
}
int main()
{
int data, ch;
char choice = 'y';
node *root = NULL;
displaymenu();
while (choice == 'y' || choice == 'Y')
{
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 0:
displaymenu();
break;
case 1:
printf("Enter the value to be inserted: ");
scanf("%d", &data);
if (searchnode(root, data) == NULL)
{
root = insertnode(data, root);
}
else
{
printf("\nData already exists");
}
break;
case 2: if (root == NULL)
{
printf("\nAVL tree is empty");
}
else
{
printf("\nInorder traversal of AVL tree:");
inorder(root);
printf("\nAVL tree is:");
view(root, 1);
}
break;
case 3: releasenode(root);
exit(0);
default:
printf("\nInvalid choice. Please try again.");
}
printf("\nDo you want to continue (y/n)? ");
scanf(" %c", &choice);
}
return 0;
}
Output
your choice: 1
Enter the value to be inserted 7 Right
Result
Thus rotations were performed as a result of insertions to AVL Tree.
Ex.NO:8 Implementation of Priority Queue Using Heaps
Date:
Aim
To write a C program to implement Priority Queue using Binary Heaps.
Algorithm
1. Initialize all necessary variables and functions.
2. Read the choices
3. For insertion, read the element to be inserted.
4. If root is NULL,assign the given element as root.
5.If the element is equal to the root, print Duplicate value.
6.Else if element value is less than the root value insert element at the
leftroot
7.Else insert right side of the root.
8. For deletion, get the priority for maximum or minimum.
9. If maximum, it deletes the root and rearranges the tree.
10. If minimum, it deletes the leaf.
11. End of the program.
Program
#include <stdio.h>
#include <stdlib.h>
struct Node
{
struct Node *Previous;
int Data;
struct Node *Next;
};
int PriorityQueue(void);
int Maximum(void);
int Minimum(void);
void Insert(int DT);
int Delete(int DataDel);
void Display(void);
int Search(int DataSearch);
int main()
{
int choice;
int DT;
PriorityQueue();
while (1) {
int PriorityQueue(void)
{
printf("\nEnter first element of Queue: ");
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory allocation failed\n");
exit(1);
}
scanf("%d", &newNode->Data);
newNode->Previous = NULL;
newNode->Next = NULL;
head = newNode;
ptr = head;
NumOfNodes++;
return 0;
}
int Maximum(void)
{
if (head == NULL) return FALSE; // Handle empty queue
int Minimum(void) {
if (head == NULL) return FALSE; // Handle empty queue
newNode->Data = DT;
newNode->Next = NULL;
// Insert at the end of the queue
if (head == NULL) {
newNode->Previous = NULL;
head = newNode;
}
else
{
ptr = head;
while (ptr->Next != NULL)
{
ptr = ptr->Next;
}
ptr->Next = newNode;
newNode->Previous = ptr;
}
NumOfNodes++;
}
// Adjust pointers
if (temp->Next != NULL)
{
temp->Next->Previous = temp->Previous;
}
if (temp->Previous != NULL)
{
temp->Previous->Next = temp->Next;
}
free(temp);
NumOfNodes--;
return TRUE;
}
void Display(void) {
ptr = head;
printf("\nPriority Queue is as follows:-\n");
while (ptr != NULL) {
printf("\t\t%d", ptr->Data);
ptr = ptr->Next;
}
printf("\n");
}
OUTPUT
RESULT
Thus the Priority Queue using Binary Heap is implemented and the result is
verified successfully.
Ex. No. 9 Dijkstra’s Shortest Path
Date:
Aim
To find the shortest path for the given graph from a specified source to all
other
vertices using Dijkstra’s algorithm.
Algorithm
1. Start
2. Obtain no. of vertices and adjacency matrix for the given graph
3. Create cost matrix from adjacency matrix. C[i][j] is the cost of going
from vertex i to vertex j. If there is no edge between vertices i and j
then C[i][j] is infinity
4. Initialize visited[] to zero
5. Read source vertex and mark it as visited
6. Create the distance matrix, by storing the cost of vertices from vertex
no. 0 to n-1 from the source vertex
distance[i]=cost[0][i];
7. Choose a vertex w, such that distance[w] is minimum and visited[w] is
0. Mark visited[w] as 1.
8. Recalculate the shortest distance of remaining vertices from the source.
9. Only, the vertices not marked as 1 in array visited[ ] should be
considered for recalculation of distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v]
distance[w]+cost[w][v])
10. Stop
Program
#include <stdio.h>
#include <conio.h>
#define MAX 10
int main() {
int G[MAX][MAX], i, j, n, u;
scanf("%d", &n);
scanf("%d", &G[i][j]);
scanf("%d", &u);
dijkstra(G, n, u);
return 0;
G[i][j];
visited arrays
distance[i] = cost[startnode][i];
pred[i] = startnode;
visited[i] = 0;
distance[startnode] = 0;
visited[startnode] = 1;
count = 1;
// Dijkstra's algorithm
mindistance = INFINITY;
distance
visited[i]) {
mindistance = distance[i];
nextnode = i;
visited[nextnode] = 1;
if (!visited[i])
pred[i] = nextnode;
count++;
if (i != startnode)
printf("\nPath = %d",i);
j = i;
do
j = pred[j];
printf("<-%d", j);
} while (j !=startnode);
}
}
Output
Result
Thus Dijkstra's algorithm is used to find shortest path from a given vertex.
Ex. No. 10 Prim’s Algorithm
Date:
Aim
To write a C Program to implement Prim’s Algorithm.
Algorithm
This algorithm creates spanning tree with minimum weight from a given weighted graph.
1. Begin
2. Create edge list of given graph, with their weights.
3. 3.Draw all nodes to create skeleton for spanning tree.
4. Select an edge with lowest weight and add it to skeletonand delete edge from edge
list.
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.
6. Repeat step 5 until n-1 edges are
added.
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()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX]; int
visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{ if(G[i][j]==0)
cost[i][j]=infinity; else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i]; from[i]=0; visited[i]=0;
}
min_cost=0;
no_of_edges=n-1;
while(no_of_edges>0)
{
min_distance=infinity; for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v]; spanning[u]
[v]=distance[v]; spanning[v]
[u]=distance[v]; no_of_edges--;
visited[v]=1; for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}
Output
Enter no. of vertices:6 Enter the
adjacency matrix:
0316 00
3050 30
1505 64
6050 02
0360 06
Result
Thus Prim’s algorithm is used to find shortest path from a given vertex.
Ex. No. 11a Linear
Search Date:
Aim
To perform linear search of an element on the given array.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai, i = 0,1,2,…n–1
4. Read search value
5. Assign 0 to found
6. Check each array element against search
If Ai = search then
found = 1
Print "Element found"
Print position i
Stop
7. If found = 0 then
print "Element not found"
8. Stop
Program
#include <stdio.h>
int main()
scanf("%d", &n);
scanf("%d", &a[i]);
scanf("%d", &val);
if (a[i] == val)
found = 1;
element
}
if (found == 0)
Output
Result
Thus an array was linearly searched for an element's existence.
Ex. No. 11b Binary Search
Date:
Aim
To locate an element in a sorted array using Binary search method
Algorithm
1. Start
2. Read number of array elements, say n
3. Create an array arr consisting n sorted elements
4. Get element, say key to be located
5. Assign 0 to lower and n to upper
6. While (lower < upper)
Determine middle element mid =
(upper+lower)/2 If key = arr[mid] then
Print mid
Stop
Else if key > arr[mid]
then lower = mid
+1
else
upper = mid – 1
#include <stdio.h>
int main()
scanf("%d", &n);
printf("%4d", a[i]);
scanf("%d", &val);
lower = 0;
found = -1;
if (a[mid] == val)
{
found = 1;
break;
upper = mid - 1;
else
lower = mid + 1;
if (found == -1)
}
Output
Result
Thus an element is located quickly using binary search method.
Ex. No. 12.a Insertion Sort
Date:
Aim
To sort an array of N numbers using Insertion
sort. Algorithm
1. Start
2. Read number of array
elements n 3.Read array
elements Ai
4. Sort the elements using insertion sort
In pass p, move the element in position p left until its correct place is
found among the first p + 1 elements.
Element at position p is saved in temp, and all larger elements (prior to
position p) are moved one spot to the right. Then temp is placed in the
correct spot.
5. Stop
Program
/* Insertion Sort */
#include <stdio.h>
int main()
scanf("%d", &n);
scanf("%d", &a[i]);
temp = a[i];
j = i - 1;
a[j + 1] = a[j];
j = j - 1;
a[j + 1] = temp;
p++;
printf("\n");
Output
Result
Thus array elements was sorted using insertion sort.
Ex No.12.b Selection Sort
Date:
Aim
Algorithm
/*Selection sort*/
#include <stdio.h>
// Function prototype
void SelSort(int array[], int n);
int main()
{
int array[100], n, i;
return 0;
}
OUTPUT:
Enter number of
elements 4
Enter 4 Numbers
4
2
7
1
Sorted
Array 1
2
4
7
Result
Thus array elements was sorted using Selection sort.
Ex. No. 13 Merge Sort
Date:
Aim
To sort an array of N numbers using Merge sort.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Divide the array into sub-arrays with a set of elements
5. Recursively sort the sub-arrays
6. Merge the sorted sub-arrays onto a single sorted array.
7. Stop
Program
/* Merge sort */
#include <stdio.h>
#include <conio.h>
void merge(int [],int ,int ,int ); void part(int [],int ,int );
int size;
main()
{
int i, arr[30];
printf("Enter total no. of elements : ");
scanf("%d", &size);
printf("Enter array elements : ");
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
part(arr, 0, size-1);
printf("\n Merge sorted list : ");
for(i=0; i<size; i++)
printf("%d ",arr[i]); getch();
}
void part(int arr[], int min, int max)
{
int i, mid; if(min < max)
{
mid = (min + max) / 2;
part(arr, min, mid);
part(arr, mid+1, max);
merge(arr, min, mid, max);
}
if (max-min == (size/2)-1)
{
printf("\n Half sorted list : ");
for(i=min;
i<=max; i++)
printf("%d ", arr[i]);
}
}
Output
Result
Thus array elements was sorted using merge sort's divide and conquer
method.
Ex. No. 14 Open Addressing Technique (Linear and Quadratic probing)
Date:
Aim
To implement open addressing using a C program.
Algorithm
1. Create a structure, data (hash table item) with key and value as data.
2. Now create an array ofstructure, data ofsome certain size (10, in this
case).But, the size of array must be immediately updated to a prime
number just greater than initial array capacity (i.e 10, in this case).
3. A menu is displayed on the screen.
4. User must choose one option from four choices given in the menu
5. Perform all the operations
6. Stop
PROGRAM:
/*Open Addressing Hashing Technique*/
#include <stdio.h>
// Linear probing
int rehashl(int key)
{
return (key + 1) % tsize;
}
// Quadratic probing
int rehashq(int key, int j)
{
return (key + (j * j)) % tsize;
}
int main()
{
int key, arr[20], hash[20], i, n, op, j, k;
printf("Enter the size of the hash table: ");
scanf("%d", &tsize);
// Ensure size is positive
if (tsize <= 0)
{
printf("Invalid hash table size!\n");
return 1;
}
// Ensure the number of elements does not exceed the hash table size
if (n > tsize)
{
printf("Number of elements exceeds hash table size!\n");
return 1;
}
// Initialize the hash table
for (i = 0; i < tsize; i++)
{
hash[i] = -1; // -1 indicates an empty slot
}
do
{
printf("\n\n1. Linear Probing\n2. Quadratic Probing \n3. Exit\nEnter your option: ");
scanf("%d", &op);
switch (op)
{
case 1: // Linear Probing
// Reinitialize the hash table
for (i = 0; i < tsize; i++)
{
hash[i] = -1;
}
for (k = 0; k < n; k++)
{
key = arr[k];
i = hasht(key);
while (hash[i] != -1)
{
i = rehashl(i);
}
hash[i] = key;
}
printf("\nThe elements in the hash table are: ");
for (i = 0; i < tsize; i++)
{
if (hash[i] != -1)
{
printf("\nElement at position %d: %d", i, hash[i]);
}
else
{
printf("\nElement at position %d: Empty", i);
}
}
break;
case 2: // Quadratic Probing
// Reinitialize the hash table
for (i = 0; i < tsize; i++)
{
hash[i] = -1;
}
for (k = 0; k < n; k++)
{
j = 0; // Initialize j for quadratic probing
key = arr[k];
i = hasht(key);
while (hash[i] != -1)
{
i = rehashq(key, j);
j++; // Increment j for the next probe
}
hash[i] = key;
}
printf("\nThe elements in the hash table are: ");
for (i = 0; i < tsize; i++)
{
if (hash[i] != -1)
{
printf("\nElement at position %d: %d", i, hash[i]);
}
else
{
printf("\nElement at position %d: Empty", i);
}
}
break;
case 3: // Exit
printf("Exiting...\n");
break;
default:
printf("Invalid option! Please try again.\n");
}
}
while (op != 3);
Result
Thus hashing has been performed successfully.