Wa0000
Wa0000
DE P A RT M E N T O F CY B E R SE C U RI T Y
2 0 C S 3 L - D A T A S T RU C T U R E S A N D A L G O R I T H M S
L A B O R A T O RY
E x no: 1a S t a ck u s i n g
A rray
Da te :
Aim
To implement stack operations using array.
A l g o r i th m
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
E lse
Print Stack overflow
Else If choice = 2 then
If top < 0 then
Print Stack underflow
E lse
Display current top element
Decrement top
Else If choice = 3 then
Display stack elements starting from top
7. Stop
P ro g ram
/* Stack Operation using Arrays */
#include <stdio.h>
#include <conio.h>
#define max 5
static int stack[max];
int top = -1;
void push(int x)
{
2
stack[++top] = x;
}
int pop()
{
return (stack[top--]);
}
void view()
{
int i;
if (top < 0)
printf("\n Stack Empty \n"); else
{
printf("\n Top-->");
for(i=top; i>=0; i--)
{
printf("%4d", stack[i]);
}
printf("\n");
}
}
void main()
{
int ch=0, val;
//clrscr();
while(ch != 4)
{
printf("\n STACK OPERATION \n");
printf("1.PUSH ");
printf("2.POP ");
printf("3.VIEW ");
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);
}
e l se
printf("\n Stack Overflow \n"); break;
case 2:
if(top < 0)
printf("\n Stack Underflow \n"); else
{
3
val = pop();
printf("\n Popped element is %d\n", val);
}
break;
case 3:
view(); break;
//case 4:
//exit(0);
default:
printf("\n Invalid Choice \n");
}
}
}
Ou tpu t
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
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
OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 3
Top--> 45 34 23 12STACK
4
OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 2 Popped
e l e me n t i s 4 5
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 3
Top--> 34 23 12STACK
OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 4
Re s u l t
Thus push and pop operations of a stack was demonstrated using arrays.
5
E x. No . 1 b Li s t u s i n g A rray
Da te :
Aim
To perform various operations on List ADT using array implementation.
A l g o r i th m
1. Start
2. Create a list of n elements
3. Display list operations as a menu
4. Accept user choice
5. If choice = 1 then
Get position of element to be deleted
Move elements one position upwards thereon.
Decrement length of the list
Else if choice = 2
Get position of element to be inserted.
Increment length of the list
Move elements one position downwards thereonStore
the new element in corresponding position
Else if choice = 3
Traverse the list and inspect each element
Report position if it exists.
6. Stop
P ro g ram
/* List operation using Arrays */
#include <stdio.h>
#include <conio.h>
void create();
void insert();
void search();
void deletion();
void display();
void main()
{
int ch;
char g = 'y'; create();
do
{
printf("\n List Operations");
printf("\n 1.Deletion\n 2.Insert\n 3.Search\n4.Exit\n");
printf("Enter your choice: ");
6
scanf("%d", &ch);
switch(ch)
{
case 1:
deletion();
break;
case 2:
insert();
break;
case 3:
search();
break;
case 4:
exit(0);
default:
printf("\n Enter the correct choice:");
}
printf("Do you want to continue: ");
fflush(stdin);
scanf("\n %c",&g);
} while(g=='y' || g=='Y');
getch();
}
void create()
{
printf("\n Enter the number of elements:");
scanf("%d",&n);
printf("\n Enter list elements: "); for(i=0; i<n; i++)
scanf("%d", &b[i]);
}
void deletion()
{
printf("\n enter the position you want to delete: "); scanf("%d", &pos);
if(pos >= n)
printf("\n Invalid location"); else
{
for(i=pos+1; i<n; i++)
b[i-1] = b[i];
n --;
} printf("List elements after deletion");
display();
}
void search()
{
int flag = 0;
printf("\n Enter the element to be searched: "); scanf("%d", &e);
for(i=0; i<n; i++)
{
if(b[i] == e)
7
{
flag = 1;
printf("Element is in the %d position", i); break;
}
}
if(flag == 0)
printf("Value %d is not in the list", e);
}
void insert()
{
printf("\n Enter the position you need to insert: "); scanf("%d", &pos);
if(pos >= n)
printf("\n Invalid location"); else
{
++n ;
for(i=n; i>pos; i--)
b[i] = b[i-1];
printf("\n Enter the element to insert: "); scanf("%d", &e);
b[pos] = e;
}
printf("\n List after insertion:"); display();
}
void display()
{
for(i=0; i<n; i++) printf("\n %d", b[i]);
}
8
Ou tpu t
List Operations1.Deletion
2.Insert 3.Search
4.Exit
Enter your choice:2
Enter the position you need to insert: 1Enter the element to
insert: 99
List after insertion:
12
99
23
34
45
56
Do you want to continue: y
List Operations1.Deletion
2.Insert 3.Search
4. Exit
Enter your choice:1
Enter the position you want to delete: 3
Re s u l t
Thus various operations was successfully executed on list using array
implementation.
9
E x. No . 2 a I m pl e m e n t a t i o n o f L i n k e d L i s t
Da te :
Aim
To define a singly linked list node and perform operations such as insertions and
deletions dynamically.
A l g o r i th m
1. Start
2. Define single linked list node as self referential structure
3. Create Head node with -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 addressElse if
choice = 2
Get node's data to be deleted. Locate
the node and delink the nodeRearrange
the links
E lse
Traverse the list from Head node to node which points to null
7. Stop
P ro g r am
# i n cl u de < s t di o . h >
# i n cl u de < m a l l o c. h >
# i n cl u de < s t dl i b. h >
struct node {
int value;
struct node *next;
};
void insert();
10
void display();
void delete();
int count();
i n t m a i n () {
int option = 0;
printf("\nOptions\n");
printf("1 : Insert into Linked List \n");
printf("2 : Delete from Linked List \n");
printf("3 : Display Linked List\n");
printf("4 : Count Linked List\n");
printf("Others : Exit()\n");
printf("Enter your option:");
scanf("%d", &option);
switch (option) {
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
11
break;
case 4:
count();
break;
default:
break;
}
}
return 0;
}
void insert() {
printf("\nEnter Element for Insert Linked List : \n");
scanf("%d", &data);
temp_node->value = data;
if (first_node == 0) {
first_node = temp_node;
} el se {
head_node->next = temp_node;
}
temp_node->next = 0;
head_node = temp_node;
fflush(stdin);
}
void delete() {
int countvalue, pos, i = 0;
countvalue = count();
12
temp_node = first_node;
printf("\nDisplay Linked List : \n");
void display() {
13
int count = 0;
temp_node = first_node;
printf("\nDisplay Linked List : \n");
while (temp_node != 0) {
printf("# %d # ", temp_node->value);
count++;
temp_node = temp_node -> next;
}
printf("\nNo Of Items In Linked List : %d\n", count);
}
i n t c o u n t () {
int count = 0;
temp_node = first_node;
while (temp_node != 0) {
count++;
temp_node = temp_node -> next;
}
printf("\nNo Of Items In Linked List : %d\n", count);
return count;
}
Re s u l t :
Aim
To implement stack operations using linked list.
A l g o r i th m
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
nodeElse If choice = 2 then
Make temp node point to first node
Make head node point to next of temp
nodeRelease memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop
P ro g ram
<stdio.h>
#include <conio.h> #include
<process.h>#include <alloc.h>
struct node
{
int label;
struct node *next;
};
ma i n ( )
{
int ch = 0;int k;
struct node *h, *temp, *head;
while(1)
{
15
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)));printf("Enter
label for new node : "); scanf("%d", &temp->label);
h = head;
temp->next = h->next;h
->next = temp; break;
case 2:
/* Delink the first node */h = head
->next;
head->next = h->next;
case 3:
printf("\n HEAD -> ");h = head;
/* Loop till last node */while(h
->next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n");break;
case 4:
exit(0);
}
}
}
Ou tpu t
Re s u l t
Thus push and pop operations of a stack was demonstrated using linked list.
E x. No . 3 Que ue U s i n g L i n k e d
17
L i s t D a te :
Aim
To implement queue operations using linked list.
A l g o r i th m
1. Start
2. Define a singly linked list node for queue
3. Create Head node
4. Display a menu listing queue 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
nodeElse If choice = 2 then
Make temp node point to first node
Make head node point to next of temp
nodeRelease memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop
P ro g ram
/* Queue using Single Linked List */#include <stdio.h>
#include <stdlib.h>
struct node
int data;
} *rear,*front,*temp,*newNode;
void create()
{
18
front = rear = NULL;
if(rear != NULL)
e l se
front = rear = newNode; // In a empty queue, the inserted element becomes FRONT and
REAR
int dequeue()
int data;
rear = NULL;
return data;
int empty()
if(front == NULL)
return 1;
e l se
return 0;
void display()
if(empty())
printf("\nEMPTY QUEUE\n");
e l se
temp = front;
while(temp != NULL)
{
20
printf("%d ",temp -> data);
}}}
/* Main Function */
int main()
int num,choice;
while(1)
printf("\n\nQUEUE OPERATIONS\n\n1.ENQUEUE\n2.DEQUEUE\n3.DISPLAY\n\n");
scanf("%d",&choice);
switch (choice)
case 1:
scanf("%d",&num);
enqueue(num);
break;
case 2:
if(!(empty()))
break;
case 3:
display();
break;
default: exit(0);
21
}}
return 0;
Ou tpu t
Re s u l t
Thus insert and delete operations of a queue was demonstrated using linked
list.
22
E x. No . 4 P o l y n om i al
A d di t i o n D a t e :
Aim
To add any two given polynomial using linked lists.
A l g o r i th m
1. Create a structure for polynomial with exp and coeff terms.
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
PolynomialAdvance 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
E lse
Insert the term from second polynomial into sum polynomial
Advance q
4. Copy the remaining terms from the non empty polynomial into the
sumpolynomial
5. Stop
23
P ro g ram
/* 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;
ma i n ( )
{
poly1 = (struct link *)malloc(sizeof(struct link)); poly2 = (struct link
*)malloc(sizeof(struct link)); poly = (struct l i nk
*)malloc(sizeof(struct link));
25
Ou tpu t
Re s u l t
Thus the two given polynomials were added using lists.
E x. No . 5 I n fi x T o P o s tf i x
C o n ve r s i o n D a t e :
26
Aim
To convert infix expression to its postfix form using stack operations.
A l g o r i th m
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expression character-by-
characterIf character is an operand
print it
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.
E lse
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
printit until a left parenthesis is encountered. Do not print the
parenthesis.
If character = $ then Pop out all operators, Print them and Stop
P ro g r am:
I n fi x T o P o s t fi x C o n ve r s i o n
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include <string.h>
/* Variable declarations */
char infix_string[20], postfix_string[20];
int top;
int stack[20];
int pop();
int precedence(char symbol);
int isEmpty();
void infix_to_postfix();
int check_space(char symbol);
void push(long int symbol);
int main()
{
int count, length;
char temp;
top = -1;
27
printf("\nINPUT THE INFIX EXPRESSION : ");
scanf("%s", infix_string);
infix_to_postfix();
printf("\nEQUIVALENT POSTFIX EXPRESSION : %s\n", postfix_string);
return 0;
}
int isEmpty()
{
if(top == -1)
{
return 1;
}
e l se
{
return 0;
}
}
29
int pop()
{
if(isEmpty())
{
printf("Stack is Empty\n");
exit(1);
}
return(stack[top--]); // Pop the symbol and decrement TOP
}
Ou tpu t
Re s u l t
Thus the given infix expression was converted into postfix form using stack.
30
E x. No . 6 B i n ary T r e e
Da te :
Aim
To Construct a binary tree.
A l g o r i th m
1. Create a structure with value and 2 pointer variable l for left node and r for
right node.
2. Read the node to be inserted.
3. If it is the first value, the left and right is equal to NULL.
4. Read the left & right child and return the node
5. Stop
P ro g ram
/ * B i n a r y T r e e */
#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
}*root = NULL;
void printout(struct btnode*);
struct btnode* newnode(int);
void main()
{
root=newnode(50);
root->l=newnode(20);
root->r=newnode(30);
root->l->l=newnode(70);
root->l->r=newnode(80);
root->l->r->r=newnode(60);
root->l->l->l=newnode(10);
root->l->l->r=newnode(40);
printf("tree elements are\n");
printf("\nDISPLAYED IN INORDER\n");
printout(root);
printf("\n");
31
}
OUT P UT : -
tree elements are
DISPLAYED IN INORDER
10->70->40->20->80->60->50->30,
Re s u l t
Thus nodes o f binary t ree will constructed successfully.
32
E x. No . 7 B i n a r y Se a r c h
T re e
Da te :
Aim
To insert and delete nodes in a binary search tree.
A l g o r i th m
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 & childif 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 Copy min
value to delnode placeDelete the duplicate
4. Stop
P ro g ram
/ * B i n a r y S e a r ch T r e e * /
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);
}
Ou tpu t
Re s u l t
Thus nodes were inserted and deleted from a binary search tree.
35
E x. No . 8 A VL Trees
Da te :
Aim
To perform insertion operation on an AVL tree and to maintain balance factor.
A l g o r i th m
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 bethe 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 bearranged 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
P ro g ram
/ * A V L T r e e */
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define CHANGED 0
#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");
36
printf("\n2.View AVL tree"); printf("\n3.Exit");
}
node* getnode()
{
int size;
node *newnode;
size = sizeof(node);
newnode = (node*)malloc(size);
return(newnode);
}
void copynode(node *r, int data)
{
r->data = data;
r->left = NULL;
r->right = NULL;
r->bfactor = 0;
}
void releasenode(node *p)
{
free(p);
}
node* searchnode(node *root, int data)
{
if(root!=NULL)
if(data < root->data)
root = searchnode(root->left, data);
else if(data > root->data)
root = searchnode(root->right, data);
return(root);
}
void lefttoleft(node **pptr, node **aptr)
{
node *p = *pptr, *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;
}
e l se
{
p->bfactor = 0;
a->bfactor = 0;
}
p = a;
*pptr = p;
*aptr = a;
}
void lefttoright(node **pptr, node **aptr, node **bptr)
{
node *p = *pptr, *a = *aptr, *b = *bptr;
37
printf("\nLeft to Right AVL rotation");
b = a->right;
b->right = p;
if(b->bfactor == 1)
p->bfactor = -1; else
p->bfactor = 0;
if(b->bfactor == -1)
a->bfactor = 1; else
a->bfactor = 1;
b->bfactor = 0; p = b;
*pptr = p;
*aptr = a;
*bptr = b;
}
void righttoright(node **pptr, node **aptr)
{
node *p = *pptr, *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;
}
e l se
{
p->bfactor = 0;
a->bfactor = 0;
}
p = a;
*pptr = p;
*aptr = a;
}
void righttoleft(node **pptr, node **aptr, node **bptr)
{
node *p = *pptr, *a = *aptr, *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;
b->bfactor = 0; p = b;
*pptr = p;
*aptr = a;
*bptr = b;
}
38
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);
e l se
lefttoright(&p, &a, &b);
height = BALANCED;
break;
}
}
}
if(data > p->data)
{
p->right = insertnode(data, p->right);
if(height == CHANGED)
{
39
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);
e l se
righttoleft(&p, &a, &b);
height=BALANCED; break;
}
}
}
return(p);
}
void main()
{
int data, ch;
char choice = 'y'; node *root = NULL;
displaymenu();
while((choice == 'y') || (choice == 'Y'))
{
printf("\nEnter your choice: "); fflush(stdin);
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);
e l se
printf("\nData already exists"); break;
case 2:
if(root == NULL)
{
printf("\nAVL tree is empty"); continue;
}
printf("\nInorder traversal of AVL tree"); inorder(root);
printf("\nAVL tree is"); view(root, 1);
break; case 3:
releasenode(root); exit(0);
}
}
getch();
}
40
Ou tpu t
your choice: 1
Enter the value to be inserted 7Right to
Re s u l t
Thus rotations were performed as a result of insertions to AVL Tree.
E x. No . 9 B i n ary He ap
Da te :
Aim
To build a binary heap.
A l g o r i th m
1. Start
2. In a heap, for every node x with parent p, the key in p is smaller than or equal
tothe key in x.
3. For insertion operation
a. Add the element to the bottom level of the heap.
b. Compare the added element with its parent; if they are in the
correctorder, stop.
c. If not, swap the element with its parent and return to the previous step.
4. For deleteMin operation
a. Replace the root of the heap with the last element on the last level.
b. Compare the new root with its children; if they are in the correct
order,stop.
c. If not, Swap with its smaller child in a min-heap
5. Stop
#include<stdio.h>
#include<math.h>
#define MAX 100
int main()
{
intlb,choice,num,n,a[MAX],data,s;
choice = 0;
n=0; //Represents number of nodes in the queue
lb=0; //Lower bound of the array is initialized to 0
while(choice != 4)
{
printf(".....MAIN MENU.....\n");
printf("\n1.Insert.\n");
printf("2.Delete.\n");
printf("3.Display.\n");
printf("4.Quit.\n");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter data to be inserted : ");
scanf("%d",&data);
insert(a,n,data,lb);
n++;
break;
case 2:
s=del_hi_priori(a,n+1,lb);
if(s!=0)
printf("The deleted value is : %d",s);
if(n>0)
n --;
break;
case 3:
printf("\n");
display(a,n);
break;
case 4:
return 0;
default:
printf("Invalid choice\n");
}
printf("\n\n");
}
return 0;
}
//-------INSERT-------
void insert(int a[],intheapsize,intdata,intlb)
{
inti,p;
int parent(int);
if(heapsize==MAX)
43
{
printf("Queue Is Full!!n");
return;
}
i=lb+heapsize;
a[i]=data;
while(i>lb&&a[p=parent(i)]<a[i])
{
swap(&a[p],&a[i]);
i=p;
}
}
//-------DELETE-------
intdel_hi_priori(int a[],intheapsize,intlb)
{
intdata,i,l,r,max_child,t;
int left(int);
int right(int);
if(heapsize==1)
{
printf("Queue Is Empty!!\n");
return 0;
}
t=a[lb];
swap(&a[lb],&a[heapsize-1]);
i=lb;
heapsize--;
while(1)
{
if((l=left(i))>=heapsize)
break;
if((r=right(i))>=heapsize)
max_child=l;
e l se
max_child=(a[l]>a[r])?l:r;
if(a[i]>=a[max_child])
break;
swap(&a[i],&a[max_child]);
i=max_child;
}
return t;
}
//-------DISPLAY-------
void display(int a[],int n)
{
int i;
if(n==0)
{
printf("Queue Is Empty!!\n");
return;
}
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
//-------SWAP-------
void swap(int*p,int*q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
45
E x. No . 1 0 B r e a dt h F i r s t
Se a r c h
Da te :
Aim
To create adjacency matrix of the given graph and to perform breadth first
search traversal.
A l g o r i th m
1. Start
2. Obtain Adjacency matrix for the given graph
3. Define a Queue of size total number of vertices in the graph.
4. Select any vertex as starting point for traversal. Visit that vertex and
insert itinto the Queue.
5. Visit all the adjacent vertices of the vertex which is at front of the Queue
which isnot visited and insert them into the Queue.
6. When there is no new vertex to be visit from the vertex at front of the
Queuethen delete that vertex from the Queue.
7. Repeat step 5 and 6 until queue becomes empty.
8. When queue becomes Empty, then produce final spanning tree by
removingunused edges from the graph.
9. Stop
P ro g ram
/* Graph Traversal – BFS */
#include<stdio.h>
int q[20],front=-1,rear=-1,a[20][20],vis[20];
int delete();
46
void add(int item);
void bfs(int s,int n);
void main()
{
int n,i,s,ch,j;
char c,dummy;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}
do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);
bfs(s,n);
printf("DO U WANT TO CONTINUE(Y/N) ? ");
scanf("%c",&dummy);
scanf("%c",&c);
}
while((c=='y')||(c=='Y'));
}
//**************BFS(breadth-first search) code**************//
void bfs(int s,int n)
{
int p,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)
printf(" %d",p);
while(p!=0)
{
for(i=1;i<=n;i++)
if((a[p][i]!=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}
p=delete();
if(p!=0)
printf(" %d ",p);
47
}
for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}
void add(int item)
{
if(rear==19)
printf("QUEUE FULL");
el se
{
if(rear==-1)
{
q[++rear]=item;
front++;
}
el se
q[++rear]=item;
}
}
int delete()
{
int k;
if((front>rear)||(front==-1))
return(0);
el se
{
k=q[front++];
return(k);
}
}
Re s u l t
Thus Breadth First Traversal is executed on the given graph.
48
E x. No . 1 1 D e p th F i r s t
Se a r c h
Da te :
Aim
To create adjacency matrix of the given graph and to perform depth first
search
traversal.
A l g o r i th m
1. Start
2. Obtain Adjacency matrix for the given graph
3. Define a Stack of size total number of vertices in the graph.
4. Select any vertex as starting point for traversal. Visit that vertex and push it
onto the Stack.
5. Visit any one of the adjacent vertex of the vertex which is at top of the
stackwhich is not visited and push it on to the stack.
6. Repeat step 5 until there are no new vertex to be visit from the vertex on
top ofthe stack.
7. When there is no new vertex to be visit then use back tracking and pop
onevertex from the stack.
8. Repeat steps 5, 6 and 7 until stack becomes Empty.
9. When stack becomes Empty, then produce final spanning tree by
removingunused edges from the graph.
10. Stop
49
P ro g ram
/* DFS on graph */
#include<stdio.h>
int q[20],top=-1,a[20][20],vis[20],stack[20];
void dfs(int s,int n);
void push(int item);
int pop();
void main()
{
int n,i,s,ch,j;
char c,dummy;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}
do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);
dfs(s,n);
printf("DO U WANT TO CONTINUE(Y/N) ? ");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}
//***************DFS(depth-first search) code******************//
void dfs(int s,int n)
{
int i,k;
50
push(s);
vis[s]=1;
k=pop();
if(k!=0)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++)
if((a[k][i]!=0)&&(vis[i]==0))
{
push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
dfs(i,n);
}
void push(int item)
{
if(top==19)
printf("Stack overflow ");
e l se
stack[++top]=item;
}
int pop()
{
int k;
if(top==-1)
return(0);
e l se
{
k=stack[top--];
return(k);
}
}
Re s u l t
Thus depth first traversal is executed on the given graph.
51
E x. No . 1 2 A p p l i c a t i o n o f G r a p h - D i j k s t r a ’ s S h o r t e s t P a th
Da te :
Aim
To find the shortest path for the given graph from a specified source to all
other
vertices using Dijkstra’s algorithm.
A l g o r i th m
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] isinfinity
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-1from the source vertex
distance[i]=cost[0][i];
7. Choose a vertex w, such that distance[w] is minimum and visited[w] is 0.
Markvisited[w] as 1.
8. Recalculate the shortest distance of remaining vertices from the source.
52
9. Only, the vertices not marked as 1 in array visited[ ] should be considered
forrecalculation of distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v]
distance[w]+cost[w][v])
10. Stop
53
P ro g ram
#include <stdio.h>#include
<conio.h>
mindistance = distance[i];nextnode=i;
}
visited[nextnode] = 1;for(i=0;
i < n ; i ++)
if(!visited[i])
if(mindistance + cost[nextnode][i] <
distance[i])
{
distance[i] = mindistance +
cost[nextnode][i];pred[i] =
nextnode;
count++; }
}
55
for(i=0; i<n; i++) if(i !=
startnode)
{
printf("\nDistance to node%d = %d", i,
distance[i]);
printf("\nPath = %d", i);j = i;
do
{
j = pred[j]; printf("<-%d",
j);
} while(j != startnode);
}
}
Ou tpu t
Re s u l t
Thus Dijkstra's algorithm is used to find shortest path from a given vertex.
56
E x. No . 1 3 a Li n e ar
S e a r ch Da t e :
Aim
To perform linear search of an element on the given array.
A l g o r i th m
1 . S ta r t
2 . Re ad n u mbe r o f a r r a y e l e m e n t s n
3 . R e a d a r r a y e l e m e n ts A i , i = 0 , 1 , 2 , … n – 1
4 . R e a d s e a r ch v a l u e
5 . A s s i g n 0 to f o u n d
6 . C h e ck e a ch a r r a y e l e m e n t a g a i n s t s e a r c h
If A i = s e arch th e n
fo u n d = 1
P r i n t "E l e m e n t f o u n d"
P r i n t po s i t i o n i
S to p
7 . I f fo u n d = 0 t h e n
pri n t " E l e me n t n o t f o u n d "
8 . S to p
57
P ro g ram
/ * L i n e a r s e a r c h o n a s o r te d a r r a y */ #i n c l u d e
< s t di o . h >
#i n cl u de < con i o . h >
mai n( )
{
i n t a [5 0 ] , i , n , v a l , f o u n d ; c l r s c r ( ) ;
Ou tpu t
E n te r n u m b e r o f e l e m e n ts : 7 E n te r
A r r a y E l e m e n ts :
23 6 12 5 0 32 10
E n te r e l e m e n t t o l o c a te : 5 E l e m e n t
fo u n d a t po s i t i o n 3
Re s u l t
T h u s a n a r r a y w a s l i n e a r l y s e a r ch e d f o r a n e l e m e n t ' s e x i s t e n c e .
58
E x. No . 1 3 b Bi n ar y
Se a r c h Da t e :
Aim
T o l o ca t e a n e l e m e n t i n a s o r t e d a r r a y u s i n g B i n a r y s e a r ch m e t h o d
A l g o r i th m
1 . S ta r t
2 . Re ad n u m b e r o f a r r a y e l e m e n t s , s a y n
3 . Cr e a te a n a r r a y a r r c o n s i s t i n g n s o r t e d e l e m e n t s
4 . G e t e l e m e n t , s a y k e y t o be l o ca t e d
5 . A s s i g n 0 to l o w e r a n d n t o u pp e r
6 . W h i l e ( l o w e r < u pp e r )
D e t e r m i n e m i ddl e e l e m e n t m i d =
( u pp e r + l o w e r )/ 2 I f ke y = a r r [ m i d ] th e n
P ri n t mi d
St o p
E l s e i f k e y > arr[mi d]
th e n l o we r = m i d +
1
else
u pp e r = m i d – 1
7 . P r i n t "E l e m e n t n o t f o u n d"
8 . S to p
59
P ro g ram
/ * B i n a r y S e a r c h o n a s o r t e d a r r a y * / # i n c l u de
< s td i o . h >
#i n cl u de < con i o . h >
mai n( )
{
i n t a [5 0 ] , i , n , u p p e r , l o w e r , m i d , v a l , f o u n d; c l r s c r ( ) ;
i f ( fo u n d = = - 1 ) pr i n t f( " E l e m e n t n o t
f o u n d" ) ;
g e t ch ( ) ;
}
60
Ou tpu t
E n te r a r r a y s i z e : 9 E l e m e n t s i n
So rt e d O rde r
0 2 4 6 8 10 12 14 16
E n te r e l e m e n t t o l o c a te : 1 2 L o ca t e d
a t p o s i ti o n 6
E n te r a r r a y s i z e : 1 0 E l e m e n t s i n
So rt e d O rde r
0 2 4 6 8 10 12 14 16 18
E n te r e l e m e n t t o l o c a te : 1 3 E l e m e n t
n o t fo u n d
Re s u l t
61
T h u s a n e l e m e n t i s l o c a t e d q u i ck l y u s i n g b i n a r y s e a r ch m e t h o d .
62
E x. No . 1 3 c B u b bl e
S o r t D a te :
Aim
T o s o r t a n a r r a y o f N n u m b e r s u s i n g B u b bl e s o r t .
A l g o r i th m
1 . S ta r t
2 . Re ad n u mbe r o f a r r a y e l e m e n t s n
3 . R e a d a r r a y e l e m e n ts A i
4 . I n de x i va r i e s f r o m 0 t o n - 2
5 . I n de x j v a r i e s f r o m i + 1 t o n - 1
6 . T r a v e r s e t h e a r r a y a n d c o m p a r e e a ch p a i r o f
e l e m e n ts I f A i > A j th e n
Swa p A i a n d A
7 . S to p
63
P ro g ram
/ * B u bb l e S o r t * /
# i n c l u d e < s t di o . h > # i n cl u d e
< con i o .h >
mai n( )
{
i n t a [5 0 ] , i , j , n , t ; c l r s c r ( ) ;
p r i n t f ( " E n t e r n u m b e r o f e l e m e n t s : " ) ; s c a n f ( " % d" ,
&n);
p r i n t f ( "E n t e r A r r a y E l e m e n t s \ n ") ; f o r ( i = 0 ; i < n ;
i + +)
s ca n f( " % d" , & a [ i ] ) ;
fo r ( i = 0 ; i < n - 1 ; i + + )
{
fo r ( j = i + 1 ; j < n ; j + + )
{
i f ( a [i ] > a [ j ])
{
t = a [i ]; a [ i ] = a [ j ] ;
a[j] = t;
}
}
}
Ou tpu t
E n te r n u m b e r o f e l e m e n ts : 5 E n te r
A r r a y E l e m e n ts
3 7 -9 0 2
E l e m e n t s i n So rt e d o rde r :
-9 0 2 3 7
Re s u l t
T h u s a n a r r a y w a s s o r te d u s i n g b u bb l e s o r t .
64
E x. No . 1 3 d Qu i c k So rt
Da t e :
Aim
T o s o r t a n a r r a y o f N n u m b e r s u s i n g Q u i c k s o r t.
A l g o r i th m
1 . S ta r t
2 . Re ad n u mbe r o f a r r a y e l e m e n t s n
3 . R e a d a r r a y e l e m e n ts A i
4 . S e l e c t a n p i v o t e l e m e n t x fr o m A i
5 . D i vi de t h e a r r a y i n t o 3 s e q u e n c e s : e l e m e n t s < x , x , e l e m e n t s > x
6 . R e c u r s i ve l y q u i c k s o r t b o t h s e t s ( A i < x a n d A i > x )
7 . S to p
65
P ro g ram
/ * Q u i ck S o r t * /
# i n c l u d e < s t di o . h > # i n cl u d e
< con i o .h >
vo i d q s o r t ( i n t a r r [2 0 ] , i n t f s t , i n t l a s t ) ; m a i n ( )
{
int arr[30];int i,
s i ze ;
p r i n t f ( " E n t e r t o t a l n o . o f t h e e l e m e n t s : " ) ; s c a n f ( " % d" , & s i z e ) ;
p r i n tf ( "E n te r t o ta l % d e l e m e n t s : \ n ", s i z e ) ; fo r ( i = 0 ; i < s i z e ;
i ++)
s ca n f ( " % d" , & a r r [i ]) ;
q s o r t( a r r , 0 , s i z e - 1 ) ;
p r i n tf ( "\ n Q u i ck s o r t e d e l e m e n ts \ n ") ; fo r ( i = 0 ;
i < s i ze ; i ++)
p r i n t f ( "% d \ t " , a r r [i ]) ; g e t c h ( ) ;
}
vo i d q s o r t ( i n t a r r [2 0 ] , i n t f s t , i n t l a s t )
{
i n t i , j , p i v o t, t m p ; i f( f s t < l a s t )
{
p i v o t = fs t; i =
fs t ;
j = l as t; wh i l e (i
< j)
{
w h i l e ( a r r [i ] < = a r r [ p i v o t ] & & i < l a s t ) i + + ;
w h i l e ( a r r [j ] > a r r [ p i v o t ] ) j - - ;
i f(i <j )
{
tmp = arr[i ]; a rr[i ] =
a r r [ j ] ; a r r [j ] = t m p ;
}
}
t m p = a r r [ p i vo t ]; a r r [p i v o t ] =
a r r [ j ] ; a r r [ j ] = tm p ; q s o r t ( a r r ,
f s t , j - 1 ) ; q s o r t( a r r , j + 1 , l a s t ) ;
66
}
}
Ou tpu t
E n te r t o ta l n o . of th e e l e m e n t s : 8 E n te r t o ta l 8
e l e m e nts :
1
2
7
-1
0
4
-2
3
Q u i ck s o r t e d e l e m e n ts
-2 -1 0 1 2 3 4 7
Re s u l t
67
T h u s a n a r r a y w a s s o r te d u s i n g q u i c k s o r t ' s d i v i d e a n d c o n q u e r m e t h o d .
68
E x. No . 1 3 e M e rg e
S o r t Da t e :
Aim
T o s o r t a n a r r a y o f N n u m b e r s u s i n g M e r g e s o r t.
A l g o r i th m
1 . S ta r t
2 . Re ad n u mbe r o f a r r a y e l e m e n t s n
3 . R e a d a r r a y e l e m e n ts A i
4 . D i vi de t h e a r r a y i n t o s u b - a r r a y s w i t h a s e t o f e l e m e n t s
5 . R e cu r s i v e l y s o r t t h e s u b - a r r a y s
6 . M e r g e th e s o r te d s u b - a r r a y s o n t o a s i n g l e s o r t e d a r r a y .
7 . S to p
69
P ro g ram
/ * M e r g e s o r t */
# i n c l u d e < s t di o . h > # i n cl u d e
< con i o .h >
vo i d m e r g e ( i n t [] , i n t , i n t , i n t ) ; v o i d p a r t ( i n t
[ ], i n t , i n t ) ;
i n t s i ze ;
mai n( )
{
i n t i , arr[3 0 ];
p r i n tf ( "E n te r t o ta l n o . o f e l e m e n t s : ") ; s c a n f ( "% d ",
& s i ze );
p r i n tf ( "E n te r a r r a y e l e m e n ts : " ) ; fo r ( i = 0 ;
i < s i ze ; i + + )
s ca n f ( " % d" , & a r r [i ]) ;
p a r t( a r r , 0 , s i z e - 1 ) ;
p r i n tf ( "\ n M e r g e s o r t e d l i s t : ") ; fo r ( i = 0 ; i < s i z e ;
i ++ )
p r i n t f ( "% d ", a r r [ i ] ) ; g e t c h ( ) ;
}
vo i d p a r t ( i n t a r r [ ], i n t m i n , i n t m a x )
{
i n t i , m i d; i f ( m i n
< m a x)
{
mi d = ( mi n + max) / 2 ; part( arr,
m i n , m i d ) ; p a r t ( a r r , m i d+ 1 , m a x ) ;
me rg e ( ar r, mi n , m i d, max);
}
i f ( max- mi n = = ( s i ze / 2 )- 1 )
{
p r i n tf ( "\ n H a l f s o r t e d l i s t : ") ; fo r ( i = m i n ;
i < = max; i ++ )
p r i n t f ( " % d " , a r r [i ]) ;
}
}
vo i d m e r g e ( i n t a r r [ ] , i n t m i n , i n t m i d , i n t m a x)
{
i n t t m p [ 3 0 ]; i n t i , j , k ,
m; j = mi n ;
m = mid + 1;
70
Ou tpu t
E n te r t o ta l n o . of e l e m e n t s : 8
E n te r a r r a y e l e m e n ts : 2 4 1 3 2 6 1 2 2 7 3 8 1 5
Hal f s o rte d l i s t : 1 1 3 2 4 2 6
Hal f s o rte d l i s t : 2 1 5 2 7 3 8
M e rg e s o rte d l i s t : 1 2 1 3 1 5 2 4 2 6 2 7 3 8
Re s u l t
T h u s a r r a y e l e m e n ts w a s s o r t e d u s i n g m e r g e s o r t ' s d i v i de a n d co n q u e r
m e t h o d.
71
E x. No . 1 3 f I n s e r ti o n
S o r t Da t e :
Aim
T o s o r t a n a r r a y o f N n u m b e r s u s i n g I n s e r ti o n s o r t.
A l g o r i th m
1 . S ta r t
2 . Re ad n u mbe r o f a r r a y e l e m e n t s n
3 . R e a d a r r a y e l e m e n ts A i
4 . S o r t th e e l e m e n t s u s i n g i n s e r t i o n s o r t
I n pa s s p , m o v e th e e l e m e n t i n p o s i ti o n p l e ft u n t i l i ts co r r e ct pl a ce i s
fo u n d a m o n g t h e f i r s t p + 1 e l e m e n t s .
E l e m e n t a t po s i t i o n p i s s a v e d i n te m p, a n d a l l l a r g e r e l e m e n ts
( p r i o r t o po s i t i o n p ) a r e m o v e d o n e s po t to t h e r i g h t. T h e n te m p i s
p l a c e d i n t h e co r r e c t s p o t.
5 . S to
72
P ro g ram
/ * I n s e r t i o n So r t */ m a i n ( )
{
i n t i , j , k , n , te m p , a [ 2 0 ] , p= 0 ;
fo r ( i = 1 ; i < n ; i + + )
{
t e m p = a [i ]; j = i - 1 ;
w h i l e ( ( te m p < a [j ]) & & ( j > = 0 ) )
{
a [ j + 1 ] = a [ j ]; j = j - 1 ;
}
a [ j + 1 ] = te m p;
p++;
p r i n tf ( "\ n A ft e r P a s s % d : ", p ) ; fo r ( k= 0 ; k < n ; k + + )
p r i n tf ( " % d ", a [ k] ) ;
}
Ou tpu t
E n te r t o ta l e l e m e n t s : 6 E n te r
a r r a y e l e m e n ts : 3 4 8 64 51 32 21
A ft e r P a s s 1 : 8 34 64 51 32 21
A ft e r P a s s 2 : 8 34 64 51 32 21
A ft e r P a s s 3 : 8 34 51 64 32 21
A ft e r P a s s 4 : 8 32 34 51 64 21
A ft e r P a s s 5 : 8 21 32 34 51 64
So rt e d Li s t : 8 21 32 34 51 64
Re s u l t
T h u s a r r a y e l e m e n ts w a s s o r t e d u s i n g i n s e r t i o n s o r t .
P r o g r a m N a m e : - P r i n t th e A l t e r n a te N o de s i n a L i n k e d L i s t
INPUT:-
#include <stdio.h>
73
#include <stdlib.h>
struct node
int a;
};
int main()
generate(&head);
display(head);
delete(&head);
return 0;
if(head != NULL)
if (!(flag % 2))
flag++;
display(head->next);
i nt nu m, i ;
scanf("%d", &num);
temp->a = i;
if (*head == NULL)
*head = temp;
(*head)->next = NULL;
75
e l se
temp->next = *head;
*head = temp;
temp = *head;
*head = (*head)->next;
free(temp);
OUTPUT:-
1 3 5 7 9