0% found this document useful (0 votes)
12 views72 pages

CS3311 Data Structures Record R2021 - 240814 - 111421

The document is a laboratory record for a Data Structures course at C.S.I Institute of Technology, detailing various experiments and implementations in C, including stacks, queues, linked lists, and sorting algorithms. Each experiment includes an aim, algorithm, program code, output, and results, demonstrating the practical application of data structures. The record is structured to facilitate practical examinations and includes sections for student information and certification by faculty members.

Uploaded by

thanasanthosh764
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)
12 views72 pages

CS3311 Data Structures Record R2021 - 240814 - 111421

The document is a laboratory record for a Data Structures course at C.S.I Institute of Technology, detailing various experiments and implementations in C, including stacks, queues, linked lists, and sorting algorithms. Each experiment includes an aim, algorithm, program code, output, and results, demonstrating the practical application of data structures. The record is structured to facilitate practical examinations and includes sections for student information and certification by faculty members.

Uploaded by

thanasanthosh764
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/ 72

1

C.S.I INSTITUTE OF TECHNOLOGY


THOVALAI-629302

Affiliated to ANNA UNIVERSITY

CS 3311

DATA STRUCTURES LABORATORY

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

DATA STRUCTURES LAB

NAME :

REGISTER NUMBER :

SEMESTER :

DEPARTMENT :
2

C.S.I INSTITUTE OF TECHNOLOGY

THOVALAI-629302
Affiliated to ANNA UNIVERSITY

DATA STRUCTURES LAB RECORD

University Register No

Name……………………………............. Class No……………………………..

Branch of study…………………............ Semester/Year……………………….

Subject Name........................................... Subject Code.......................................

Certified that this is the Bonafide Record of work done by


……………...….....………………………. in the COMPUTER LABORATORY of the
C.S.I INSTITUTE OF TECHNOLOGY, THOVALAI during the year
…………………...

Staff Member in Charge Head of Department

Certified that this Record has been submitted for the Practical Examination held
on .………….

Internal Examiner External Examiner


3

S.No Date List of Experiments Page No Mark Staff


Sign
1a. Array Implementation of Stack

1b. Array Implementation of Queue

1c. Array Implementation of Circular Queue

2 Implementation of Singly Linked List

3a Implementation of Stack Using Linked


List
3b. Implementation of Queue Using Linked
List
4 Implementation of polynomial
Manipulation using Linked List

5a. Implementation of Infix to postfix

5b. Evaluation of postfix Expression

6. Implementation of Binary Search Trees

7. Implementation of AVL Trees

8 Implementation of Heaps using Priority


Queue
9 Implementation of Dijikstras Algorithm

10. Application of Graph-Prims Algorithm

11a. Implementation of Linear Search


Algorithm
11b. Implementation of Binary Search
Algorithm
12a Implementation of Insertion Sort
Algorithm
12b. Implementation of Selection sort
Algorithm
13. Implementation of Merge sort Algorithm

14. Implementation of Hashing using open


addressing with Linear Probing
4

Ex.no:1a ARRAY IMPLEMENTATION OF STACK


AIM:
To implement stack using array in C.

ALGORITHM:

Step 1: Include all the header files and give the maximum size.

Step 2: Define a integer variable 'top' and initialize with '-1'. (int top = -1).

Step 3: Create a one dimensional array ‘a’ with max size.

Step 4:Display the menu with list of operations and perform the operation selected by the
user on the stack.

Step 5:Operations:

push - to insert an element into the stack.

pop - to delete an element from the stack

display – to display the elements of a stack.

Exit – to exit from the program

PROGRAM:
#include<stdio.h>
void main()
{
int a[10]={0},i,top=-1,max=10,n,x;
printf("\n\tMENU\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n");
do
{
printf("\nEnter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
if(top==max-1)
printf("Stack is FULL\n");
5

else
{
printf("Enter the element\n");

scanf("%d",&x);
a[++top]=x;
}
break;
case 2:
if(top<0)
printf("Stack is Empty\n");
else
printf("The deleted item =%d",a[top--]); break;
case 3:
if(top<0)
printf("The stack is empty\n");
else
{
printf("The elements of the stack are :");
for(i=0;i<=top;i++)
printf("%d\n",a[i]);
}
break;
case 4:
break;
default:
printf("Invalid choice\n");
break;
}
}
while(n!=4);
}
6

OUTPUT:
MENU
1.PUSH
2.POP
3.DISPLAY
4.EXIT
Enter your choice

1
Enter the element
2
Enter your choice
1
Enter the element
3
Enter your choice
2
The deleted item =3
Enter your choice
3
The elements of the stack are :2
Enter your choice
4

RESULT:
Thus, the program to implement stack using array in C was executed successfully.
7

Ex.no:1b ARRAY IMPLEMENTATION OF QUEUE

AIM:
To implement Queue using array in C.

ALGORITHM:

Step 1: Include all the header files and define the maximum size.

Step 2: Create a one dimensional array ‘queue_array’ with max size.

Step 3: Define the integer variables'rear'and ‘front’ and initialize them with '-1'.

Step 4:Display the menu with list of operations and perform the operation selected by the
user on the Queue.

Step 5: Operations:

enQueue- to insert an element into the Queue.

deQueue- to delete an element from the Queue

display – to display the elements of a Queue.

exit – to exit from the program

PROGRAM:
#include <stdio.h>
#define MAX 50
int queue_array[MAX];
int rear = - 1;
int front = - 1;
void 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();
8

break;
case 2:
delete();
break;
case 3:
display();
break;
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("Insert the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /*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;
}
} /*End of delete() */
display()
{
int i;
if (front == - 1|| front > rear)
printf("Queue is empty \n");
else
9

{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}

OUTPUT:
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 29
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 16
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 4
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 3
Queue is :
29 16 4
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
10

4.Quit
Enter your choice : 2
Element deleted from queue is : 29
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit

Enter your choice : 3


Queue is :
16 4
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 4

RESULT:
Thus, the program to implement Queue using array in C was executed successfully.
11

Ex.No:1c Array Implementation of Circular Queue

AIM:
To implement circular Queue using array in C.

ALGORITHM:
Data Structure: CQ is the array representation of circular queue structure; two pointers
FRONT and REAR of the queue CQ are known.
1. Start
2. Initialize the array of 10 elements name d as cqueue and variables CQ[10], FRONT=-1,
REAR=-1
3. Provide the choice to the users using switch for the different operations on circular
queue like Insert, Delete, Display and Exit Function insert()
4. Check for the overflow condition of the Queue IF (FRONT=(REAR+1)%N) THEN
Print “Queue is full”
5. If not overflow , increment the value of rear REAR = (REAR+1) % N
6. Get the element to be inserted into the queue from the user CQ[REAR] = ITEM
7. Assign it as the last value , CQ[REAR] Function delete()
8. Check for the underflow (empty) condition of the queue
9. If not empty ,Output the element to be deleted from the queue
10.Increment the value of front. FRONT = (FRONT+1) % N Function display()
11. Display the elements of the queue

PROGRAM:
#include <stdio.h>
#define size 5

void insertq(int[], int);


void deleteq(int[]);
void display(int[]);

int front = - 1;
int rear = - 1;

int main()
{
int n, ch;
int queue[size];
12

do
{

printf("\n\n Circular Queue:\n1. Insert \n2. Delete\n3. Display\n0. Exit");


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

void insertq(int queue[], int item)


{
if ((front == 0 && rear == size - 1) || (front == rear + 1))
{
printf("queue is full");
return;
}
else if (rear == - 1)
{
rear++;
front++;
}
else if (rear == size - 1 && front > 0)
{
rear = 0;
}
else
{
rear++;
13

}
queue[rear] = item;
}

void display(int queue[])

{
int i;
printf("\n");
if (front > rear)
{
for (i = front; i < size; i++)
{
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]);
}
}

void deleteq(int queue[])


{
if (front == - 1)
{
printf("Queue is empty ");
}
else if (front == rear)
{
printf("\n %d deleted", queue[front]);
front = - 1;
rear = - 1;
}
else
{
printf("\n %d deleted", queue[front]);
front++;
}
}
14

OUTPUT:
Circular Queue:
1. Insert
2. Delete
3. Display
0. Exit
Enter Choice 0-3? : 1
Enter number: 2

Circular Queue:
1. Insert
2. Delete
3. Display
0. Exit
Enter Choice 0-3? : 1
Enter number: 5
Circular Queue:
1. Insert
2. Delete
3. Display
0. Exit
Enter Choice 0-3? : 3
25
Circular Queue:
1. Insert
2. Delete
3. Display
0. Exit
Enter Choice 0-3? : 2
2 deleted
Circular Queue:
1. Insert
2. Delete
3. Display
0. Exit
Enter Choice 0-3? : 3
5

RESULT:
Thus, the program to implement circular Queue using array in C was executed
successfully.
15

Ex.No:2 Implementation of Singly Linked List

AIM:
To implement Singly Linked List in C.

ALGORITHM:

Step 1: Include all the header files.

Step 2:Create a structure LIST with no and *next.

Step 3:Declare all the functions with which operations are done on the linked list.

Step 4:Display the menu with list of operations and perform the operation selected by the
user on the linked List.

Step 5:Operations:

create – to create the linked list

insert- to insert an element into the linked list in the chosen position.

deletion - to delete an element from the chosen position in the linked list

display – to display the elements of the linked List.

exit – to exit from the program

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<process.h>
#define NULL 0

typedefstruct list
{
int no;
struct list *next;
}LIST;
LIST *p,*t,*h,*y,*ptr,*pt;

void create( void );


void insert( void );
void delet( void );
void display ( void );

intj,pos,k=1,count;
16

void main()
{
int n,i=1,opt;
clrscr();
p = NULL;
printf("%d",sizeof(LIST));
printf( "Enter the no of nodes :\n " );
scanf( "%d",&n );
count = n;
while( i <= n)
{
create();
i++;
}
printf("\nEnter your option:\n");
printf("1.Insert \t 2.Delete \t 3.Display \t 4.Exit\n");
do
{
scanf("%d",&opt);
switch( opt )
{
case 1:
insert();
count++;
break;
case 2:
delet();
count--;
if ( count == 0 )
{
printf("\n List is empty\n");
}
break;
case 3:
printf("List elements are:\n");
display();
break;
case 4:
exit(0);
break;
}
printf("\nEnter your option \n");
}while( opt != 4 );
getch();
}
void create ( )
{
if( p== NULL )
{
17

p = ( LIST * ) malloc ( sizeof ( LIST ) );


printf( "Enter the element:\n" );
scanf( "%d",&p->no );
p->next = NULL;

h = p;
}
else
{
t= ( LIST * ) malloc (sizeof( LIST ));
printf( "\nEnter the element" );
scanf( "%d",&t->no );
t->next = NULL;
p->next = t;
p = t;
}
display();
}
void insert()
{
t=h;
p = ( LIST * ) malloc ( sizeof(LIST) );
printf("Enter the element to be inserted:\n");
scanf("%d",&p->no);
printf("Enter the position to insert:\n");
scanf( "%d",&pos );
if( pos == 1 )
{
h = p;
h->next = t;
}
else
{
for(j=1;j<(pos-1);j++)
t = t->next;
p->next = t->next;
t->next = p;
t=p;
}
display();
}

void delet()
{
printf("Enter the position to delete:\n");
scanf( "%d",&pos );
if( pos == 1 )
{
h = h->next ;
18

}
else
{
t= h;
for(j=1;j<(pos-1);j++)
t = t->next;
pt=t->next->next;
free(t->next);

t->next= pt;
}
display();
}
void display()
{
t= h;
while( t->next != NULL )
{
printf("\t%d",t->no);
t = t->next;
}
printf( "\t %d\t",t->no );
}

OUTPUT:
4Enter the no of nodes :
3
Enter the element:
4
4
Enter the element5
4 5
Enter the element6
4 5 6
Enter your option:
1.Insert 2.Delete 3.Display 4.Exit
1
Enter the element to be inserted:
7
Enter the position to insert:
3
19

4 5 7 6
Enter your option
3
List elements are:
4 5 7 6
Enter your option
2
Enter the position to delete:

2
4 7 6
Enter your option
4

RESULT:
Thus, the program to implement List ADT using Linked list in C was executed
successfully.
20

Ex.No:3a Implementation of Stack Using Linked List

AIM:
To implement stack using Linked List in C.

ALGORITHM:

Step 1: Include all the header files.

Step 2:Create a structure node with data and *link.

Step 3:Declare all the functions with which operations are done on the linked list
implementation of stack.

Step 4:Display the menu with list of operations and perform the operation selected by the
user on the linked List implementation of stack.

Step 5:Operations:

Push - to insert an element into the stack.

Pop - to delete an element from the stack.

display – to display the elements of the stack.

exit – to exit from the program

PROGRAM:
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
void pop();
void push(int value);
void display();

struct node
{
int data;
struct node *link;
};
struct node *top=NULL,*temp;

void main()
{
int choice,data;

while(1)
{
21

printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
printf("\nEnterur choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: //To push a new element into stack

printf("Enter a new element :");


scanf("%d",&data);
push(data);
break;

case 2: // pop the element from stack


pop();
break;

case 3: // Display the stack elements


display();
break;
case 4: // To exit
exit(0);
}

}
}
void display()
{
temp=top;
if(temp==NULL)
{
printf("\nStack is empty\n");
}
printf("\n The Contents of the Stack are...");
while(temp!=NULL)
{
printf(" %d ->",temp->data);
temp=temp->link;
}
}
void push(int data)
{
temp=(struct node *)malloc(sizeof(struct node)); // creating a space for the new
element.
temp->data=data;
temp->link=top;
top=temp;
display();
22

void pop()
{
if(top!=NULL)

{
printf("The poped element is %d",top->data);
top=top->link;
}
else
{
printf("\nStack Underflow");
}
display();
}

OUTPUT:
1.Push

2.Pop

3.Display

4.Exit

Enter ur choice:1

Enter a new element :2

The Contents of the Stack are... 2 ->

1.Push

2.Pop

3.Display

4.Exit

Enter ur choice:1

Enter a new element :5

The Contents of the Stack are... 5 -> 2 ->

1.Push

2.Pop
23

3.Display

4.Exit
Enter ur choice:1
Enter a new element :9
The Contents of the Stack are... 9 -> 5 -> 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:3
The Contents of the Stack are... 9 -> 5 -> 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:2
The poped element is 9
The Contents of the Stack are... 5 -> 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:2
The poped element is 5
The Contents of the Stack are... 2 ->
1.Push
2.Pop
3.Display
4.Exit

Enter ur choice:4

RESULT:
Thus, the program to implement stack ADT using Linked list in C was executed
successfully.
24

Ex.No:3b Implementation of Queue Using Linked List

AIM:
To implement queue using Linked List in C.

ALGORITHM:

Step 1: Include all the header files.

Step 2:Create a structure node with info and *ptr.

Step 3:Declare all the functions with which operations are done on the linked list
implementation of Queue.

Step 4:Display the menu with list of operations and perform the operation selected by the
user on the linked List implementation of Queue.

Step 5:Operations:

enq- to insert an element into the Queue.

deq - to delete an element from the Queue.

display – to display the elements of theQueue.

empty – to check whether the queue is empty

queuesize–to display the size of the Queue

frontelement - to display the element at the front position of the Queue

exit – to exit from the program

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;
intfrontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();
25

int count = 0;
void main()
{
int no, ch, e;
clrscr();
printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Queue size");
printf("\n 6 - Display");
printf("\n 7 - Exit");
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:
queuesize();
break;
case 6:
display();
break;
case 7:
exit(0);
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
26

}
}
/* Create an empty queue */
void create()
{
front = rear = NULL;

}
void queuesize()
{
printf("\n Queue size : %d", count);
}
/* Enqueing the queue */
void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;
rear = temp;
}
count++;
}
/* Displaying the queue elements */
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);
}
27

void deq()
{
front1 = front;
if (front1 == NULL)
{
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--;
}
/* Returns the front element of queue */
intfrontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}
/* Display if queue is empty or not */
void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}

OUTPUT:
1 - Enque

2 – Deque
28

3 - Front element
4 - Empty
5 - Queue size
6 - Display
7 - Exit
Enter choice : 1
Enter data : 4
Enter choice : 1
Enter data : 5
Enter choice : 1
Enter data : 6
Enter choice : 1
Enter data : 7
Enter choice : 2
Dequed value : 4
Enter choice : 6
567
Enter choice : 3
Front element : 5
Enter choice : 4
Queue not empty
Enter choice : 5
Queue size : 3
Enter choice : 6
567
Enter choice : 7

RESULT:
Thus, the program to implement Queue ADT using Linked list in C was executed
successfully.
29

Ex.No:4 Implementation of Polynomial Manipulation Using Linked List

AIM:
To implement polynomial addition using Linked List in C.

ALGORITHM:

1.Create a new linked list, newHead to store the resultant list.

2.Traverse both lists until one of them is null.

3.If any list is null insert the remaining node of another list in the resultant list.

4.Otherwise compare the degree of both nodes, a and b

Here three cases are possible:


1) If the degree of a and b is equal, we insert a new node in the resultant list with the
coefficient equal to the sum of coefficients of a and b and the same degree.
2) If the degree of a is greater than b, we insert a new node in the resultant list with the
coefficient and degree equal to that of a.
3) If the degree of b is greater than a, we insert a new node in the resultant list with the
coefficient and degree equal to that of b.

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
typedef struct link
{
int coeff;
int pow;
struct link * next;
} my_poly;
void my_create_poly(my_poly **);
void my_show_poly(my_poly *);
void my_add_poly(my_poly **, my_poly *, my_poly *);
int main(void)
{
int ch;
do
{
my_poly * poly1, * poly2, * poly3;
printf("\nCreate 1st expression\n");
my_create_poly(&poly1);
printf("\nStored the 1st expression");
my_show_poly(poly1);

printf("\nCreate 2nd expression\n");


my_create_poly(&poly2);
30

printf("\nStored the 2nd expression");


my_show_poly(poly2);

my_add_poly(&poly3, poly1, poly2);


my_show_poly(poly3);

printf("\nAdd two more expressions? (Y = 1/N = 0): ");


scanf("%d", &ch);
} while (ch);
return 0;
}
void my_create_poly(my_poly ** node)
{
int flag;
int coeff, pow;
my_poly * tmp_node;
tmp_node = (my_poly *) malloc(sizeof(my_poly));
*node = tmp_node;
do
{
//Get the user data
printf("\nEnter Coeff:");
scanf("%d", &coeff);
tmp_node->coeff = coeff;
printf("\nEnter Pow:");
scanf("%d", &pow);
tmp_node->pow = pow;
tmp_node->next = NULL;
printf("\nContinue adding more terms to the polynomial list?(Y = 1/N = 0): ");
scanf("%d", &flag);
if(flag)
{
tmp_node->next = (my_poly *) malloc(sizeof(my_poly));
tmp_node = tmp_node->next;
tmp_node->next = NULL;
}
}
while (flag);
}
void my_show_poly(my_poly * node)
{
printf("\nThe polynomial expression is:\n");
while(node != NULL)
{
printf("%dx^%d", node->coeff, node->pow);
node = node->next;
if(node != NULL)
printf(" + ");
}
31

}
void my_add_poly(my_poly ** result, my_poly * poly1, my_poly * poly2)
{
my_poly * tmp_node;

tmp_node = (my_poly *) malloc(sizeof(my_poly));


tmp_node->next = NULL;
*result = tmp_node;

while(poly1 && poly2)


{
if (poly1->pow > poly2->pow)
{
tmp_node->pow = poly1->pow;
tmp_node->coeff = poly1->coeff;
poly1 = poly1->next;
}
else if (poly1->pow < poly2->pow)
{
tmp_node->pow = poly2->pow;
tmp_node->coeff = poly2->coeff;
poly2 = poly2->next;
}
else
{
tmp_node->pow = poly1->pow;
tmp_node->coeff = poly1->coeff + poly2->coeff;
poly1 = poly1->next;
poly2 = poly2->next;
}
if(poly1 && poly2)
{
tmp_node->next = (my_poly *) malloc(sizeof(my_poly));
tmp_node = tmp_node->next;
tmp_node->next = NULL;

}
while(poly1 || poly2)
{

tmp_node->next = (my_poly *) malloc(sizeof(my_poly));


tmp_node = tmp_node->next;
tmp_node->next = NULL;
if(poly1)
{
tmp_node->pow = poly1->pow;
tmp_node->coeff = poly1->coeff;
poly1 = poly1->next;
}
32

if(poly2)
{
tmp_node->pow = poly2->pow;
tmp_node->coeff = poly2->coeff;
poly2 = poly2->next;
}
}
printf("\nAddition Complete");

OUTPUT:
Create 1st expression

Enter Coeff:2
Enter Pow:3
Continue adding more terms to the polynomial list?(Y = 1/N = 0): 1
Enter Coeff:4
Enter Pow:2
Continue adding more terms to the polynomial list?(Y = 1/N = 0): 0
Stored the 1st expression
The polynomial expression is:
2x^3 + 4x^2
Create 2nd expression

Enter Coeff:4
Enter Pow:3
Continue adding more terms to the polynomial list?(Y = 1/N = 0): 1
Enter Coeff:2
Enter Pow:1
Continue adding more terms to the polynomial list?(Y = 1/N = 0): 0
Stored the 2nd expression
The polynomial expression is:
4x^3 + 2x^1
Addition Complete
The polynomial expression is:
6x^3 + 0x^0 + 2x^1
Add two more expressions? (Y = 1/N = 0):
RESULT:
Thus, the program to implement adding two polynomials using Linked list in C was
executed successfully.
33

Ex.No:5a IMPLEMENTATION OF INFIX TO POSTFIX


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

ALGORITHM
1. Start the program
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expression character-by-character
5. If character is an operand print it
6. If character is an operator
7. Compare the operator’s priority with the stack[top] operator.
8. If the stack [top] operator has higher or equal priority than the input operator,
9. Pop it from the stack and print it.
Else
10. Push the input operator onto the stack
11. If character is a left parenthesis, then push it onto the stack.
12. If the character is a right parenthesis, pop all the operators from the stack and
print it.until a left parenthesis is encountered. Do not print the parenthesis.
PROGRAM:

#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;
34

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

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

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

Ex. No. 5b EVALUATION OF POSTFIX EXPRESSION

AIM
To evaluate the given postfix expression using stack operations.

ALGORITHM
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the postfix expression character-by-character
If character is an operand push it onto the
stack If character is an operator
Pop topmost two elements from stack.
Apply operator on the elements and push the result onto the
stack,
5. Eventually only result will be in the stack at end of the expression.
6. Pop the result and print it.
7. Stop

PROGRAM:

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

struct stack
{
int top; float
a[50];
}s;
38

main()
{
char pf[50]; float
d1,d2,d3; int i;
clrscr();

s.top = -1;
printf("\n\n Enter the postfix expression: "); gets(pf);
for(i=0; pf[i]!='\0'; i++)
{
switch(pf[i])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
s.a[++s.top] =pf[i]-'0'; break;

case '+':
d1 = s.a[s.top--];
d2 = s.a[s.top--]; s.a[++s.top]
= d1 +d2; break;

case '-':
d2 =s.a[s.top--];
d1 =s.a[s.top--];
s.a[++s.top] = d1 -d2;
break;

case '*':
d2 = s.a[s.top--];
d1 = s.a[s.top--];
s.a[++s.top] =d1*d2; break;

case '/':
d2 = s.a[s.top--];
d1 = s.a[s.top--]; s.a[++s.top]
= d1 /d2; break;
}
}
39

printf("\n Expression value is %5.2f", s.a[s.top]); getch();


}

OUTPUT:

Enter the postfix expression: 6523+8*+3+*


Expression value is 288.00

RESULT:

Thus the given postfix expression was evaluated using stack


40

Ex. No. 6
IMPLEMENTATAION OF BINARY SEARCH TREE

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.

4.Stop.
41

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

struct node* deleteNode(struct node* root, intkey)


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

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

root = deleteNode(root, 50);


printf("Inorder traversal of the modified tree \n"); inorder(root);
}
OUTPUT:

RESULT:
Thus, the program to implement the operations in Binary Search Tree in C was executed
successfully.
44

Ex.No:7 IMPLEMENTATION OF AVL TREES

AIM:
To implement the operations in AVL Tree using C.

ALGORITHM:
Step 1:Create the AVL tree.

Step 2:Declare all the functions with which operations are done on the AVLtree.

Step 3:Display the menu with list of operations and perform the operation selected by the user on
theAVL tree.

Step 4:Operations

Insert – to insert an element into the AVL tree.

Delete - to delete an element from the AVL tree.

Print – to display the elements of the AVL tree.

exit – to exit from the program

PROGRAM:
#include<stdio.h>
typedefstruct node
{
int data;
struct node *left,*right;
intht;
}node;

node *insert(node *,int);


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

int main()
{
node *root=NULL;
45

intx,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)
{
46

T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;
}
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)
{
47

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
{
//data to be deleted is found
if(T->right!=NULL)
{ //delete its inordersuccesor
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)


{
intlh,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);
48

return(rh);
}

node * rotateright(node *x)


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

return(y);
}

node * RR(node *T)


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

node * LL(node *T)


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

node * LR(node *T)


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

return(T);
}
node * RL(node *T)
{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}
49

int BF(node *T)


{
intlh,rh;
if(T==NULL)
return(0);

if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;

return(lh-rh);
}

void preorder(node *T)


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

OUTPUT

1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:1
Enter no. of elements:4

Enter tree data:7 12 4 9


50

1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:4
Preorder sequence:
7(Bf=-1)4(Bf=0)12(Bf=1)9(Bf=0)
Inorder sequence:
4(Bf=0)7(Bf=-1)9(Bf=0)12(Bf=1)

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

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, the program to implement the operations in AVL Tree in C was executed
successfully.
51

Ex.no:8 IMPLEMENTATION OF HEAPS USING PRIORITY QUEUE

AIM:
To implement the Heap using Priority Queue in C.

ALGORITHM:
Step 1:Create the heap using Priority Queue.

Step 2:Declare all the functions with which operations are done on the Priority Queue.

Step 3:Display the menu with list of operations and perform the operation selected by the user on
thePriority Queue.

Step 4:Operations

Insert – to insert an element into the Priority Queue.

Delete - to delete an element from the Priority Queue.

Display – to display the elements of the Priority Queue.

exit – to exit from the program

PROGRAM:
#include<stdio.h>
#include<malloc.h>
void insert();
voiddel();
void display();

struct node
{
int priority;
int info;
struct node *next;
}*start=NULL,*q,*temp,*new;

typedefstruct node N;
void main()
{
intch;
clrscr();
do
{
printf("\n[1] INSERTION\t[2] DELETION\t[3] DISPLAY [4] EXIT\t:");
scanf("%d",&ch);
switch(ch)
{
52

case1:insert();
break;
case2:del();
break;
case3:display();
break;
case4:
break;
}
}
while(ch<4);
}

void insert()
{
intitem,itprio;
new=(N*)malloc(sizeof(N));
printf("ENTER THE ELT.TO BE INSERTED :\t");
scanf("%d",&item);
printf("ENTER ITS PRIORITY :\t");
scanf("%d",&itprio);
new->info=item;
new->priority=itprio;
new->next=NULL;
if(start==NULL )
{
//new->next=start;
start=new;
}
elseif(start!=NULL&&itprio<=start->priority)
{new->next=start;
start=new;
}
else
{
q=start;
while(q->next!= NULL && q->next->priority<=itprio)
{q=q->next;}
new->next=q->next;
q->next=new;
}
}

Void del()
{
if(start==NULL)
{
printf("\nQUEUE UNDERFLOW\n");

}
else
53

{
new=start;
printf("\nDELETED ITEM IS %d\n",new->info);
start=start->next;
//free(start);
}
}

void display()
{
temp=start;
if(start==NULL)
printf("QUEUE IS EMPTY\n");
else
{
printf("QUEUE IS:\n");
if(temp!=NULL)
for(temp=start;temp!=NULL;temp=temp->next)
{
printf("\n%d priority =%d\n",temp->info,temp->priority);
//temp=temp->next;
}
}
}
OUTPUT:
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :1
ENTER THE ELT.TO BE INSERTED : 2
ENTER ITS PRIORITY : 1
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :1
ENTER THE ELT.TO BE INSERTED : 3
ENTER ITS PRIORITY : 2
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :3
QUEUE IS:
2 priority =1
3 priority =2

[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :2

DELETED ITEM IS 2

[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :3


QUEUE IS:

3 priority =2

[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :4

RESULT:
Thus, the program to implement the Heap using Priority Queue in C was executed
successfully.
54

Ex.no:9 IMPLEMENTATION OF DIJIKSTRAS ALGORITHM

AIM:
To implement the Dijikstras Algorithm to find the shortest path in C.

ALGORITHM:
1. Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. 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.

2. Array visited[ ] is initialized to zero.


for(i=0;i<n;i++)
visited[i]=0;

3. If the vertex 0 is the source vertex then visited[0] is marked as 1.

4. Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1 from the
source vertex 0.
for(i=1;i<n;i++)
distance[i]=cost[0][i];
Initially, distance of source vertex is taken as 0. i.e. distance[0]=0;

5. for(i=1;i<n;i++)
Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark visited[w] as 1.
Recalculate the shortest distance of remaining vertices from the source.
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])

PROGRAM:
#include<stdio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX],int n,int startnode);
int main()
{

int G[MAX][MAX],i,j,n,u;

printf("Enter no. of vertices:");

scanf("%d",&n);

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

for(i=0;i<n;i++)
55

for(j=0;j<n;j++)

scanf("%d",&G[i][j]);

printf("\nEnter the starting node:");

scanf("%d",&u);

dijkstra(G,n,u);

return 0;

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

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

//initialize pred[],distance[] and visited[]

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

distance[i]=cost[startnode][i];

pred[i]=startnode;

visited[i]=0;

}
56

distance[startnode]=0;

visited[startnode]=1;

count=1;

while(count<n-1)

mindistance=INFINITY;

//nextnode gives the node at minimum distance

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)

{
57

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

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
Enter the starting node:0
Distance of node1=10
Path=1<-0
Distance of node2=50
Path=2<-3<-0
Distance of node3=30
Path=3<-0
Distance of node4=60
Path=4<-2<-3<-0
RESULT:

Thus the Shortest path using Dijikstra Algorithm was found successfully.
58

Ex.No: 10 APPLICATION OF GRAPH- PRIM’S ALGORITHM

AIM: To write a C program to find minimum spanning tree using Prim’s Algorithm.

ALGORITHM:

Get the number of vertices in the graph and the adjacency matrix.
Choose the edge with minimum distance.
Add it to the minimum spanning tree.
Check the other nodes in the graph which are adjacent to any one of the node in the
minimum spanning tree.
 Include the edge which has the minimum cost in the minimum spanning tree it does not
make cycle.
 Repeat steps 4 & 5 until all the nodes included in the minimum spanning tree.
PROGRAM:

#include<stdio.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++)
59

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

}
OUTPUT:
Enter the number of nodes:6
Enter the adjacency matrix:
0 3 1 6 00
3 0 5 0 3 0
1 5 0 5 6 4
6 0 5 0 0 2
0 3 6 0 0 6
0 0 4 2 6 0
Edge 1:(1 3) cost:1
Edge 2:(1 2) cost:3
Edge 3:(2 5) cost:3
Edge 4:(3 6) cost:4
Edge 5:(6 4) cost:2
Minimun cost=13

RESULT:

Thus the minimum spanning tree was found using Prim’s Algorithm.
60

Ex.no:11a. IMPLEMENTATION OF LINEAR SEARCH ALGORITHM


AIM:
To implement the Linear Search algorithm using C.

ALGORITHM:

Step 1: Read the search element from the user

Step 2: Compare, the search element with the first element in the list.

Step 3: If both are matching, then display "Given element found!!!" and terminate the
function

Step 4: If both are not matching, then compare search element with the next element in the
list.

Step 5: Repeat steps 3 and 4 until the search element is compared with the last element in
the list.

Step 6: If the last element in the list is also doesn't match, then display "Element not
found!!!" and terminate the function.

PROGRAM:
#include<stdio.h>
void main()
{
int a[10],i,n,c;
printf("Enter the n value:");
scanf("%d",&n);
printf("enter the elements of an array:");
for(i=0;i<=n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter the value to search");
scanf("%d",&c);
for(i=0;i<=n;i++)
{
if(c==a[i])
{
printf("\n Element found"); break;
}

}
if(c!=a[i])
printf("\n Element not found");
getch();
}
61

OUTPUT:

Enter the n value:4


enter the elements of an array:1
2
3
4
5
Enter the value to search3
Element found

Enter the n value:2


enter the elements of an array:1
2
3
Enter the value to search6
Element not found

RESULT:
Thus, the program toimplement the Linear Search algorithmin C was executed
successfully.
62

Ex.no:11b. IMPLEMENTATION OF BINARY SEARCH ALGORITHM

AIM
To write a C program to implement the concept of binary search.
ALGORITHM
Step 1: Set the list to be the whole list
Step 2: Find the middle value of the list
Step 3: If the middle value is equal to the target then we declare victory and stop.
Step 4: If the middle item is less than the target, then we set the new list to be the upper half of the
old list and we repeat from step 2 using the new list.
Step 5: If the middle value is greater than the target, then we set the new list to be the bottom half
of the list, and we repeat from step 2 with the new list.
Step 6: Stop
PROGRAM
#include<stdio.h>

void main()
{
int n,i,search,f=0,low,high,mid,a[20];
printf("Enter the n value:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the number in ascending order a[%d]=",i);
scanf("%d",&a[i]);
}
printf("Enter the search element:");
scanf("%d",&search);
low=1;
high=n;
while(low<=high)
{
mid=(low+high)/2;
if(search<a[mid])
{
high=mid-1;
}
elseif(search>a[mid])
{
low=mid+1;
}
else{
f=1;
printf("obtained in the position %d:",mid); getch();
exit();
}
}
if(f==0)
printf("not present");
63

OUTPUT
Enter the n value:5
Enter the number in ascending order a[1]=10
Enter the number in ascending order a[2]=8
Enter the number in ascending order a[3]=9
Enter the number in ascending order a[4]=24
Enter the number in ascending order a[5]=1
Enter the search element:9
obtained in the position 3:

RESULT:
Thus, the program to implement the Binary Search algorithm in C was executed
successfully.
64

Ex.no:12 a IMPLEMENTATION OF INSERTION SORT ALGORITHM

AIM:

To write a program in C to implement Insetion sort algorithm.

ALGORITHM :

Step 1 − If the element is the first one, it is already sorted.


Step 2 – Move to next element
Step 3 − Compare the current element with all elements in the sorted array
Step 4 – If the element in the sorted array is smaller than the current element, iterate to the next
element. Otherwise, shift all the greater element in the array by one position towards right
Step 5 − Insert the value at the correct position
Step 6 − Repeat until the complete list is sorted

PROGRAM:
#include<stdio.h>
int main()
{
int counter1,counter2,chk,temp_val,val[100];
printf("Please enter the total count of the elements that you want to sort: \n");
scanf("%d",&chk);
printf("Please input the elements that has to be sorted:\n");
for(counter1=0;counter1<chk;counter1++)
{
scanf("%d",&val[counter1]);
}
for(counter1=1;counter1<=chk-1;counter1++)
{
temp_val=val[counter1];
counter2=counter1-1;
while((temp_val<val[counter2])&&(counter2>=0))
{
val[counter2+1]=val[counter2];
counter2=counter2-1;
}
val[counter2+1]=temp_val;
}
printf("\n Output generated after using insertion sort \n");
for(counter1=0;counter1<chk;counter1++)
{
printf("%d ",val[counter1]);
}
65

return 0;
}
Output

RESULT:
Thus, the program to implement the Insertion Sort algorithm in C was executed
successfully.
66

Ex.no:12 b IMPLEMENTATION OF SELECTION SORT ALGORITHM


AIM:

To write a program in C to implement Selection sort algorithm.

ALGORITHM

Step 1: For i = 1 to n-1.


step 2: Set min = arr[i]
step 3: Set position = i.
step 4: For j = i+1 to n-1 repeat:
if (min > arr[j])
Set min = arr[j]
Set position = j.
[end of if]
PROGRAM:
#include <stdio.h>
int main()
{
int a[100], number, i, j, temp;
printf("\n Please Enter the total Number of Elements : ");
scanf("%d", &number);
printf("\n Please Enter the Array Elements : ");
for(i = 0; i < number; i++)
scanf("%d", &a[i]);

for(i = 0; i < number; i++) {


for(j = i + 1; j < number; j++) {
if(a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("\n Selection Sort Result : ");
for(i = 0; i < number; i++) {
printf(" %d \t", a[i]);
}
printf("\n");
return 0;
}
OUTPUT:
Please Enter the total Number of Elements : 5
Please Enter the Array Elements : 45 89 12 54 34
Selection Sort Result : 12 34 45 54 89
RESULT:
Thus, the program to implement the Selection Sort algorithm in C was executed successfully.
67

Ex.no:13 IMPLEMENTATION OF MERGE SORT ALGORITHM


AIM:
To implement the Merge sort algorithm using C.

ALGORITHM:
Step 1: Get the elements to be sorted as input.
Step 2:Divide the list recursively into two halves until it can no more be divided.
Step 3:Merge the smaller lists into new list in sorted order.
Step 4: Display the sorted list.

PROGRAM:
#include<stdio.h>
#include<conio.h>
void mergesort(int a[],inti,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
return 0;
}
void mergesort(int a[],inti,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; //array used for merging
inti,j,k;
i=i1; //beginning of the first list
68

j=i2; //beginning of the second list


k=0;

while(i<=j1 && j<=j2) //while elements in both lists


{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}

while(i<=j1) //copy remaining elements of the first list


temp[k++]=a[i++];

while(j<=j2) //copy remaining elements of the second list


temp[k++]=a[j++];

//Transfer elements from temp[] back to a[]


for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
OUTPUT:

RESULT:
Thus, the program to implement the Merge Sort algorithm in C was executed successfully.
69

Ex.no:14 IMPLEMENTATION OF HASHING USING OPEN ADDRESSING WITH


LINEAR PROBING
AIM:
To implement the open addressing with Linear probing

ALGORITHM:
1.Create an array of structure (i.e a hash table).
2. Take a key and a value to be stored in hash table as input.
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.
Note: This probing will continue until we reach the same element again (from where we began
probing)
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<conio.h>
#include<stdlib.h>
#define TABLE_SIZE 10
int h[TABLE_SIZE]={NULL};
void insert()
{
int key,index,i,flag=0,hkey;
printf("Enter a value to insert into hash table: ");
scanf("%d",&key);
hkey=key%TABLE_SIZE;
for(i=0;i<TABLE_SIZE;i++)
{
index=(hkey+i)%TABLE_SIZE;
if(h[index] == NULL)
{
h[index]=key;
break;
}
}
if(i == TABLE_SIZE)
printf("\nElement cannot be inserted!\n");
}
void search()
{
70

int key,index,i,flag=0,hkey;
printf("Enter search element: ");
scanf("%d",&key);
hkey=key%TABLE_SIZE;
for(i=0;i<TABLE_SIZE; i++)
{
index=(hkey+i)%TABLE_SIZE;
if(h[index]==key)
{
printf("Value is found at index: %d",index);
break;
}
}
if(i == TABLE_SIZE)
printf("Value is not found!");
}
void display()
{
int i;
printf("\nElements in the hash table are:");
for(i=0;i< TABLE_SIZE; i++)
printf("\nAt Index: %d \t Value: %d",i,h[i]);
}
main()
{
clrscr();
int opt,i;
while(1)
{
printf("\n1.Insert\n2.Display\n3.Search\n4.Exit\nEnter the choice: ");
scanf("%d",&opt);
switch(opt)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
search();
break;
case 4:exit(0);
}
}
}
OUTPUT:
1.Insert
2.Display
3.Search
71

4.Exit
Enter the choice: 1
Enter a value to insert into hash table: 34
1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 1
Enter a value to insert into hash table: 76
1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 1
Enter a value to insert into hash table: 12
1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 2
Elements in the hash table are:
At Index: 0 Value: 0
At Index: 1 Value: 0
At Index: 2 Value: 12
At Index: 3 Value: 0
At Index: 4 Value: 34
At Index: 5 Value: 0
At Index: 6 Value: 76
At Index: 7 Value: 0
At Index: 8 Value: 0
At Index: 9 Value: 0
1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 1
Enter a value to insert into hash table: 50
1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 1
72

Enter a value to insert into hash table: 42


1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 2

Enter search element: 34


Value is found at index: 4
1.Insert
2.Display
3.Search
4.Exit
Enter the choice: 2
Elements in the hash table are:
At Index: 0 Value: 50
At Index: 1 Value: 0
At Index: 2 Value: 12
At Index: 3 Value: 42
At Index: 4 Value: 34
At Index: 5 Value: 0
At Index: 6 Value: 76
At Index: 7 Value: 0
At Index: 8 Value: 0
At Index: 9 Value: 0

RESULT:
Thus the Hashing using Open Addressing with Linear Probing was implemented Successfully.

You might also like