Cs3311 Ds Lab Manual
Cs3311 Ds Lab Manual
LAB MANUAL
REGULATIONS 2021
YEAR/SEM : II/03
STRENGTH : 63
BATCH :2024-2025 ODD
STAFF NAME : Mrs.M.Subasri AP/CSE
1
CS 3311 DATA STRUCTURES LABORATORY LTPC0042
COURSE OBJECTIVES:
To demonstrate array implementation of linear data structure algorithms.
To implement the applications using Stack.
To implement the applications using Linked list
To implement Binary search tree and AVL tree algorithms.
To implement the Heap algorithm.
To implement Dijkstra’s algorithm.
To implement Prim’s algorithm
To implement Sorting, Searching and hashing algorithms.
LIST OF EXERCISES:
1. Array implementation of Stack, Queue and Circular Queue ADTs
2. Implementation of Singly Linked List
3. Linked list implementation of Stack and Linear Queue ADTs
4. Implementation of Polynomial Manipulation using Linked list
5. Implementation of Evaluating Postfix Expressions, Infix to Postfix conversion
6. Implementation of Binary Search Trees
7. Implementation of AVL Trees
8. Implementation of Heaps using Priority Queues
9. Implementation of Dijkstra’s Algorithm
10. Implementation of Prim’s Algorithm
11. Implementation of Linear Search and Binary Search
12. Implementation of Insertion Sort and Selection Sort
13. Implementation of Merge Sort
14. Implementation of Open Addressing (Linear Probing and Quadratic Probing)
COURSE OUTCOMES:
At the end of this course, the students will be able to:
2
LIST OF EXERCISES
3
SRM TRP Engineering College
Vision of the Institute
To carve the youth as dynamic, competent, valued and knowledgeable Technocrats through
research, innovation and entrepreneurial development for accomplishing the global
expectations.
To be recognized as Centre of Excellence for innovation and research in computer science and
engineering through the futuristic technologies by developing technocrats with ethical values
to serve the society at global level.
4
Program Educational Objectives (PEO's)
PEO1: Ability to analyze and get solutions in the field of Computer Science and
Engineering through application of fundamental knowledge of Mathematics, Science and
Electronics (Preparation).
PEO2: Innovative ideas, methods and techniques thereby rendering expertise to the industrial
and societal needs in an effective manner and will be a competent computer/software engineer
(Core Competency).
PEO4: Professional with ethical values to develop leadership, effective communication skills
and teamwork to excel in career. (Professionalism)
PEO5: Strive to learn continuously and update their knowledge in the specific fields of
computer science & engineering for the societal growth. (Learning environment).
PO1: Engineering knowledge: Apply the basic knowledge of science, mathematics and
engineering fundamentals in the field of Computer Science and Engineering to solve complex
engineering problems.
PO2: Problem analysis: Ability to use basic principles of mathematics, natural sciences,
and engineering sciences to Identify, formulate, review research literature and analyze
Computer Science and engineering problems.
PO5: Modern tool usage: Ability to use state of the art of techniques, skills and modern
engineering tools necessary for engineering practice to satisfy the needs of the society with
an understanding of the limitations.
5
PO6: The Engineer and Society: Ability to apply reasoning informed by the contextual
knowledge to assess the impact of Computer Science and engineering solutions in legal, health,
cultural, safety and societal context and the consequent responsibilities relevant to the
professional engineering practice.
PO8: Ethics: Ability to understand and apply ethical principles and commitment to address
the professional ethical responsibilities of an engineer.
PO11: Project management and finance: Ability to acquire and demonstrate the
knowledge of contemporary issues related to finance and managerial skills in one’s own
work, as a member and leader in a team, to manage projects and in multidisciplinary
environments.
PO12: Life-long learning: Ability to recognize and adapt to the emerging field of application
in engineering and technology by developing self-confidence for lifelong learning process.
PSO1:Use Data structures, Data management, Networking, System software, Data science
with high end programming skills to design and implement automation in various domains
of emerging technologies.
PSO2: Apply engineering knowledge in project development with the end products and
services in the field of hardware and software platform to accomplish the industry
expectations.
6
SRM TRP ENGINEERING COLLEGE Trichy-621 105
Regulation : 2021
Course outcome
CS3311.1 Implement appropriate linear data structure for solving a real world problems using array
Design appropriate linear data structure for solving a real world applications using Linked
CS3311.2
List.
CS3311.3 Construct appropriate Nonlinear Tree data structure for solving real world applications.
CS3311.4 Solve Nonlinear Graph traversal techniques for real world problems.
Course code PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CS3311.1 3 3 3 2 1 2 1 - 1 1 1 3
CS3311.2 3 3 3 2 2 2 1 - 1 1 2 3
CS3311.3 3 3 3 3 1 1 1 1 1 2 1 3
CS3311.4 3 3 3 3 1 1 1 1 1 2 2 3
CS3311.5 3 2 3 2 1 2 1 - 1 1 1 3
CS3311.6 3 3 3 2 1 2 1 - 1 1 1 3
CS3311 3.0 2.8 3.0 2.3 1.2 1.7 1.0 1.0 1.0 1.3 1.3 3.0
7
CO-PSO MATRICES
8
Ex.No:1a ARRAY IMPLEMENTATION OF STACK ADT
AIM
ALGORITHM
PROGRAM
#include<stdio.h>
#include<string.h>
#define MAX 4 //you can take any number to limit your stack size
int stack[MAX];
int top;
void push()
{
int token;
if(top==MAX-1)
{
printf("\nStack full");
return;
}
printf("\nEnter the element to be inserted:");
scanf(“%d”,&token);
top=top+1;
stack[top]=token;
}
int pop()
{
int t;
if(top==-1)
{
return -1;
}
t=stack[top];
top=top-1;
return t;
}
void show()
{
int i;
printf("\nThe Stack elements are:\nTOP-->");
for(i=top;i>=0;i--)
{
printf("\t|%d|\n",stack[i];
}
}
void main()
9
{
int choice,token;
top=-1;
clrscr();
printf("STACK USING ARRAY");
do
{
printf("\n1.PUSH\n2.POP\n3.show or display\n4.exit"); printf("\nEnter your
choice for the operation: "); scanf(“%d”,&choice);
switch(choice)
{
case 1:
push();
show();
break;
case 2:
token=pop();
if(token==-1)
printf("\nStack empty");
else
{
printf("\nThe element deleted is:%d",token);
show();
break;
}
case 3:
show();
break;
case 4:
exit(0);
default:printf("\nWrong choice");
break;
}
}while(choice<5);
getch();
}
OUTPUT:
STACK USING ARRAY
1.PUSH
2.POP
3.SHOW OR DISPLAY
4.EXIT
Enter your choice for the operation:1
Enter the element to be inserted: 4
The stack elements are:
TOP|4|
10
STACK USING ARRAY
1.PUSH
2.POP
3.SHOW OR DISPLAY
4.EXIT
Enter your choice for the operation:1
Enter the element to be inserted: 8
The stack elements are:
TOP |8|
|2|
|4|
1.PUSH
2.POP
3.SHOW OR DISPLAY
4.EXIT
Enter your choice for the operation:2
Enter the element to be deleted: 8
The stack elements are:
TOP |2|
|4|
1.PUSH
2.POP
3.SHOW OR DISPLAY
4.EXIT
Enter your choice for the operation:3
The stack elements are:
TOP |2|
|4|
1.PUSH
2.POP
3.SHOW OR DISPLAY
4.EXIT
Enter your choice for the operation:4
Press any key to continue…
RESULT
Thus C program to implement Stack ADT using Array was written, executed and output is
verified successfully.
11
Ex.No:1b ARRAY IMPLEMENTATION OF QUEUE ADT
AIM
ALGORITHM
Step 3: Ask the user for the operation like insert, delete, display and exit.
Step 4: According to the option entered, access its respective function using switch statement.
Step 5: In the function insert(), firstly check if the queue is full. If it is, then print the output as
“Queue Overflow”. Otherwise take the number to be inserted as input and store it in the variable
add_item. Copy the variable add_item to the array queue_array[] and increment the variable rear by
1.
Step 6: In the function delete(), firstly check if the queue is empty. If it is, then print the
output as “Queue Underflow”. Otherwise print the first element of the array queue_array[]
and decrement the variable front by 1.
Step 7: In the function display(), using for loop print all the elements of the array starting
from front to rear.
Step 8: Stop
PROGRAM
#include <stdio.h>
#define MAX 50
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
12
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /*End of switch*/
} /*End of while*/
} /*End of main()*/
insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
return 0;
}
/*End of insert()*/
delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
return;
} /*End of delete() */
display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
return 0;
}
/*End of display() */
13
OUTPUT
RESULT
Thus C program to implement Queue ADT using Array was written, executed and output is
verified successfully.
14
Ex.No:1c ARRAY IMPLEMENTATION OF CIRCULAR QUEUE ADT
AIM
ALGORITHM
Step 3: Ask the user for the operation like insert, delete, display and exit.
Step 4: According to the option entered, access its respective function using switch statement.
Step 5: In the function insert(), firstly check if the queue is full. If it is, then print the output as
“Queue Overflow”. Otherwise take the number to be inserted as input and store it in the variable
add_item. Copy the variable add_item to the array queue_array[] and increment the variable rear
by 1.
Step 6: In the function delete(), firstly check if the queue is empty. If it is, then print the
output as “Queue Underflow”. Otherwise print the first element of the array
queue_array[] and decrement the variable front by 1.
Step 7: In the function display(), using for loop print all the elements of the array starting
from front to rear.
Step 8: Stop
PROGRAM
int front = - 1;
int rear = - 1;
int main()
{
int n, ch;
int queue[size];
do
{
printf("\n\n Circular Queue:\n1. Insert \n2. Delete\n3. Display\n0. Exit");
15
printf("\nEnter Choice 0-3? : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter number: ");
scanf("%d", &n);
insertq(queue, n);
break;
case 2:
deleteq(queue);
break;
case 3:
display(queue);
break;
}
}while (ch != 0);
}
16
printf("%d ", queue[i]);
}
for (i = 0; i <= rear; i++)
printf("%d ", queue[i]);
}
else
{
for (i = front; i <= rear; i++)
printf("%d ", queue[i]);
}
}
RESULT
Thus C program to implement Circular Queue ADT using Array was written, executed and
output is verified successfully.
17
Ex.No: 2 IMPLEMENTATION OF SINGLY LINKED LIST
AIM
ALGORTIHM
Step 4: In main (), using do-while loop call the different operations based on user choice.
Step 5: Perform the operations such as creating a list, Inserting an element into the list, Deleting
an element from the list, Check for duplication, Find the previous and next element in the list, sort
the list and display the required result. Step 6: Stop the program.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*head=NULL;
void insertend()
{
struct node *new,*temp;
new=(struct node*)malloc(sizeof(struct node));
printf("Enter the data ");
scanf("%d",&new->data);
new->next=NULL;
if(head==NULL)
{
head=new;
}
else
{
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
18
}
temp->next=new;
}
}
void insertbeg()
{
struct node *new;
new=(struct node*)malloc(sizeof(struct node));
printf("Enter the data ");
scanf("%d",&new->data);
new->next=head;
head=new;
}
void insertafter()
{
int pos,i;
struct node *new,*temp;
new=(struct node*)malloc(sizeof(struct node));
printf("Enter the data ");
scanf("%d",&new->data);
printf("Enter the position after which data to be added ");
scanf("%d",&pos);
temp=head;
for(i=0;i<pos-1;i++)
{
temp=temp->next;
if(temp==NULL)
{
printf("There are less than %d elements",pos);
return;
}
}
new->next=temp->next;
temp->next=new;
}
void delnode()
{
int x;
struct node *temp,*a;
printf("Enter data to be deleted ");
scanf("%d",&x);
temp=head;
while(temp->data!=x&&temp!=NULL)
{
a=temp;
temp=temp->next;
}
if(temp==NULL)
{
printf("Data does not exist\n");
return;
19
}
if(temp==head)
{
head=temp->next;
}
else
{
a->next=temp->next;
free(temp);
}
}
void display()
{
struct node *temp;
temp=head;
printf("List contains:\n");
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
void main()
{
int ch;
clrscr();
printf("Menu\n");
printf("1.Insert at the end\n");
printf("2.Insert at the beginning\n");
printf("3.Insert in between nodes\n");
printf("4.Delete a node\n");
printf("5.Display list\n");
printf("6.Exit\n");
do
{
printf("Enter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:insertend();
break;
case 2:insertbeg();
break;
case 3:insertafter();
break;
case 4:if(head==NULL)
printf("List underflow\n");
else
delnode();
break;
case 5:if(head==NULL)
20
printf("List underflow\n");
else
display();
break;
case 6:break;
default:printf("Wrong Choice\n");
}
}
while(ch!=6);
getch();
}
OUTPUT
Menu
1.Insert at the end
2. Insert at the beginning
3. Insert in between nodes
4. Delete a node
5. Display list
6.Exit
Enter your choice: 1
Enter the data : 5
Enter your choice 5
List contains: 5 6
Enter your choice: 2
Enter the data : 2
Enter your choice 5
List contains: 2 5 6
Enter your choice: 3
Enter the data : 8
Enter the position after which the data to be added : 2
Enter your choice 5
List contains: 2 5 8 6
Enter your choice: 4
Enter the data to be deleted : 8
Enter your choice 5
List contains: 2 5 6
Enter your choice: 6
RESULT
Thus C program to implement List ADT using Linked List was written, executed and
output is verified successfully.
21
Ex.No: 3a LINKED LIST IMPLEMENTATION OF LIST ADT
AIM
ALGORTIHM
Step 4: In main (), using do-while loop call the different operations based on user choice.
Step 5: Perform the operations such as creating a list, Inserting an element into the list, Deleting
an element from the list, Check for duplication, Find the previous and next element in the list, sort
the list and display the required result. Step 6: Stop the program.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*head=NULL;
void insertend()
{
struct node *new,*temp;
new=(struct node*)malloc(sizeof(struct node));
printf("Enter the data ");
scanf("%d",&new->data);
new->next=NULL;
if(head==NULL)
{
head=new;
}
else
{
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
22
temp->next=new;
}
}
void insertbeg()
{
struct node *new;
new=(struct node*)malloc(sizeof(struct node));
printf("Enter the data ");
scanf("%d",&new->data);
new->next=head;
head=new;
}
void insertafter()
{
int pos,i;
struct node *new,*temp;
new=(struct node*)malloc(sizeof(struct node));
printf("Enter the data ");
scanf("%d",&new->data);
printf("Enter the position after which data to be added ");
scanf("%d",&pos);
temp=head;
for(i=0;i<pos-1;i++)
{
temp=temp->next;
if(temp==NULL)
{
printf("There are less than %d elements",pos);
return;
}
}
new->next=temp->next;
temp->next=new;
}
void delnode()
{
int x;
struct node *temp,*a;
printf("Enter data to be deleted ");
scanf("%d",&x);
temp=head;
while(temp->data!=x&&temp!=NULL)
{
a=temp;
temp=temp->next;
}
if(temp==NULL)
{
printf("Data does not exist\n");
return;
}
23
if(temp==head)
{
head=temp->next;
}
else
{
a->next=temp->next;
free(temp);
}
}
void display()
{
struct node *temp;
temp=head;
printf("List contains:\n");
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
void main()
{
int ch;
clrscr();
printf("Menu\n");
printf("1.Insert at the end\n");
printf("2.Insert at the beginning\n");
printf("3.Insert in between nodes\n");
printf("4.Delete a node\n");
printf("5.Display list\n");
printf("6.Exit\n");
do
{
printf("Enter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:insertend();
break;
case 2:insertbeg();
break;
case 3:insertafter();
break;
case 4:if(head==NULL)
printf("List underflow\n");
else
delnode();
break;
case 5:if(head==NULL)
printf("List underflow\n");
24
else
display();
break;
case 6:break;
default:printf("Wrong Choice\n");
}
}
while(ch!=6);
getch();
}
OUTPUT
Menu
1.Insert at the end
2. Insert at the beginning
3. Insert in between nodes
4. Delete a node
5. Display list
6.Exit
Enter your choice: 1
Enter the data : 5
Enter your choice 5
List contains: 5 6
Enter your choice: 2
Enter the data : 2
Enter your choice 5
List contains: 2 5 6
Enter your choice: 3
Enter the data : 8
Enter the position after which the data to be added : 2
Enter your choice 5
List contains: 2 5 8 6
Enter your choice: 4
Enter the data to be deleted : 8
Enter your choice 5
List contains: 2 5 6
Enter your choice: 6
RESULT
Thus C program to implement List ADT using Linked List was written, executed and
output is verified successfully.
25
Ex.No: 3b LINKED LIST IMPLEMENTATION OF STACK ADT
AIM
ALGORITHM
PROGRAM
#include<stdio.h>
#include<conio.h>
struct Node
{
int Data;
struct Node *next;
}*top;
void popStack()
{
struct Node *var=top;
if(var==top)
{
top = top->next;
free(var);
}
else
printf("\nStack Empty");
}
void push(int value)
{
struct Node *temp;
temp=(struct Node *)malloc(sizeof(struct Node));
temp->Data=value;
if (top == NULL)
{
top=temp;
top->next=NULL;
}
else
{
temp->next=top;
top=temp;
}
}
26
void display()
{
struct Node *var=top;
if(var!=NULL)
{
printf("\nElements are as:\nTOP->");
while(var!=NULL)
{
printf("\t|%d|\n",var->Data);
var=var->next;
}
}
else
printf("\nStack is Empty");
}
void main()
{
int i=0,value;
top=NULL;
clrscr();
while(1)
{
printf(" \n1. Push to stack");
printf(" \n2. Pop from Stack");
printf(" \n3. Display data of Stack");
printf(" \n4. Exit\n");
printf(" \nChoose Option: ");
scanf(“%d”,&i);
switch(i)
{
case 1:
printf("\nEnter a value to push into Stack: ");
scanf(“%d”,&value);
push(value);
display();
break;
case 2:
popStack();
display();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\nwrong choice for operation");
getch();
}
}
}
27
OUTPUT
1. Push to stack
2. Pop from stack
3. Display data of stack
Choose Option: 1
Enter a value to push into Stack: 4
Elements are as Top |4|
Choose Option: 1
Enter a value to push into Stack: 8
Elements are as Top |8|
|4|
Choose Option: 1
Enter a value to push into Stack: 8
Elements are as Top |1|
|8|
|4|
1. Push to stack
2. Pop from stack
3. Display data of stack
Choose Option: 2
Element are as TOP|8 |
|4|
1. Push to stack
2. Pop from stack
3. Display data of stack
Choose Option: 3
Element are as TOP|8 |
|4|
1. Push to stack
2. Pop from stack
3. Display data of stack
Choose Option: 4
Press any key to continue. . .
RESULT
Thus C program to implement Stack ADT using Linked List was written, executed and
output is verified successfully.
28
Ex.No: 3c LINKED LIST IMPLEMENTATION OF QUEUE ADT
AIM
ALGORITHM
Step 3: Ask the user for the operation like insert, delete, display and exit.
Step 4: According to the option entered, access its respective function using switch statement.
Step 5: In the function insert(), firstly check if the queue is full. If it is, then print the output as
“Queue Overflow”. Otherwise take the number to be inserted as input and store it in the variable
add_item. Copy the variable add_item to the array queue_array[] and increment the variable rear
by 1.
Step 6: In the function delete(), firstly check if the queue is empty. If it is, then print the
output as “Queue Underflow”. Otherwise print the first element of the array
queue_array[] and decrement the variable front by 1.
Step 7: In the function display(), using for loop print all the elements of the array starting
from front to rear.
Step 8: Stop
PROGRAM
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;
int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();
int count = 0;
29
void main()
{
int no, ch, e;
printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
void create()
30
{
front = rear = NULL;
}
void queuesize()
{
printf("\n Queue size : %d", count);
}
void display()
{
front1 = front;
if ((front1 == NULL) && (rear ==NULL))
{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}
void deq()
{
front1 = front;
if (front1 == NULL)
{
31
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d",front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d",front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}
void empty()
{
if ((front == NULL) && (rear ==NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}
32
OUTPUT
1 - Enque
2 - Deque
3 - Front element
4 - Empty
5 - Exit
6 - Display
7 - Queue size
Enter choice : 1
Enter data : 14
Enter choice : 1
Enter data : 85
Enter choice : 1
Enter data : 38
Enter choice : 3
Front element : 14
Enter choice : 6
14 85 38
Enter choice : 7
Queue size : 3
Enter choice : 2
Dequed value : 14
Enter choice : 6
85 38
Enter choice : 7
Queue size : 2
Enter choice : 4
Queue not empty
Enter choice : 5
RESULT
Thus C program to implement Queue ADT using Linked List was written, executed and
output is verified successfully.
33
Ex.No: 4 IMPLEMENTATION OF POLYNOMIAL MANIPULATION USING
LINKED LIST
AIM
ALGORITHM
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
struct node {
int coefficient, exponent;
struct node *next;
};
34
struct node *lPtr, *pPtr, *qPtr = *myNode;
lPtr = buildNode(coefficient, exponent);
}
else if ((exponent < pPtr->exponent) && (exponent > qPtr->exponent){
lPtr->next = qPtr;
pPtr->next = lPtr;
break;
}
}
return;
}
/* inserting new node with resultant data into the output list (n1) */
void polynomial_add(struct node **n1, int coefficient, int exponent) {
struct node *x = NULL, *temp = *n1;
if (*n1 == NULL || (*n1)->exponent < exponent) {
/* adding at the front */
*n1 = x = buildNode(coefficient, exponent);
(*n1)->next = temp;
} else {
while (temp) {
if (temp->exponent == exponent) {
/* updating the co-efficient value alone */
temp->coefficient = temp->coefficient + coefficient;
return;
}
if (temp->exponent > exponent && (!temp->next || temp->next->exponent < exponent)) {
/* inserting in the middle or end */
x = buildNode(coefficient, exponent);
x->next = temp->next;
temp->next = x;
return;
}
temp = temp->next;
}
35
x->next = NULL;
temp->next = x;
}
}
void polynomial_multiply(struct node **n1, struct node *n2, struct node *n3) {
struct node * temp;
int coefficient, exponent;
temp = n3;
/* input list 1(n2) is absent, then output list is input list2 (n3) */
if (!n2) {
*n1 = n3;
} else if (!n3) {
/*
* list n3 is absent, then o/p list is n2
*/
*n1 = n2;
} else {
while (n2) {
while (n3) {
/* multiply coefficient & add exponents */
coefficient = n2->coefficient * n3->coefficient;
exponent = n2->exponent + n3->exponent;
n3 = n3->next;
/* insert the above manipulated data to o/p list */
polynomial_add(n1, coefficient, exponent);
}
n3 = temp;
n2 = n2->next;
}
}
return;
}
36
void polynomial_view(struct node *ptr) {
int i = 0;
int flag=0;
while (ptr) {
if(ptr->exponent != 0 || ptr->exponent != 1 ){
if(ptr->coefficient > 0 && flag==0 ){
printf("%dx^%d", ptr->coefficient,ptr->exponent);
flag++;
}
else if (ptr->coefficient > 0 && flag==1 )
printf("+%dx^%d", ptr->coefficient,ptr->exponent);
else if(ptr->coefficient < 0)
printf("%dx^%d", ptr->coefficient,ptr->exponent);
}
else if (ptr->exponent == 0){
if(ptr->coefficient > 0 && flag==0 ){
printf("%d", ptr->coefficient);
flag++;
}
else if (ptr->coefficient > 0 && flag==1 )
printf("+%d", ptr->coefficient);
else if(ptr->coefficient < 0)
printf("%d", ptr->coefficient);
}
else if( ptr->exponent == 1 ){
if(ptr->coefficient > 0 && flag==0 ){
printf("%dx", ptr->coefficient);
flag++;
}
else if (ptr->coefficient > 0 && flag==1 )
printf("+%dx", ptr->coefficient);
else if(ptr->coefficient < 0)
printf("%dx", ptr->coefficient);
}
ptr = ptr->next;
i++;
}
printf("\n");
return;
}
37
printf("Enter the coefficient part:");
scanf("%d", &coefficient);
printf("Enter the exponent part:");
scanf("%d",&exponent);
polynomial_insert(&hPtr1, coefficient, exponent);
}
printf("Enter the number of coefficients in the multiplier:");
scanf("%d",&count);
for(i=0;i<count;i++){
printf("Enter the coefficient part:");
scanf("%d", &coefficient);
printf("Enter the exponent part:");
scanf("%d",&exponent);
polynomial_insert(&hPtr2, coefficient, exponent);
}
printf("Polynomial Expression 1: ");
polynomial_view(hPtr1);
printf("Polynomial Expression 2: ");
polynomial_view(hPtr2);
printf("Output:\n");
polynomial_view(hPtr3);
printf("-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
hPtr1 = polynomial_deleteList(hPtr1);
hPtr2 = polynomial_deleteList(hPtr2);
hPtr3 = polynomial_deleteList(hPtr3);
return 0;
OUTPUT:
38
Output:
2x^6+11x^5+12x^4
RESULT:
Thus C program to implement Polynomial Manipulation using linked list was executed
and verified successfully.
39
Ex.No: 5 a CONVERTION OF INFIX TO POSTFIX EXPRESSION USING STACK
AIM
To write a C program to implement the conversion of infix to postfix expression using stack
ALGORITHM
Step 4: If the character is operator , push it onto the stack. If the stack operator has higher or equal
priority, then pop that operator from the stack and place it onto the output.
Step 6: If the character is a right parenthesis, pop all the operator from the stack till it encounter
left parenthesis, discard both parenthesis in the output.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
void main()
{
char exp[30],post[25];
int top=-1,i;
clrscr();
printf("enter the notation:");
scanf("%s",exp);
printf("postfix notation:");
for(i=0;i<strlen(exp);i++)
{
if(isalpha(exp[i]))
{
printf("%c",exp[i]);
while(post[top]=='*'|| post[top]=='/'|| post[top]=='^')
printf("%c",post[top--]);
}
else if(exp[i]==')')
{
while(post[top]!='(')
printf("%c",post[top--]);
40
top--;
}
else
{
post[++top]=exp[i];
} }
for(i=0;i<=top;i++)
if(post[i]!='('&&(post[i]!='*'|| post[i]!='-'|| post[i]!='^'))
printf("%c",post[i]);
getch();
}
OUTPUT
RESULT:
Thus C program to implement conversion of infix to postfix was executed and verified
successfully
41
Ex.No: 5b EVALUATION OF POSTFIX EXPRESSION USING STACK
AIM
Step 3: Create an empty stack and start scanning the postfix from left to right
Step 5: If the element is an operator O, pop twice and get A and B repectively. Calculate BOA
and push back to the stack
PROGRAM
#include<stdio.h>
#define MAX 20
typedef struct stack
{
int data[MAX];
int top;
}stack;
void init(stack *);
int empty(stack *);
int full(stack *);
int pop(stack *);
void push(stack *,int);
int evaluate(char x,int op1,int op2);
int main()
{
stack s;
char x;
int op1,op2,val;
init(&s);
printf("Enter the expression(eg: 59+3*)\nSingle digit operand and operators only:");
while((x=getchar())!='\n')
{
if(isdigit(x))
push(&s,x-48); //x-48 for removing the effect of ASCII
else
42
{
op2=pop(&s);
op1=pop(&s);
val=evaluate(x,op1,op2);
push(&s,val);
}
}
val=pop(&s);
printf("\nValue of expression=%d",val);
getch();
return 0;
}
int evaluate(char x,int op1,int op2)
{
if(x=='+')
return(op1+op2);
if(x=='-')
return(op1-op2);
if(x=='*')
return(op1*op2);
if(x=='/')
return(op1/op2);
if(x=='%')
return(op1%op2);
}
void init(stack *s)
{
s->top=-1;
}
int empty(stack *s)
{
if(s->top==-1)
return(1);
return(0);
}
int full(stack *s)
{
if(s->top==MAX-1)
return(1);
return(0);
}
void push(stack *s,int x)
{
s->top=s->top+1;
s->data[s->top]=x;
}
int pop(stack *s)
{
int x;
x=s->data[s->top];
s->top=s->top-1;
43
return(x);
}
OUTPUT
RESULT:
Thus C program to implement Evaluation of Postfix expression was executed and output is
verified successfully.
44
Ex.No: 6 IMPLEMENTATION OF BINARY SEARCH TREES
AIM
ALGORITHM
Step 2: Declare the left node, right node and root as pointer
PROGRAM
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
typedef struct tree *node;
node insert(int,node T);
void inorder(node T);
void preorder(node T);
void postorder(node T);
struct tree
{
int data;
struct tree *right,*left;
}*root;
void main()
{
node T=NULL;
int data,ch,i=0,n;
clrscr();
printf("\n Enter the no of elements in the tree:");
scanf("%d",&n);
printf("\n The Elements are:\n");
while(i<n)
{
scanf("%d",&data);
T=insert(data,T);
45
i++;
}
printf("1.INORDER\t 2.PREORDER\t 3.POSTORDER\t4.EXIT");
do
{
printf("\nEnter ur choice");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Inorder traversal of the given Tree \n");
inorder(T);
break;
case 2:
printf("preorder traversal of the given Tree \n");
preorder(T);
break;
case 3:
printf("postorder traversal of the given Tree \n");
postorder(T);
break;
default:
printf("Exit");
exit(0);
}
}
while(ch<4);
getch();
}
node insert(int X,node T)
{
struct tree*newnode;
newnode=malloc(sizeof(struct tree));
if(newnode==NULL)
printf("Out of space");
else
{
if(T==NULL)
{
newnode->data=X;
newnode->left=NULL;
newnode->right=NULL;
T=newnode;
}
else
{
if(X<T->data)
T->left=insert(X,T->left);
else
T->right=insert(X,T->right);
}}
46
return T;
}
void inorder(node T)
{
if(T!=NULL)
{
inorder(T->left);
printf("%d \t",T->data);
inorder(T->right);
}
}
void preorder(node T)
{
if(T!=NULL)
{
printf("%d \t",T->data);
preorder(T->left);
preorder(T->right);
}
}
void postorder(node T)
{
if(T!=NULL)
{
postorder(T->left);
postorder(T->right);
printf("%d \t",T->data);
}
}
OUTPUT
RESULT:
Thus C program to implement Binary Search Tree was executed and output is verified
successfully.
47
Ex.No: 7 IMPLEMENTATION OF AVL TREES
AIM
ALGORITHM
Step 3:Insertion:
Perform standard BST insert for w.
1.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.
2.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. Following are the possible 4 arrangements:
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)
Step 6: Based on the choice perform the operations such as creation of list, inserting an element,
displaying the list, deleting an element & searching an element. Step 6: Display the result based
on the choice.
PROGRAM
#include<stdio.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()
48
{
node *root=NULL;
int x,n,i,op;
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);
return 0;
}
node * insert(node *T,int x)
{
if(T==NULL)
{
T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;
}
49
else
if(x > T->data) // insert in right subtree
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);
else
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x < T->left->data)
T=LL(T);
else
T=LR(T);
}
T->ht=height(T);
return(T);
}
node * Delete(node *T,int x)
{
node *p;
if(T==NULL)
{
return NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=Delete(T->right,x);
if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
if(x<T->data)
{
T->left=Delete(T->left,x);
if(BF(T)==-2) //Rebalance during windup
if(BF(T->right)<=0)
T=RR(T);
else
T=RL(T);
}
else
50
{
//data to be deleted is found
if(T->right!=NULL)
{ //delete its inorder succesor
p=T->right;
while(p->left!= NULL)
p=p->left;
T->data=p->data;
T->right=Delete(T->right,p->data);
if(BF(T)==2)//Rebalance during windup
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);\
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}
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);
}
51
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);
}
52
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
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:3
Enter a data:7
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:4
53
Preorder sequence:
9(Bf=0)4(Bf=0)12(Bf=0)
Inorder sequence:
4(Bf=0)9(Bf=0)12(Bf=0)
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:5
RESULT:
Thus C program to implement AVL Trees and its operations are executed and its output is
verified successfully.
54
Ex.No: 8 IMPLEMENTATION OF HEAPS USING PRIORITY QUEUES
AIM
ALGORITHM
Step 4: A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at root
must be minimum among all keys present in Binary Heap. The same property must be recursively
true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap
Step 5: Based on the choice perform the operations such as creation of list, inserting an element,
displaying the list, deleting an element & searching an element.
PROGRAM
#include<stdio.h>
#include<math.h>
#define MAX 100/*Declaring the maximum size of the queue*/
void swap(int*,int*);
main()
{
int choice,num,n,a[MAX],data,s;
void display(int[],int);
void insert(int[],int,int,int);
int del_hi_priori(int[],int,int);
int lb=0;
n=0;/*Lower bound of the array is initialized to 0*/
while(1)
{
printf(".....MAIN MENU.....\n");
printf("1.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 : ");
55
scanf("%d",&data);
insert(a,n,data,lb);
n++;
break;
case 2:
s=del_hi_priori(a,n+1,lb);
if(s!=0)
printf("\nThe deleted value is : %d \n",s);
if(n>0)
n--;
break;
case 3:
printf("\n");
display(a,n);
break;
case 4:
return;
default:
printf("Invalid choice.n");
}
printf("\n");
}
}
void insert(int a[],int heapsize,int data,int lb)
{
int i,p;
int parent(int);
if(heapsize==MAX)
{
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;
}
}
int del_hi_priori(int a[],int heapsize,int lb)
{
int data,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];
56
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;
else
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;
}
int parent(int i)
{
float p;
p=((float)i/2.0)-1.0;
return ceil(p);
}
int left(int i)
{
return 2*i+1;
}
int right(int i)
{
return 2*i+2;
}
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");
}
void swap(int*p,int*q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
57
OUTPUT :
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 1
Enter data to be inserted : 52
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 1
Enter data to be inserted : 63
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 1
Enter data to be inserted : 45
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 1
Enter data to be inserted : 2
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 1
Enter data to be inserted : 99
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 3
99 63 45 2 52
.....MAIN MENU.....
58
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 2
The deleted value is : 99
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 3
63 52 45 2
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 2
The deleted value is : 63
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 2
The deleted value is : 52
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 3
45 2
.....MAIN MENU.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your choice : 4
RESULT:
Thus C program to implement Binary heap using priority queue was executed and output is
verified successfully.
59
Ex.No: 9 IMPLEMENTATION OF DIJKSTRA ALGORITHM
AIM
ALGORITHM
Step 3: Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest
path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set
is empty
Step 4: Assign a distance value to all vertices in the input graph. Initialize all distance values as
INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
Step 6: Pick a vertex u which is not there in sptSet and has minimum distance value
60
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
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];
for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
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++;
}
for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
61
OUTPUT
Enter no of vertices: 5
Enter the adjacency matrix:
0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 10 60 0
RESULT:
Thus C program to implement Dijkstra’s algorithm was executed and output is verified
successfully.
62
Ex.No: 10 IMPLEMENTATION OF PRIMS ALGORITHM
AIM
ALGORITHM
Step 5: At each setp, it finds a shortest edge(u,v) such that the cost of (u,v) is the smallest among
all the edges, where ‘u’ is in MST and ‘v’ is not in MST
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);
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");
63
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;
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])
{
64
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}
OUTPUT
RESULT:
Thus C program to implement Prim’s algorithm was executed and output is verified
successfully.
65
Ex.No: 11a IMPLEMENTATION OF SEARCHING AND SORTING
(LINEAR SEARCH)
AIM
ALGORITHM
Step 5: Every item is checked and if a match is found then that particular item is returned
Step 6: Otherwise the search continues till the end of the data collection
PROGRAM
#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
66
OUTPUT
RESULT:
Thus C program to implement Linear Search was executed and output is verified successfully.
67
Ex.No: 11b IMPLEMENTATION OF SEARCHING AND SORTING
(BINARY SEARCH)
AIM
ALGORITHM
PROGRAM
//BINARY SEARCH
#include<stdio.h>
#include<conio.h>
void main()
{
int flag=0,a[20],n,pos,i,item,low,high,mid;
void sort(int[],int);
clrscr();
printf("Enter the no.of numbers\n");
scanf("%d",&n);
printf("Enter the numbers\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
sort(a,n);
printf("Enter the data to be searched");
scanf("%d",&item);
low=1;
high=n;
while(low<=high)
{
mid=(low+high)/2;
if(item==a[mid])
{
flag=1;
break;
68
}
else if(item>a[mid])
low=mid+1;
else
high=mid-1;
}
if(flag==0)
printf("The element %d is not present in the array \n",item);
else
printf("The element %d is present in the array \n",item);
getch();
}
void sort(int a[],int n)
{
int i,j,temp;
for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
OUTPUT
Enter the number of elements in a array: 5
Enter the numbers: 3 7 0 2 1
Enter the data to be searched : 0
The number 0 is present in the array
RESULT:
Thus C program to implement Binary Search was executed and output is verified
successfully.
69
Ex.No: 11c IMPLEMENTATION OF SEARCHING AND SORTING
(BUBBLE SORT)
AIM
To write a C program to implement sorting and searching technique using bubble sort
ALGORITHM
Step 4: The elements are swapped in case the one on the left is greater then the element on the
right.
PROGRAM
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
clrscr();
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
70
printf("%d\n", array[c]);
getch();
return 0;
OUTPUT
RESULT:
Thus C program to implement Bubble sort was executed and output is verified successfully.
71
Ex.No: 11d IMPLEMENTATION OF SEARCHING AND SORTING
(INSERTION SORT)
AIM
To write a C program to implement searching and sorting technique using insertion sort
ALGORITHM
Step 3: Take the elements from the list one by one and inserting them in their position into new
sorted list
Step 5: During ith pass, it will insert the ith element A[i] into right place.
PROGRAM
#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
clrscr();
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++) {
scanf("%d", &array[c]);
}
72
printf("%d\n", array[c]);
}
getch();
return 0;
}
OUTPUT:
RESULT:
Thus C program to implement Insertion Sort was executed and output is verified
successfully.
73
Ex.No: 11e IMPLEMENTATION OF SEARCHING AND SORTING
(SHELL SORT)
AIM
To write a C program to implement searching and sorting technique using shell sort.
ALGORITHM
Step 5: In the next pass, value of K is reduced and then sort the reduced array elements
PROGRAM
#include <stdio.h>
void shellsort(int arr[], int num)
{
int i, j, k, tmp;
for (i = num / 2; i > 0; i = i / 2)
{
for (j = i; j < num; j++)
{
for(k = j - i; k >= 0; k = k - i)
{
if (arr[k+i] >= arr[k])
break;
else
{
tmp = arr[k];
arr[k] = arr[k+i];
arr[k+i] = tmp;
}
}
}
}
}
int main()
{
int arr[30];
74
int k, num;
clrscr();
printf("Enter total no. of elements : ");
scanf("%d", &num);
printf("\nEnter %d numbers: ", num);
OUTPUT
RESULT:
Thus C program to implement Shell Sort was executed and output is verified successfully.
75
Ex.No: 11f IMPLEMENTATION OF SEARCHING AND SORTING
(MERGE SORT)
AIM
To write a C program to implement searching and sorting technique using merge sort
ALGORITHM
Step 3: Take two input array as A and B and one output array as C
Step 4: First element of A array and B array are compared, then the smallest element is stored in
the output array C
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) {
int l1, l2, i;
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
while(l1 <= mid)
b[i++] = a[l1++];
while(l2 <= high)
b[i++] = a[l2++];
for(i = low; i <= high; i++)
a[i] = b[i];
}
void sort(int low, int high) {
int mid;
if(low < high) {
mid = (low + high) / 2;
76
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else {
return;
}
}
int main()
{
int i;
clrscr();
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]);
getch();
return 0;
}
OUTPUT
RESULT:
Thus C program to implement Shell Sort was executed and output is verified successfully.
77
Ex.No: 11g IMPLEMENTATION OF SEARCHING AND SORTING
(QUICK SORT)
AIM
ALGORITHM
Step 5: Target of partitions is, given an array and an element x of array as pivot, put x at its
correct position in sorted array and put all smaller elements (smaller than x) before x, and put all
greater elements (greater than x) after x.
Step 6: All this should be done in linear time and display the numbers in sorted order
PROGRAM
#include <stdio.h>
void sort_numbers_ascending(int number[], int count)
{
int temp, i, j, k;
for (j = 0; j < count; ++j)
{
for (k = j + 1; k < count; ++k)
{
if (number[j] > number[k])
{
temp = number[j];
number[j] = number[k];
number[k] = temp;
}
}
}
printf("Numbers in ascending order:\n");
for (i = 0; i < count; ++i)
printf("%d\n", number[i]);
}
void main()
{
78
int i, count, number[20];
clrscr();
printf("How many numbers you are gonna enter:");
scanf("%d", &count);
printf("\nEnter the numbers one by one:");
for (i = 0; i < count; ++i)
scanf("%d", &number[i]);
sort_numbers_ascending(number, count);
getch();
}
OUTPUT
RESULT:
Thus C program to implement Quick Sort was executed and output is verified successfully.
79
Ex.No: 12a IMPLEMENTATION OF HASHING
(LINEAR PROBING)
AIM
ALGORITHM
Step 3: In collision situation, the linear probing table will look onto to subsequent hash
elements until the first free space is found.
Step 4: This traversal is known as probing the table; and as it goes by one element at a time, it
is linear probing.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
void main()
{
int a[MAX],num,key,i;
char ans;
int create(int);
void linear_prob(int[],int,int);
void display(int[]);
clrscr();
printf("\nCollision Handling by Linear Probing");
for(i=0;i<MAX;i++)
a[i]=-1;
do
{
printf("\nEnter the number:");
scanf("%d",&num);
key=create(num);
linear_prob(a,key,num);
printf("\nDo you want to continue?");
ans=getch();
}while(ans=='y');
80
display(a);
}
int create(int num)
{
int key;
key=num%10;
return key;
}
void linear_prob(int a[MAX],int key,int num)
{
int flag,i,count=0;
void display(int a[]);
flag=0;
if(a[key]==-1)
a[key]=num;
else
{
i=0;
while(i<MAX)
{
if(a[i]!=-1)
count++;
i++;
}
if(count==MAX)
{
printf("\nHash Table is full");
display(a);
getch();
exit(1);
}
for(i=key+1;i<MAX;i++)
if(a[i]==-1)
{
a[i]=num;
flag=1;
break;
}
for(i=0;i<key&&flag==0;i++)
if(a[i]==-1)
{
a[i]=num;
flag=1;
break;
}
}
81
int i;
printf("\nThe Hash Table is ...\n");
for(i=0;i<MAX;i++)
printf("\n %d %d",i,a[i]);
getch();
}
OUTPUT
Do u want to continue?
Enter the number:
2
Do u want to continue?
Enter the number:
6
Do u want to continue?
The Hash Table is ….
0 -1
1 -1
2 2
3 -1
4 -1
5 5
6 8
7 -1
RESULT:
Thus C program to implement Hashing using Linear Probing was executed and output is
verified successfully.
82
Ex.No: 12b IMPLEMENTATION OF HASHING
(QUADRATIC PROBING)
AIM
ALGORITHM
3. Corresponding to the key, an index will be generated i.e every key is stored in a particular array index.
4. Using the generated index, access the data located in that array index.
5. In case of absence of data, create one and insert the data item (key and value) into it and increment the
size of hash table.
6. In case the data exists, probe through the subsequent elements (looping back if necessary) for free
space to insert new data item.
7. To display all the elements of hash table, element at each index is accessed (via for loop).
8. To remove a key from hash table, we will first calculate its index and delete it if key matches, else
probe through elements until we find key or an empty space where not a single data has been entered
(means data does not exist in the hash table).
9. Exit
PROGRAM
#include<stdio.h>
#include<stdlib.h>
/* each hash table item has a flag (status) and data (consisting of key and value) */
struct hashtable_item
{
int flag;
83
/*
* flag = 0 : data does not exist
* flag = 1 : data exists at given array location
* flag = 2 : data was present at least once
*/
struct item *data;
};
int i = index;
int h = 1;
if (array[i].data->key == key)
{
84
}
i = (i + (h * h)) % max;
h++;
if (i == index)
{
printf("\n Hash table is full, cannot add more elements \n");
return;
}
array[i].flag = 1;
array[i].data = new_item;
printf("\n Key (%d) has been inserted\n", key);
size++;
/* probing through the hash table until we reach at location where there had not been
an element even once */
while (array[i].flag != 0)
{
if (array[i].flag == 1 && array[i].data->key == key)
{
/* case where data exists at the location and its key matches to the
given key */
array[i].flag = 2;
array[i].data = NULL;
size--;
printf("\n Key (%d) has been removed \n", key);
return;
}
i = (i + (h * h)) % max;
h++;
if (i == index)
{
break;
}
}
printf("\n Key does not exist \n");
85
{
int i;
for(i = 0; i < max; i++)
{
if (array[i].flag != 1)
{
printf("\n Array[%d] has no elements \n", i);
}
else
{
printf("\n Array[%d] has elements \n %d (key) and %d (value) \n",
i, array[i].data->key, array[i].data->value);
}
}
int size_of_hashtable()
{
return size;
}
void main()
{
int choice, key, value, n, c;
clrscr();
do {
printf("Implementation of Hash Table in C with Quadratic Probing.\n\n");
printf("MENU-: \n1.Inserting item in the Hash table"
"\n2.Removing item from the Hash table"
"\n3.Check the size of Hash table"
"\n4.Display Hash table"
"\n\n Please enter your choice-:");
scanf("%d", &choice);
switch(choice)
{
case 1:
break;
case 2:
86
printf("Deleting in Hash table \n Enter the key to delete-:");
scanf("%d", &key);
remove_element(key);
break;
case 3:
n = size_of_hashtable();
printf("Size of Hash table is-:%d\n", n);
break;
case 4:
display();
break;
default:
printf("Wrong Input\n");
}while(c == 1);
getch();
OUTPUT:
87
2. Removing item from the Hash table
3. Check the size of Hash table
4. Display Hash table
88
Implementation of Hash Table in C with Quadratic Probing
MENU-:
1. Inserting item in the Hash table
2. Removing item from the Hash table
3. Check the size of Hash table
4. Display Hash table
89
4. Display Hash table
RESULT:
Thus C program to implement Hashing using Quadratic Probing was executed and output is
verified successfully.
90