0% found this document useful (0 votes)
14 views85 pages

CS3311 Datastructures Laboratory

DSA

Uploaded by

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

CS3311 Datastructures Laboratory

DSA

Uploaded by

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

ARM COLLEGE OF ENGINEERING AND TECHNOLOGY

SATTAMANGALAM, MARAIMALAI NAGAR, CHENNAI, TAMIL NADU. PIN-603 209.

ARMCET
(Approved by AICTE & Affiliated to Anna University)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS3311 DATA STRUCTURES LABORATORY


2023-2024

Name of the Student :

Registration Number :

Year of Study :

Semester :
ARM COLLEGE OF ENGINEERING AND TECHNOLOGY
SATTAMANGALAM, MARAIMALAI NAGAR, CHENNAI, TAMIL NADU. PIN-603 209.

ARMCET
(Approved by AICTE & Affiliated to Anna University)

BONAFIDE CERTIFICATE

Reg. No.

Certified that this is a Bonafide Record of Practical Work done by


Mr. /Ms ……………………………………………………………………………………………...
of B.E/ B.Tech ………………………………………………………………………………….
of ……… Semester in ……………………………………………………………………………….
during the academic year…………………

Signature of Lab-In charge Signature of Head of Dept.

Submitted for the practical Examination held on: …./…./…….

Internal Examiner External Examiner


INDEX

S. No DATE NAME OF THE EXPERIMENT PAGE SIGN


NO.
S. No DATE NAME OF THE EXPERIMENT PAGE SIGN
NO.
Ex. No. 1a Array implementation of Queue ADT
Date:

AIM
To implement queue operations using array.

ALGORITHM
1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
If choice = 1
thenIfrear
<max -1
Increment rear
Store element at current position of rear
Else
Print Queue Full
Else If choice = 2
then Iffront = –1 then
Print Queue empty
Else
Display current front
elementIncrement front
Else If choice = 3 then
Display queue elements starting from front to rear.
6.Stop
PROGRAM

/* Queue Operation using Arrays */

#include <stdio.h>
#include <conio.h>

#define max 5
static int queue[max];
int front = -1;
int rear = -1;

void insert(int x)
{
queue[++rear] = x;
if (front == -1)
front = 0;
}

int remove()
{

int val;
val = queue[front];
if (front==rear && rear==max-1)
front = rear = -1;
else
front ++;
return (val);
}

void view()
{
int i;

if (front == -1)
printf("\n Queue Empty \n");
else
{
printf("\n Front-->");
for(i=front; i<=rear; i++)
printf("%4d", queue[i]);
printf(" <--Rear\n");
}
}

void main()
{
int ch= 0,val;
clrscr();
while(ch != 4)
{
printf("\n QUEUE OPERATION \n");
printf("1.INSERT");
printf("2.DELETE");
printf("3.VIEW");
printf("4.QUIT\n");
printf("Enter Choice :");
scanf("%d", &ch);
switch(ch)
{
case 1:
if(rear < max-1)
{
printf("\n Enter element to be inserted : ");
scanf("%d", &val);
insert(val);
}
else
printf("\n Queue Full \n");
break;
case 2:
if(front == -1)

printf("\n Queue Empty \n");


else
{
val = remove();
printf("\n Element deleted : %d \n", val);
}
break;
case 3:
view();
break;
case 4:
exit(0);
default:
printf("\n Invalid Choice \n");
}
}
}
OUTPUT

QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1

Enter element to be inserted: 12

QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1

Enter element to be inserted: 23

QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1

Enter element to be inserted: 34

QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1

Enter element to be inserted: 45

QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1

Enter element to be inserted: 56

QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1

Queue Full

QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 3

Front--> 12 23 34 45 56 <--Rear

RESULT

Thus, the C program for the implementation of array queue in ADT is executed successfully.
Ex. No. 1b Array implementation of Stack ADT
Date:

AIM
To implement stack operations using array.
ALGORITHM
1. Start
2. Define a array stack of size max = 5
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
If top < max -1
Increment top
Store element at current position of top
Else
Print Stack overflow
Else If choice = 2 then
If top < 0 then
Print Stack underflow
Else
Display current top
elementDecrement top
Else If choice = 3 then
Display stack elements starting from top
7. Stop
PROGRAM

/* Stack Operation using Arrays */

#include <stdio.h>
#include <conio.h>

#define max 5

static int stack[max];


int top = -1;

void push(int x)
{
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("\nSTACK OPERATION”);
printf("1.PUSH ");
printf(“2.POP”);
printf(“3.VIEW”);
printf("4.QUIT \n"); 0.
printf("Enter Choice :");
scanf("%d", &ch);
switch(ch)
{
case 1:
if(top < max-1)
{
printf("\nEnter Stack element : ");
scanf("%d",&val);
push(val);
}
else

printf("\n Stack Overflow \n");


break;
case 2:
if(top < 0)
printf("\n Stack Underflow \n");
else
{
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");
}
}
}

OUTPUT

STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 1

Enter Stack element: 12

STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 1

Enter Stack element: 23


STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 1

Enter Stack element: 34

STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 1

Enter Stack element: 45

STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 3

Top - > 45 34 23 12

STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 2

Popped element is 45

STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 3

Top--> 34 23 12

STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 4

RESULT

Thus the C program for the implementation of Stack using arrays is executed successfully.
Ex. No. 1c Array implementation of Circular Queue ADT
Date:

AIM
To implement Circular Queue operations using array.

ALGORITHM

Algorithm to insert an element in a circular queue

Step 1: IF (REAR+1) %MAX = FRONT


Write “OVERFLOW”
Goto step 4
[End OF IF]
Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE IF REAR = MAX - 1 and FRONT! = 0
SET REAR = 0
ELSE
SET REAR = (REAR + 1) % MAX
[END OF IF]
Step 3: SET QUEUE [REAR] = VAL
Step 4: EXIT

Algorithm to delete an element from the circular queue

Step 1: IF FRONT = -1
Write “UNDERFLOW”
Goto Step 4
[END of IF]
Step 2: SET VAL = QUEUE [FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]
Step 4: EXIT
PROGRAM

#include <stdio.h>
# define max 6
int queue[max]; // array declaration
int front=-1;
int rear=-1;
// function to insert an element in a circular queue
Void enqueue(int element)
{
if(front==-1 && rear==-1) // condition to check queue is empty
{
front=0;
rear=0;
queue[rear]=element;
}
else if((rear+1)%max==front) // condition to check queue is full
{
printf("Queue is overflow..");
}
else
{
rear=(rear+1)%max; // rear is incremented
queue[rear]=element; // assigning a value to the queue at the rear positin.
}}
// function to delete the element from the queue
int dequeue()
{
if ((front==-1) && (rear==-1)) // condition to check queue is empty
{
printf("\nQueue is underflow..");
}
else if(front==rear)
{
printf("\nThe dequeued element is %d", queue[front]); front=-
1;
rear=-1;
}
else {
printf("\nThe dequeued element is %d", queue[front]);
front=(front+1)%max;
}}
// function to display the elements of a queue

void display()
{
int i=front;
if(front==-1 && rear==-1)
{
printf("\n Queue is empty..");
}
else
{
printf("\nElements in a Queue are :");
while(i<=rear)
{
printf("%d,", queue[i]);
i=(i+1)%max;
} }}

int main()
{
int choice=1,x; // variables declaration
while(choice<4 && choice!=0) // while loop
{
printf("\n Press 1: Insert an element");
printf("\nPress 2: Delete an element");
printf("\nPress 3: Display the element");
printf("\nEnter your choice"); scanf("%d",
&choice);

switch(choice)
{
case 1:
printf("Enter the element which is to be inserted");
scanf("%d", &x);
enqueue(x);
break;
case 2:
dequeue();
break;
case 3:
display(); }}
return 0;
}
OUTPUT

RESULT:

Thus the C program for the implementation of Circular Queue ADT is executed successfully.
Ex.No:2 IMPLEMENTATION OF SINGLY LINKED LIST
Date:

AIM:

To write a program for Linked list implementation.

ALGORITHM:

Step1: Create nodes first, last; next, prev and cur then set the value as NULL.
Step 2: Read the list operation type.
Step 3: If operation type is create then process the following steps.
1. Allocate memory for node cur.
2. Read data in cur's data area.
3. Assign cur node as NULL.
4. Assign first=last=cur.
1. Allocate memory for node cur.
2. Read data in cur's data area.
3. Read the position the Data to be insert.
4. Availability of the position is true then assign cur's node as first and first=cur.
5. If availability of position is false then do following steps.
1.Assign next as cur and count as zero.
2. Repeat the following steps until count less than position.
1 .Assign prev as next
2. Next as prev of node.
3. Add count by one.
4. If prev as NULL then display the message INVALID POSITION.
5. If prev not equal to NULL then do the following steps.
1. Assign cur's node as prev's node.
2. Assign prev's node as cur.
1. Read the position .
2. Check list is Empty .If it is true display the message List empty.
3. If position is first.
1. Assign cur as first.
2. Assign First as first of node.
3. Reallocate the cur from memory.
4. If position is last.
1. Move the current node to prev.
2. cur's node as Null.
3. Reallocate the Last from memory.
4. Assign last as cur.
5. If position is enter Mediate.
1. Move the cur to required postion.
2. Move the Previous to cur's previous position
3. Move the Next to cur's Next position.
4. Now Assign previous of node as next.
5. Reallocate the cur from memory.
Step 4: If operation is traverse.
1. Assign current as first.
2. Repeat the following steps untill cur becomes NULL.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define null 0
typedef struct n
{
int data;
struct n*next;
}
node;
node*head=null,*newn,*temp,*t;
void insert();
void delete();
void view();
void main()
{
int choice;
clrscr();
printf("\n\t\t SINGLY LINKED LIST");
while (1)
{
printf("\n 1.Insert\t 2.Delete\t 3.View");
printf("\n Enter the choice:");
scanf("%d", &choice);
switch(choice)
{
case 1:insert();
break;
case 2:delete();
break;
case 3:view();
break;
case 4:exit(0);
break;
default: printf("\n Enter the correct option");
}
}
}
void insert()
{
int option,no;
newn=(node*)malloc(sizeof(node));
printf("Enter the data to be inserted : ");
scanf("%d",&newn->data);
newn->next=null;
printf("\n 1.Insert first\t 2.Insert middle\t 3.Insert last");
printf("\n Enter the option:");
scanf("%d", &option);
switch (option)
{
case 1:if(head==null)
head=newn;
else
{
newn-> next=head;
head=newn;
}
break;
case 2:if(head-> next==null)
printf("single entry list cannot perform insertion in the middle");
else
{
printf("\n entry the data which the node has to insert");
scanf("%d",&no);
temp=head;
while(temp->data!=no)
{
temp=temp-> next;
}
newn->next=temp->next;
temp->next = newn;
}
break;
case 3:temp=head;
if(head == null)
head=newn;
else
{
temp=head;
while(temp->next!=null)
{
temp=temp->next;
}
temp->next = newn;
}
break;
}
}
void delete()
{
int option,no;
if(head==null)
{
printf("empty list cannot perform deletion");
}
printf("1.Deletion at first\t 2.Deletion in middle\t 3.Deletion at last\n");
printf(“Enter the Option : “);
scanf("%d",&option);
switch (option)
{
case 1: temp=head;
head =head->next;
printf("The data deleted is %d",temp ->data);
free(temp);
break;
case 2:if(head->next == null)
printf("single entry list cannot perform deletion at middle");
else
{
printf("Enter the data which has to be deleted : ");
scanf("%d",&no);
temp=head;
while(temp->data!=no)
{
t=temp;
temp=temp->next;
}
printf("the data deleted is %d",temp->data);
t->next=temp->next;
free(temp);
}
break;
case 3:temp=head;
if(head->next == null)
{
printf("the data deleted is%d",head->data);
head=null;
}
else
{
while(temp->next!=null)
{
t=temp;
temp=temp->next;
printf("the data deleted is%d",temp->data);
free (temp);
}
}
break;
}
}
void view()
{
temp=head;
printf("Head-->");
while(temp!=null)
{
printf("%d->\t",temp->data);
temp=temp->next;
}
printf("NULL");
}
OUTPUT:
SINGLY LINKED LIST
1.Insert 2.Delete 3.View
Enter the choice: 1
Enter the data to be inserted : 11
1.Insert first 2.Insert middle 3.Insert last
Enter the option : 1
1.Insert 2.Delete 3.View

Enter the choice: 1


Enter the data to be inserted : 22
1.Insert first 2.Insert middle 3.Insert last
Enter the option : 3
1.Insert 2.Delete 3.View
Enter the choice: 1
Enter the data to be inserted : 33
1.Insert first 2.Insert middle 3.Insert last
Enter the option : 2
Enter the data after which the node has to insert : 11
1.Insert 2.Delete 3.View
Enter the choice:3
Head-->11 -> 33 -> 22 -> Null
1.Insert 2.Delete 3.View

Enter the choice:2


1.Deletion at first 2.Deletion in middle 3.Deletion at last
Enter the Option : 2
Enter the data after which has to be deleted 22
The data deleted is 22

RESULT:
Thus, the C program for Linked list implementation of List ADT was created, executed and
output was verified successfully.
Ex. No. 3a Linked list implementation of Stack ADT
Date:

AIM
To implement stack operations using linked list.

ALGORITHM
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to first node
Make head node point to new node
Else If choice = 2 then
Make temp node point to first node
Make head node point to next of temp node
Release memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop

PROGRAM

/* Stack using Single Linked List */

#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>

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

main()
{
int ch = 0;
int k;
struct node *h, *temp, *head;

/* Head node construction */


head = (struct node*) malloc(sizeof(struct node));
head->next = NULL;
while(1)
{
printf("\n Stack using Linked List \n");
printf("1->Push ");
printf("2->Pop ");
printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch);

switch(ch)
{
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node)));
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;
printf("Node %s deleted\n", h->label);
free(h);
break;
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);
}
}

}
OUTPUT

Stack using Linked List


1->Push 2->Pop 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 23
New node added

Stack using Linked List


1->Push 2->Pop 3->View 4->Exit
Enter your choice : 1
Enter label for new node : 34

Stack using Linked List


1- >Push 2->Pop 3->View 4->Exit
Enter your choice : 3
HEAD -> 34 -> 23 -> NULL

RESULT:

Thus push and pop operations of a stack was demonstrated using linked list.
Ex.No:3b
Date:
IMPLEMENTATION OF LINEAR QUEUE ADT USING LINKED LIST

AIM:

To write a C program for Queue using Linked implementation

ALGORITHM:

1. Define a struct for each node in the queue. Each node in the queue contains data and
link to the next node. Front and rear pointer points to first and last node inserted in the queue.
2.The operations on the queue are
a. INSERT data into the queue
b.DELETE data out of queue
3.PUSH DATA INTO STACK
a.Enter the data to be inserted into stack.
b.If TOP is NULL
i.The input data is the first node in stack.
ii.The link of the node is NULL.
iii.TOP points to that node.
c.If TOP is NOT NULL
i.The link of TOP points to the new node.
ii.TOP points to that node.
4.POP DATA FROM STACK
a.If TOP is NULL
i. the stack is empty
b.If TOP is NOT NULL
i.The link of TOP is the current TOP.
ii.The pervious TOP is popped from stack.

The stack represented by linked list is traversed to display its content


PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
typedef struct node
{
int data;
struct node *next;
}Q;
Q *front,*rear;
void main(void)
{
char ans;
int choice;
void insert();
Q *delet();
void display(Q*);
front=NULL;
rear=NULL;
do
{
printf("\n\tProgram For Queue Using Linked List\n");
printf("\n Main Menu");
printf("\n1.Insert\n2.Delete\n3.Display");
printf("\n Enter Your Choice");
scanf("%d",&choice);
switch(choice)
{
case 1 :insert();
break;
case 2 :front =delet();
break;
case 3 :display(front);
break;
default: printf("\nYou have entered Wrong Choice\n");
break;
}
printf("\nDo you want to continue?\n");
ans = getch();
}
while(ans =='y' || ans == 'Y');
getch();
}
Q *get_node(Q *temp)
{
temp =(Q*) malloc(sizeof(Q));
temp->next = NULL;
return temp;
}
void insert()
{
char ch;
Q *temp;
Clrscr();
temp =get_node(temp);/*allocates memory for temp node*/
printf("\n\n\n\tInsert the element in the Queue\n");
scanf("%d",&temp->data);
if(front == NULL)
{
front=temp;
rear=temp;
}
else
{
rear->next=temp;
rear=rear->next;
}
}
int Qempty(Q *front)
{
if(front==NULL)
return 1;
else
return 0;
}
Q *delet()
{
Q *temp; temp=front;
if(Qempty(front))
{
printf("\n\n\tSorry!The Queue IS Empty\n");
printf("\n Can not delete the element");
}
else
{
printf("\n\tThe deleted Element Is %d",temp->data);
front=front->next;/*deleting the front node*/
temp->next=NULL;
free(temp);
}
return front;
}
void display(Q *front)
{
if(Qempty(front))
printf("\n The Queue Is Empty\n");
else
{
printf("\n\t The Display Of Queue Is\n");
/*queue is displayed from front to rear*/
for(;front !=rear->next;front=front->next)
printf("\t%d",front->data);
}
getch();
}

OUTPUT:
Program For Queue Using Linked List
Main Menu
1.Insert
2.Delete
3.Display
Enter Your Choice1
Insert the element in the Queue 65
Do you want to continue?
Program For Queue Using Linked List
Main Menu
1.Insert
2.Delete
3.Display
Enter Your Choice 1
Insert the element in the Queue 71
Do you want to continue?
Program For Queue Using Linked List
Main Menu
1.Insert
2.Delete
3.Display

Enter Your Choice1


Insert the element in the Queue 51
Do you want to continue?
Program For Queue Using Linked List
Main Menu
1.Insert
2.Delete
3.Display
Enter Your Choice3
The Display Of Queue Is

65 71 51
Do you want to continue?
Program For Queue Using Linked List
Main Menu
1. Insert
2.Delete
3.Display
Enter Your Choice2
The deleted Element Is 65

Do you want to continue?

RESULT:

Thus, the C program for linked list implementation of Queue ADT was created, executed and output
was verified successfully.
Ex.No:4 IMPLEMENTATION OF POLYNOMIAL MANIPULATION USING
Date: LINKED LIST

AIM:

To write a program to implement polynomial equation using linked list.

ALGORITHM:

1. Get the two polynomials. First polynomial is P1 and second polynomial is P2


2. For addition of two polynomials if exponents of both the polynomials are same then we
ad d coefficients. For storing the result we will create the third linked lists say P3.
3. If Exponent of P2 is greater than exponent of P1 then keep the P3 as P2.
4. If Exponent of P2 is greater than exponent of P1 then keep the P3 as P1
5. If Exponent of P2 is equal to the exponent of P1 then add the coefficient of P1 and
coefficient of P2 as coefficient of P3.
6. Continue the above step from 3 to 5 until end o the two polynomials.
7. If any of the polynomial is ended keep P3 as the remaining polynomial.
8.Stop the execution.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct pnode
{
float coef;
int exp;
struct pnode *next;
}p;
void main()
{
p *p1,*p2,*p3;
p *get_poly(),*add(p*,p*);
void display(p*);
printf("\n Enter the first polynomial\n\n");
p1=get_poly();
printf("\nEnter the second polynomial is \n");
p2=get_poly();
printf("\nThe first polynomial is\n");
display(p1);
printf("\nThe second polynomial is\n");
display(p2);
p3=add(p1,p2);
printf("\nThe addition of the polynomials is...\n");
display(p3);
exit(0);
}
p *get_poly()
{
p *temp,*new,*last;
int Exp,flag;
float coef;
p *get_node();
char ans='y';
temp=NULL;
flag=TRUE;
printf("\nEnter the polynomial in descending order of exponent\n");
do
{
printf("\nEnter the Coefficient and Exponent of a temp:");
scanf("%f%d",&coef,&Exp);
New=(p*)malloc(sizeof(p));
if(New==NULL)
printf("memory cannot be allocated");
New->coef=coef;
New->exp=Exp;
New->next=NULL;
if(flag==TRUE)
{
temp=New;
last=temp;
flag=FALSE;
}
else
{
last->next=new;
last=new;
}
printf("\n Do you Want To Add more terms?(y/n)");
ans=getch();

32
}
while(ans=='y');
return(temp);
}
void display(p *head)
{
p *temp;
temp=head;
if(temp==NULL)
{
printf("The polynomial is empty\n");
getch();
return; }
printf("\n");
while(temp->next!=NULL)
{
printf("%0.1fx^%d+",temp->coef,temp->exp);
temp=temp->next;
}
printf("%0.1fx^%d",temp->coef,temp->exp);
getch();
}
p *add(p*first,p*second)
{
p *p1,*p2,*temp,*dummy;
char ch;
float coef;
p *append(int,float,p*);
p1=first;
p2=second;
temp=(p*)malloc(sizeof(p));
if(temp==NULL)
printf("\nMomorycan not be allocated");
dummy=temp;
while(p1 != NULL&&p2!= NULL)
{
if(p1->exp==p2->exp)

{
coef=p1->coef+p2->coef;
temp=append(p1->exp,coef,temp);
p1=p1->next;
p2=p2->next; }
else if(p1->exp<p2->exp)
{
coef=p2->coef;
temp=append(p2->exp,coef,temp);
p2=p2->next;
}
else if(p1->exp<p2->exp)
{
coef=p2->coef;
temp=append(p2->exp,coef,temp);
p2=p2->next; }
else if(p1->exp>p2->exp)
{
coef=p1->coef;
temp=append(p1->exp,coef,temp);
p1=p1-> next; }}
while(p1!=NULL)
{
temp=append(p1->exp,p1->coef,temp);
p1=p1-> next; }
while(p2!=NULL)
{
temp=append(p2->exp,p2->coef,temp);
p2=p2-> next; }
temp->next=NULL;
temp=dummy->next;
free(dummy);
return(temp); }
p *append(int Exp,floatcoef,p*temp)
{
p *New,*dummy;
New=(p*)malloc(sizeof(p));
if(New==NULL)
printf("\n Memory cannot be allocated\n");
New->exp=Exp;
New->coef=coef;
New->next=NULL;
dummy=temp;
dummy->next=New;
dummy=New;
return(dummy);
}
OUTPUT:
Enter the first polynomial
Enter the polynomial in descending order of exponent
Enter the Coefficient and Exponent of a temp: 5 3
Do you Want To Add more terms?(y/n)
Enter the Coefficient and Exponent of a temp:3 3
Do you Want To Add more terms?(y/n)
Enter the Coefficient and Exponent of a temp:2 2
Do you Want To Add more terms?(y/n)
Enter the Coefficient and Exponent of a temp:1 1
Do you Want To Add more terms?(y/n)
Enter the second polynomial is
Enter the polynomial in descending order of exponent
Enter the Coefficient and Exponent of a temp:4 3
Do you Want To Add more terms?(y/n)
Enter the Coefficient and Exponent of a temp: 3 3Do
you Want To Add more terms?(y/n)
Enter the Coefficient and Exponent of a temp:5 2
Do you Want To Add more terms?(y/n)
The first polynomial is
5.0x^3+3.0x^3+2.0x^2+1.0x^1
The second polynomial is
4.0x^3+3.0x^3+5.0x^2
The addition of the polynomials is...
9.0x^3+6.0x^3+7.0x^2+1.0x^1

RESULT:
Thus, a polynomial equation was implemented and executed successfully.
Ex. No: 5 Evaluating Postfix Expressions- Infix to Postfix Conversion
Date:

AIM

To convert infix expression to its postfix form using stack operations.

ALGORITHM
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expression character-by-character If
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.
Else
Push the input operator onto the stack
If character is a left parenthesis, then push it onto the stack.
If character is a right parenthesis, pop all operators from stack and print it until a
left parenthesis is encountered. Do not print the parenthesis. If character = $
then Pop out all operators, Print them and Stop

PROGRAM

/* Conversion of infix to postfix expression */

#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 20

int top = -1;


char stack[MAX];
char pop();
void push(char item);

int prcd(char symbol)


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

Int isoperator(char symbol)


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

break;
default:
return 0;
}
}

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


{
int i,symbol,j = 0;
stack[++top] = '#';
for(i=0;i<strlen(infix);i++)
{
symbol = infix[i];
if(isoperator(symbol) == 0)
{
postfix[j] = symbol;
j++;
}
else
{
if(symbol == '(')
push(symbol);
else if(symbol == ')')
{
while(stack[top] != '(')
{
postfix[j] = pop();
j++;
}
pop(); //pop out (.
}
else
{
if(prcd(symbol) > prcd(stack[top]))
push(symbol);
else
{
while(prcd(symbol) <= prcd(stack[top]))
{
postfix[j] = pop();
j++;
}
push(symbol);
}
}
}
}
while(stack[top] != '#')
{
postfix[j] = pop();

j++;
}
postfix[j] = '\0';
}

main()
{
char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string: ");
gets(infix);
convertip(infix, postfix);
printf("The corresponding postfix string is: ");
puts(postfix);
getch();
}
void push(char item)
{
top++;
stack[top] = item;
}
char pop()
{
char a;
a = stack[top];
top--;
return a;
}
OUTPUT
Enter the valid infix string: (a+b*c)/(d$e)
The corresponding postfix string is: abc*+de$/

Enter the valid infix string: a*b+c*d/e


The corresponding postfix string is: ab*cd*e/+

Enter the valid infix string: a+b*c+(d*e+f)*g


The corresponding postfix string is: abc*+de*f+g*+

RESULT
Thus the given infix expression was converted into postfix form using stack.
Ex. No:6 Implementation of Binary Search Tree
Date:

AIM
To insert and delete nodes in a binary search tree.

ALGORITHM

1. Create a structure with key and 2 pointer variable left and right.
2. Read the node to be inserted.
If (root==NULL)
root=node
else if (root>key<node-
>key) root->right=NULL
else
Root->left=node
3. For Deletion
if it is a leaf node
Remove immediately
Remove pointer between del node &
child if it is having one child
Remove link between del node&child
Link delnode is child with delnodes
parent
If it is a node with a children
Find min value in right subtree
Copy min value to delnode place
Delete the duplicate and stop.

4.Stop
PROGRAM

/* Binary Search Tree */

#include <stdio.h>
#include <stdlib.h>
struct node
{
int key;
struct node *left;
struct node *right;
};

struct node *newNode(int item)


{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

void inorder(struct node *root)


{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}

struct node* insert(struct node* node, int key)


{
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key); else
node->right = insert(node->right, key); return node;
}

struct node * minValueNode(struct node* node)


{
struct node* current = node;
while (current->left != NULL)
current = current->left;
return current;
}

struct node* deleteNode(struct node* root, int key)


{
struct node *temp;
if (root ==NULL)
return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);

else
{
if (root->left == NULL)
{
temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
temp = root->left;
free(root);
return temp;
}
temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);

}
return root;
}
Void main()
{
Struct node *root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
printf("Inorder traversal of the given tree \n");
inorder(root);
printf("\nDelete 20\n");
root = deleteNode(root, 20);
printf("Inorder traversal of the modified tree \n");
inorder(root);
printf("\nDelete 30\n");
root = deleteNode(root, 30);
printf("Inorder traversal of the modified tree \n");
inorder(root);
printf("\nDelete 50\n");
root = deleteNode(root, 50);
printf("Inorder traversal of the modified tree \n");
inorder(root);

}
OUTPUT
Inorder traversal of the given tree 20 30 40 50 60 70 80
Delete 20
Inorder traversal of the modified tree
30 40 50 60 70 80
Delete 30
Inorder traversal of the modified tree
40 50 60 70 80
Delete 50
Inorder traversal of the modified tree 40 60 70 80

RESULT

Thus nodes were inserted and deleted from a binary search tree.
Ex. No. 7 Implementation of AVL Tree
Date:

AIM
To perform insertion operation on an AVL tree and to maintain balance factor.

ALGORITHM
1. Start
2. Perform standard BST insert for w
3. Starting from w, travel up and find the first unbalanced node. Let z be
the first unbalanced node, y be the child of z that comes on the path from
w to z and x be the grandchild of z that comes on the path from w to z.
4. Re-balance the tree by performing appropriate rotations on the subtree
rooted with z. There can be 4 possible cases that needs to be handled as x, y and
z can be arranged in 4 ways.
a) y is left child of z and x is left child of y (Left Left Case)
b) y is left child of z and x is right child of y (Left Right Case)
c) y is right child of z and x is right child of y (Right Right Case)
d) y is right child of z and x is left child of y (Right Left Case)

5.Stop
PROGRAM

/* AVL Tree */

#include <stdio.h>
#include <conio.h>
#include <malloc.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"); 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;
}
else
{
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; 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;
}
else
{
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;
}
void inorder(node *root)
{
if(root == NULL)
return;
inorder(root->left);
printf("\n%4d", root->data);
inorder(root->right);
}
void view(node *root, int level)
{
int k;
if(root == NULL)
return;
view(root->right, level+1);
printf("\n");
for(k=0; k<level; k++)
printf(" ");
printf("%d", root->data);
view(root->left, level+1);
}

node* insertnode(int data, node *p)


{
node *a,*b;
if(p == NULL)
{
p=getnode();
copynode(p, data);
height = CHANGED;
return(p);
}
if(data < p->data)
{
p->left = insertnode(data, p->left);
if(height == CHANGED) {

switch(p->bfactor)
{
case -1:
p->bfactor = 0;
height = BALANCED;
break;
case 0:
p->bfactor = 1;
break;
case 1:
a = p->left;
if(a->bfactor == 1)
lefttoleft(&p, &a);
else
lefttoright(&p, &a, &b);
height = BALANCED;
break;
}
}
}

if(data > p->data)


{
p->right = insertnode(data, p->right);

if(height== CHANGED)
{
switch(p->bfactor)
{

case -1:
p->bfactor = 0;
height = BALANCED;
break;
case 0:
p->bfactor =-1;
break;
case 1:
a=p->right;
if(a->bfactor == -1)
righttoright(&p, &a);
else
righttoleft(&p, &a, &b);
height=BALANCED;
break;
}
}
}
return(p);
}

main()
{

int data, ch;


char choice = 'y';
node *root = NULL;
clrscr();
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);
else
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();
}

OUTPUT

Basic Operations in AVL tree


0.Display a menu list
1. Insert a node inAVL tree
2. View AVL tree
3.Exit
Enter your choice:1
Enter the value to be inserted 1

Enter your choice:1


Enter the value to be inserted 2

Enter your choice:1


Enter the value to be inserted 3

Right to Right AVL rotation

Enter your choice:1


Enter the value to be inserted 4

Enter your choice:1


Enter the value to be inserted 5

Right to Right AVL rotation


Enter your choice: 1
Enter the value to be inserted 6

Right to Right AVL rotation

Enter your choice: 1


Enter the value to be inserted 7

Right to Right AVL rotation

Enter your choice: 1


Enter the value to be inserted 8

Enter your choice: 2

Inorder traversal of AVL tree


1
2
3
4
5
6
7
8

AVL tree is
8
7
6
5
4
3
2
1
Enter your choice: 3

RESULT

Thus rotations were performed as a result of insertions to AVL Tree.


Ex. NO:8 Implementation of Heaps using Priority Queues
Date:

AIM:

To write a C program to implement Priority Queue using Binary Heaps.

ALGORITHM:

1. Initialize all necessary variables and functions.


2. Read the choices.
3. For insertion, read the element to be inserted.
4. If root is NULL, assign the given element as root.
5. If the element is equal to the root, print “Duplicate value”.
6. Else if element value is less than the root value, insert element at the left of the root.
7. Else insert right side of the root.
8. For deletion, get the priority for maximum or minimum.
9. If maximum, it deletes the root and rearranges the tree.
10. If minimum, it deletes the leaf.
11. End of the program

PROGRAM:
#include<stdio.h>
#include<math.h>
#define MAX 100
void swap(int*, int*);
void display(int[],int);
void insert(int[],int,int,int);
int del_hi_priori(int[],int,int);
int main()
{
int lb,choice,num,n,a[MAX],data,s;
choice = 0;
n=0;
lb=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[],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;
}
}
// DELETE
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]; 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;
}
//Returns Parent Index
int parent(int i)
{
float p;
p=((float)i/2.0)-1.0;
return ceil(p);
}
//Return Leftchild Index
int left(int i)
{
return 2*i+1;
}
//Return Rightchild Index
int right(int i)
{
return 2*i+2;
}
//-------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;
}

OUTPUT:
.....Main Menu.....
1.Insert.
2.Delete.
3.Display.

4.Quit.
Enter your Choice:3
Queue is Empty!!
.....Main Menu.....
1.Insert.
2.Delete.
3.Display.

4.Quit.
Enter your Choice:1
Enter Data to be inserted: 100
.....Main Menu.....
1.Insert.
2.Delete.
3.Display.

4.Quit.
Enter your Choice: 2
the deleted value is : 100
.....Main Menu.....
1.Insert.
2.Delete.
3.Display.

4.Quit.
Enter your Choice:4

RESULT:

Thus, the Priority Queue using Binary Heap is implemented and the result is verified successfully.
Ex. No. 9 Implementation of Dijkstra’s Algorithm
Date:

Aim

To find the shortest path for the given graph from a specified source to all other
vertices using Dijkstra’s algorithm

Algorithm
1. Start
2. Obtain no. of vertices and adjacency matrix for the given graph
3. Create cost matrix from adjacency matrix. C[i][j] is the cost of
going from vertex i to vertex j. If there is no edge between vertices i
and j then C[i][j] is infinity
4. Initialize visited[] to zero
5. Read source vertex and mark it as visited
6. Create the distance matrix, by storing the cost of vertices from vertex no. 0
to n-1 from the source vertex
distance[i]=cost[0][i];
Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark
visited[w] as 1.
7. Recalculate the shortest distance of remaining vertices from the source.
8. Only, the vertices not marked as 1 in array visited[ ] should be
considered for recalculation of distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v]
distance[w]+cost[w][v])
9. Stop
Program
/* Dijkstra’s Shortest Path */

#include <stdio.h>
#include <conio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX], int n, int startnode);
main()
{
int G[MAX][MAX], i, j, n, u;
printf("Enter no. of vertices: ");
scanf("%d", &n); printf("Enter the adjacency matrix:\n");
for(i=0; i<n; i++)
for(j=0; j<n; j++)
scanf("%d", &G[i][j]);
printf("Enter the starting node: ");
scanf("%d", &u);
dijkstra(G, n, u);
}
void dijkstra(int G[MAX][MAX], int n,int startnode)
{
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 to node%d = %d", i, distance[i]);
printf("\nPath = %d", i);j = i;
do
{
j = pred[j]; printf("<-%d", j);
} while(j != startnode);
}
}
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 0 60 0
Enter the starting node: 0
Distance to node1 = 10
Path = 1<-0
Distance to node2 = 50
Path = 2<-3<-0
Distance to node3 = 30
Path = 3<-0
Distance to node4= 60
Path = 4<-2<-3<-0

Result

Thus Dijkstra's algorithm is used to find shortest path from a given vertex.
Ex. No:10 Implementation of Prim’s Algorithm
Date:

Aim

To implement the Prim’s Algorithm in C program.

Algorithm

Step 1: Select a starting vertex

Step 2: Repeat Steps 3 and 4 until there are fringe vertices

Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum weight

Step 4: Add the selected edge and the vertex to the minimum spanning tree T

[END OF LOOP]

Step 5: EXIT

Program

#include<stdio.h>

#include<conio.h> int

a,b,u,v,n,i,j,ne=1;

int visited[10]={0},min,mincost=0,cost[10][10];

void main()

{
printf("\nEnter the number of nodes:");

scanf("%d",&n);

printf("\nEnter the adjacency matrix:\n");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);

if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;

printf("\n");

while(ne < n)

{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++) if(cost[i][j]<
min) if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min); mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;

}
printf("\n Minimun cost=%d",mincost);
getch();
}
Output

Result

Thus the C program for the implementation of Prim’s algorithm is executed successfully.
Ex. No. 11a Implementation of Searching-Linear Search
Date:

Aim
To perform linear search of an element on the given array.

Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai, i = 0,1,2,…n–1
4. Read search value
5. Assign 0 to found
6. Check each array element against search
If Ai = search then
found = 1
Print "Element
found" Print position
i
Stop
7. If found = 0 then
print "Element not found"
8. Stop
Program

/* Linear search on a sorted array */

#include
<stdio.h>
#include
<conio.h> main()
{
int a[50],i, n, val, found;
clrscr();
printf("Enter number of elements : ");
scanf("%d", &n); printf("Enter Array Elements : \n");
for(i=0; i<n;i++)
scanf("%d", &a[i]);
printf("Enter element to locate : ");
scanf("%d", &val);
found = 0;
for(i=0; i<n;
i++)
{
if (a[i] == val)
{
printf("Element found at position %d",i);

found = 1;
break;
}
}
if (found == 0)
printf("\n Element not found");
getch();
}
Output

Enter number of elements : 7


Enter Array Elements :
23 6 12 5 0 32 10
Enter element to locate :
5 Element found at
position 3

Result

Thus an array was linearly searched for an element's existence.


Ex. No. 11b Implementation of Searching-Binary Search
Date:

Aim
To locate an element in a sorted array using Binary search method

Algorithm

1. Start
2. Read number of array elements, say n
3. Create an array arr consisting n sorted elements
4. Get element, say key to be located
5. Assign 0 to lower and n to upper
6. While (lower < upper)
Determine middle element mid =
(upper+lower)/2 If key = arr[mid] then
Print
mid Stop
Else if key > arr[mid] then
lower = mid + 1
else
upper = mid – 1

7. Print "Element not found"


8. Stop
Program

/* Binary Search on a sorted array */

#include <stdio.h>
#include <conio.h>
main()
{
int a[50],i, n, upper, lower, mid, val, found; clrscr();

printf("Enter array size: ");


scanf("%d", &n);
for(i=0; i<n; i++)
a[i] = 2 * i;

printf("\n Elements in Sorted Order \n"); for(i=0; i<n; i++)


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

printf("\n Enter element to locate : ");


scanf("%d", &val);
upper =
n; lower
= 0;
found = -1;

while (lower <= upper)


{
mid = (upper +
lower)/2; if (a[mid] ==
val)
{
printf("Located at position %d", mid);
found = 1;
break;
}
else if(a[mid] >
val) upper =
mid - 1;
else
lower = mid + 1;
}

if (found == -1)
printf("Element not
found"); getch();
}
Out put

Enter array size 9


Elements in Sorted Order
0 2 4 6 8 10 12 14 16
Enter element to locate : 12 Located
at position 6
Enter array size 10
Elements in Sorted Order
0 2 4 6 8 10 12 14 16 18
Enter element to locate : 13
Element not found

Result

Thus an element is located quickly using binary search method.


Ex. No. 12a Implementation of Sorting- Insertion Sort
Date:

Aim
To sort an array of N numbers using Insertion sort.

Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Sort the elements using insertion sort
In pass p, move the element in position p left until its correct place is
foundamong the first p + 1 elements.
Element at position p is saved in temp, and all larger elements
(prior to position p) are moved one spot to the right. Then temp
is placed in the correct spot.
5. Stop

Program

/* Insertion Sort */

main()
{
int i, j, k, n, temp, a[20], p=0;

printf("Enter totalelements");
scanf("%d",&n);
printf("Enter array
elements:");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=1; i<n; i++)
{
temp=a[i];
j = i-1;
while((temp<a[j]) && (j>=0))
{
a[j+1] =a[j];
j = j - 1;
}
a[j+1] = temp;
p++;
printf("\n After Pass%d:",p);
for(k=0; k<n; k++)
printf("%d", a[k]);
}

printf("\n Sorted List :");


for(i=0; i<n; i++)
printf(" %d", a[i]);
}

Output

Enter total elements: 6


Enter array elements: 34 8 64 51 32 21
After Pass 1: 8 34 64 51 32 21
After Pass 2: 8 34 64 51 32 21
After Pass 3: 8 34 51 64 32 21
After Pass 4: 8 32 34 51 64 21
After Pass 5: 8 21 32 34 51 64
Sorted List : 8 21 32 34 51 64

Result

Thus array elements was sorted using insertion sort.


Ex. No. 12 b Implementation of Sorting- Selection Sort
Date:

Aim

To sort an array of N numbers using Selection sort.

Algorithm

Step 1 − Set min to the first location

Step 2 − Search the minimum element in the array

Step 3 – swap the first location with the minimum value in the array

Step 4 – assign the second element as min.

Step 5 − Repeat the process until we get a sorted array.


Program

#include <stdio.h>
void SelSort(int array[],int n);
int main()
{
int array[100], n,i;
printf("Enter number of elements");
scanf("%d", &n);
printf("Enter %d Numbers", n);
for(i = 0; i < n; i++) scanf("%d",
&array[i]); SelSort(array,n);
return 0;
}
void SelSort(int array[], int n)
{
int i, j, position, swap; for(i
= 0; i < (n - 1); i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(array[position]>array[j]) position=j;
}
if(position != i)
{
swap=array[i]; array[i]=array[position];
array[position]=swap;
}
}
printf("Sorted Array:");
for(i = 0; i < n; i++)
printf("%d ", array[i]);
}
Output

Result

Thus the C program for the selection sort has been performed successfully.
Ex. No. 13 Implementation of Sorting- Merge Sort
Date:

Aim

To sort an array of N numbers using Merge sort.

Algorithm

1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Divide the array into sub-arrays with a set of elements
5. Recursively sort the sub-arrays
6. Merge the sorted sub-arrays onto a single sorted array.
7. Stop
Program

/* Merge sort */

#include <stdio.h>
#include <conio.h>

void merge(int [],int ,int ,int );


void part(int [],int ,int );
int size;

main()
{
int i, arr[30];
printf("Enter total no. of elements : ");
scanf("%d", &size);
printf("Enter array elements : ");
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
part(arr, 0, size-1);
printf("\n Merge sorted list : ");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
}

void part(int arr[], int min, int max)


{
int i, mid;
if(min <
max)
{
mid = (min + max) / 2;
part(arr, min, mid);
part(arr, mid+1, max);
merge(arr, min, mid,
max);
}

if (max-min == (size/2)-1)
{
printf("\n Half sorted list : ");
for(i=min; i<=max; i++)

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


}
}

void merge(int arr[],int min,int mid,int max)


{
int tmp[30];
int i, j, k, m;
j= min;
m= mid + 1;

for(i=min; j<=mid && m<=max; i++)


{
if(arr[j] <= arr[m])
{
tmp[i] = arr[j];
j++;
}
else
{
tmp[i] = arr[m];
m++;
}
}
if(j > mid)
{
for(k=m; k<=max; k++)
{
tmp[i] = arr[k];
i++;
}
}
else
{
for(k=j; k<=mid; k++)
{
tmp[i] = arr[k];
i++;
}
}
for(k=min; k<=max; k++)
arr[k] = tmp[k];
}
Output

Enter total no. of elements : 8


Enter array elements : 24 13 26 1 2 27 38 15
Half sorted list : 1 13 24 26
Half sorted list : 2 15 27 38
Merge sorted list : 1 2 13 15 24 26 27 38

Result

Thus array elements was sorted using merge sort's divide and conquer method.
Ex. No. 14a Implementation of Hashing- Open addressing with linear probing
Date:

Aim
To implement hashing with linear probing.

Algorithm:

1. Create a structure, data (hash table item) with key and value as data.
2. Now create an array of structure, data of some certain size (10, in this case). But, the
size of array must be immediately updated to a prime number just greater than initial
array capacity (i.e 10, in this case).
3. A menu is displayed on the screen.
4. User must choose one option from four choices given in the menu
5. Perform all the operations
6. Stop

Program:

/* Open hashing */

#include
<stdio.h>
#include
<stdlib.h>
#define MAX 1
main()
{
int a[MAX], num, key, i;
char ans;
int create(int);
void linearprobing(int[], int, int);
void display(int[]);
printf("\nCollision handling by linear probing\n\n");
for(i=0; i<MAX; i++)
a[i] = -1;
do
{
printf("\n Enter
number:"); scanf("%d",
&num);
key = create(num);
linearprobing(a, key, num);
printf("\nwish to
continue?(y/n):"); ans = getch();
} while( ans == 'y');
display(a);
}
int create(int num)
{
int key;
key = num %10;
return key;
}

Void linearprobing(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("hash 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;
}
}
}
void display(int a[MAX])
{
int i;
printf("\n Hash table is:");
for(i=0; i<MAX; i++)
printf("\n %d\t\t%d",i,a[i]);
}

Output:

Collision handling by linear probing


Enter number:1
wish to continue?(y/n):
Enter number:26
wish to continue?(y/n):
Enter number:62
wish to continue?(y/n):
Enter number:93
wish to continue?(y/n):
Enter number:84
wish to continue?(y/n):
Enter number:15
wish to continue?(y/n):
Enter number:76
wish to continue?(y/n):
Enter number:98
wish to continue?(y/n):
Enter number:26
wish to continue?(y/n):
Enter number:199
wish to continue?(y/n):
Enter number:1234
wish to continue?(y/n):
Enter number:5678
hash table is full
Hash table is:
0 1234
1 1
2 62
3 93
4 84
5 15
6 26
7 76
8 98
9 199

Result

Thus the C program for the hashing has been performed successfully.
Ex.No:14b IMPLEMENTATION OF OPEN ADDRESSING WITH
Date: QUADRATIC PROBING

AIM:

To write a C program to implement open addressing with quadratic probing.

ALGORITHM:
Hashtable is an array of size = tsize

Step 1:c o m p u t e t h e h a s h k e y u s i n g m o d
f u n c t i o n Step 2:let i = 0
Step 3:k e y = n u m % t s i z e .
Step 4: compute the index at which the value has to be inserted in hash table
index = (key+ i * i) % tsize
Step 5: if there is no element at that index then insert the value at index and STOP

Step 6: If there is already an element at that index


step 4.1: i = i+1
step 7: if i < tsize then go to step 4

PROGRAM:
#include<stdio.h>
#include<conio.h>

Void display(int a[],int n)


{
//Displaying complete hash table
for(int i =0;i<n;i++)
{
printf(“\n%d %d”,I,a[i]);
}
void Quadratic_prob(int table[],int tsize,int num)
{
int key =num %tsize;
if(table[key]==-1)
table[key]=num;
else
{
for(int i=0;i<tsize;i++)
{
int index = (key+ i*i)%tsize;
if(table[index]==-1)
{
table[index]=num;
break;
}
}
}
display(table,tsize);
}

int main()
{
int Size =10;
int num;
int hash_table[size];
char ans;
for(int i=0;i<size;i++)
{
hash_table[i]=-1;
}
do
{
Printf(“\n enter the number:”);
Scanf(“%d”,&num);
Quadratic_prob(hash_table,size,num);
Printf(“\n Do u wish to continue?(Y/n)”);
ans=getch();
}while(ans==’y’);
return 0;
}
OUTPUT

Enter the number:37

0 -1
1 -1
2 -1
3 -1
4 -1
5 -1
6 -1
7 37
8 -1
9 -1

Do u wish to continue?(y/n)

Enter the number:90

0 90
1 -1
2 -1
3 -1
4 -1
5 -1
6 -1
7 -1
8 -1
9 -1

Do u wish to continue?(y/n)

RESULT:

Thus, quadratic probing was implemented successfully.

You might also like