0% found this document useful (0 votes)
40 views98 pages

DS Labmanual

The document describes the implementation of a queue using an array in C programming. It defines the size of the array, initializes the front and rear pointers to -1, and includes functions for insertion (enqueue), deletion (dequeue), and displaying all elements. The main function runs a loop that takes user input to call these functions or exit. The program demonstrates basic queue operations using an array to store elements.

Uploaded by

220701292
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)
40 views98 pages

DS Labmanual

The document describes the implementation of a queue using an array in C programming. It defines the size of the array, initializes the front and rear pointers to -1, and includes functions for insertion (enqueue), deletion (dequeue), and displaying all elements. The main function runs a loop that takes user input to call these functions or exit. The program demonstrates basic queue operations using an array to store elements.

Uploaded by

220701292
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/ 98

RAJALAKSHMI E NGINEERING COLLEGE, CHENNAI

DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS

LAB MANUAL

CB19241-DATA STRUCUTES AND ALGORITHMS

TOWER OF HANOI USING STACK

Ex.No.1 Date:

Aim

To implement Tower of Hanoi using stack.

Algorithm

1. Start

2. Let the three towers be the source, dest, aux.

3. Read the number of disks, n from the user.

4. Move n-1 disks from source to aux.

5. Move nth disk from source to dest.

6. Move n-1 disks from aux to dest.

7. Repeat Steps 3 to 5, by decrementing n by 1.

8. Stop

Program:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#include <limits.h>
struct Stack

{
unsigned capacity;

int top;

int *array;

};

struct Stack* createStack(unsigned capacity)

struct Stack* stack =

(struct Stack*) malloc(sizeof(struct Stack));

stack -> capacity = capacity;

stack -> top = -1;

stack -> array =

(int*) malloc(stack -> capacity * sizeof(int));

return stack;

int isFull(struct Stack* stack)

return (stack->top == stack->capacity - 1);

int isEmpty(struct Stack* stack)

return (stack->top == -1);

void push(struct Stack *stack, int item)

if (isFull(stack))

return;

stack -> array[++stack -> top] = item;

}
int pop(struct Stack* stack)

if (isEmpty(stack))

return INT_MIN;

return stack -> array[stack -> top--];

void moveDisk(char fromPeg, char toPeg, int disk)

printf("Move the disk %d from \'%c\' to \'%c\'\n",

disk, fromPeg, toPeg);

void moveDisksBetweenTwoPoles(struct Stack *src,

struct Stack *dest, char s, char d)

int pole1TopDisk = pop(src);

int pole2TopDisk = pop(dest);

if (pole1TopDisk == INT_MIN)

push(src, pole2TopDisk);

moveDisk(d, s, pole2TopDisk);

else if (pole2TopDisk == INT_MIN)

push(dest, pole1TopDisk);

moveDisk(s, d, pole1TopDisk);

else if (pole1TopDisk > pole2TopDisk)

{
push(src, pole1TopDisk);

push(src, pole2TopDisk);

moveDisk(d, s, pole2TopDisk);

else

push(dest, pole2TopDisk);

push(dest, pole1TopDisk);

moveDisk(s, d, pole1TopDisk);

void tohIterative(int num_of_disks, struct Stack

*src, struct Stack *aux,

struct Stack *dest)

int i, total_num_of_moves;

char s = 'S', d = 'D', a = 'A';

if (num_of_disks % 2 == 0)

char temp = d;

d = a;

a = temp;

total_num_of_moves = pow(2, num_of_disks) - 1;

for (i = num_of_disks; i >= 1; i--)

push(src, i);

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


{

if (i % 3 == 1)

moveDisksBetweenTwoPoles(src, dest, s, d);

else if (i % 3 == 2)

moveDisksBetweenTwoPoles(src, aux, s, a);

else if (i % 3 == 0)

moveDisksBetweenTwoPoles(aux, dest, a, d);

int main()

unsigned num_of_disks ;

printf("Enter number of disks : ");

scanf("%u",&num_of_disks);

struct Stack *src, *dest, *aux;

src = createStack(num_of_disks);

aux = createStack(num_of_disks);

dest = createStack(num_of_disks);

tohIterative(num_of_disks, src, aux, dest);

return 0;

OUTPUT:

Enter number of disks : 5


Move the disk 1 from 'S' to 'D'

Move the disk 2 from 'S' to 'A'

Move the disk 1 from 'D' to 'A'

Move the disk 3 from 'S' to 'D'

Move the disk 1 from 'A' to 'S'

Move the disk 2 from 'A' to 'D'

Move the disk 1 from 'S' to 'D'

Move the disk 4 from 'S' to 'A'

Move the disk 1 from 'D' to 'A'

Move the disk 2 from 'D' to 'S'

Move the disk 1 from 'A' to 'S'

Move the disk 3 from 'D' to 'A'

Move the disk 1 from 'S' to 'D'

Move the disk 2 from 'S' to 'A'

Move the disk 1 from 'D' to 'A'

Move the disk 5 from 'S' to 'D'

Move the disk 1 from 'A' to 'S'


Move the disk 2 from 'A' to 'D'

Move the disk 1 from 'S' to 'D'

Move the disk 3 from 'A' to 'S'

Move the disk 1 from 'D' to 'A'

Move the disk 2 from 'D' to 'S'

Move the disk 1 from 'A' to 'S'

Move the disk 4 from 'A' to 'D'

Move the disk 1 from 'S' to 'D'

Move the disk 2 from 'S' to 'A'

Move the disk 1 from 'D' to 'A'

Move the disk 3 from 'S' to 'D'

Move the disk 1 from 'A' to 'S'

Move the disk 2 from 'A' to 'D'

Move the disk 1 from 'S' to 'D'

Result
Thus the program for implementation of Tower of Hanoi using stack is executed successfully.
ARRAY IMPLEMENTATION OF STACK

Ex.No.2a Date:

Aim

To write a C program to perform array implementation of stack.

Algorithm

1. Start the program.


2. Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.

3. Declare all the functions used in stack implementation.


4. Create a one dimensional array with fixed size (int stack[SIZE])
5. Define a integer variable 'top' and initialize with '-1'. (int top = -1)
6. Do push operation
7. Pop out the resut
8. Stop the program

Program

#include<conio.h>

#include<stdio.h>

#define max 50

void push();

void pop();

void display();

int menu();

int stack[max], top=0;

void main()

int ch;
clrscr();

do{

ch=menu();

switch(ch)

case 1: push();

break;

case 2: pop();

break;

case 3: display();

break;

case 4: exit();

default: printf("\nEnter a valid choice!!");

}while(ch<4);

int menu()

int ch;

printf("\nStack");

printf("\n1.Push\n2.Pop\n3.Display\n4.Exit");

printf("\nEnter your Choice:");

scanf("%d",&ch);

return ch;

}
void push()

if(top==max)

printf("\nOverflow");

else

int element;

printf("\nEnter Element:");

scanf("%d",&element);

printf("\nElement(%d) has been pushed at %d", element, top);

stack[top++]=element;

void pop()

if(top==-1)

printf("\nUnderflow");

else

top--;

printf("\nElement has been popped out!");

void display()

if(top==0)
printf("\nStack is Empty!!");

else

int i;

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

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

Output

Stack
1.Push
2.Pop
3.Display
4.Exit

Enter Your Choice:1

Enter Element:28

Element 28 has been pushed at 0

Stack
1.Push
2.Pop
3.Display
4.Exit
Enter Your Choice:1

Enter Element:32

Element 32 has been pushed at 1

Stack
1.Push
2.Pop
3.Display
4.Exit

Enter Your Choice:1

Enter Element:44

Element 44 has been pushed at 2

Result
Thus the program for array implementation of stack is executed successfully.
ARRAY IMPLEMENTATION OF QUEUE
Ex.No.2b Date:

Aim

To write a C program to perform array implementation of queue.

Algorithm

1. Start the program.


2. Include all the header files which are used in the program and define a constant
'SIZE' with specific value.
3. Declare all the user defined functions which are used in queue implementation.
4. Create a one dimensional array with above defined SIZE (int queue[SIZE])
5. Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int front = -1,
rear = -1)

6. Enque Operation and Display the result.

7. Stop the process.

Program

#include <stdio.h>
#define MAX 50
int queue_array[MAX];
int rear = - 1;
int front = - 1;

main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /*End of switch*/
} /*End of while*/
} /*End of main()*/

insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /*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)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
} /*End of display() */

Sample Input /Output:


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 : 10

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 : 15

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 : 20

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 : 30

1.Insert element to queue

2.Delete element from queue

3.Display all elements of queue

4.Quit

Enter your choice : 2

Element deleted from queue is : 10

1.Insert element to queue

2.Delete element from queue

3.Display all elements of queue

4.Quit

Enter your choice : 3

Queue is :

15 20 30

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 for array implementation of Queue is executed successfully.


IMPLEMENTATION OF SINGLY LINKED LIST

Ex.No.3
Date:

Aim

To write a c program for implementation of insertion, deletion and traverse operation in


singly linked list.

Algorithm

Inserting At Beginning of the list

1 - Create a newNode with given value.

2 - Check whether list is Empty (head == NULL)

3 - If it is Empty then, set newNode→next = NULL and head = newNode.

4 - If it is Not Empty then, set newNode→next = head and head = newNode.

Inserting At End of the list

1 - Create a newNode with given value and newNode → next as NULL.

2 - Check whether list is Empty (head == NULL).

3 - If it is Empty then, set head = newNode.

4 - If it is Not Empty then, define a node pointer temp and initialize with head.

5 - Keep moving the temp to its next node until it reaches to the last node in the list
(until temp → next is equal to NULL).

Step 6 - Set temp → next = newNode.

Deletion
In a single linked list, the deletion operation can be performed in three ways.

1. Deleting from Beginning of the list


2. Deleting from End of the list
3. Deleting a Specific Node

Deleting from Beginning of the list

1 - Check whether list is Empty (head == NULL)

2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate
the function.
3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.

4 - Check whether list is having only one node (temp → next == NULL)

5 - If it is TRUE then set head = NULL and delete temp (Setting Empty list conditions)

6 - If it is FALSE then set head = temp → next, and delete temp.

Deleting from End of the list

1 - Check whether list is Empty (head == NULL)

2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate
the function.

3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize
'temp1' with head.

4 - Check whether list has only one Node (temp1 → next == NULL)

5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate the function.
(Setting Empty list condition)

6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node. Repeat
the same until it reaches to the last node in the list. (until temp1 → next == NULL)

7 - Finally, Set temp2 → next = NULL and delete temp1.

Deleting a Specific Node from the list

1 - Check whether list is Empty (head == NULL)

2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate
the function.

3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize
'temp1' with head.

4 - Keep moving the temp1 until it reaches to the exact node to be deleted or to the last
node. And every time set 'temp2 = temp1' before moving the 'temp1' to its next node.

5 - If it is reached to the last node then display 'Given node not found in the list! Deletion
not possible!!!'. And terminate the function.

6 - If it is reached to the exact node which we want to delete, then check whether list is
having only one node or not

7 - If list has only one node and that is the node to be deleted, then set head = NULL and
delete temp1 (free(temp1)).

8 - If list contains multiple nodes, then check whether temp1 is the first node in the list
(temp1 == head).
9 - If temp1 is the first node then move the head to the next node (head = head → next)
and delete temp1.

10 - If temp1 is not first node then check whether it is last node in the list (temp1 → next
== NULL).

11 - If temp1 is last node then set temp2 → next = NULL and


delete temp1 (free(temp1)).

12 - If temp1 is not first node and not last node then set temp2 → next = temp1 →
next and delete temp1 (free(temp1)).

Traversing the linked list

To traverse the linked list keep moving the temp node to the next one and display in
contents, when temp is NULL, get out of the while loop.

.Program

#include <stdio.h>

#include<stdlib.h>

struct Node

int data;

struct Node* next;

};

typedef struct Node node;

node *head=NULL;

void insertatbeg(int e)

node* newnode=malloc(sizeof(node));

newnode->data=e;

if(head==NULL)

newnode->next=NULL;

head=newnode;

}
else

newnode->next=head;

head=newnode;

void insertatend(int e)

node* newnode=malloc(sizeof(node));

newnode->data=e;

if(head==NULL)

newnode->next=NULL;

head=newnode;

else

{ newnode->next=NULL;

node* position=head;

while(position->next!=NULL)

position=position->next;

position->next=newnode;

void insertatmid(int p,int e)

node* newnode=malloc(sizeof(node));

newnode->data=e;

if(head==NULL)
{

newnode->next=NULL;

head=newnode;

else

node* position=head;

while(position->data!=p)

position=position->next;

newnode->next=position->next;

position->next=newnode;

void dis()

if(head==NULL)

printf("The list is empty\n");

else

printf("The elements are : ");

node* temp=head;

while(temp!=NULL)

printf("%d ",temp->data);

temp=temp->next;

printf(“\n”);

}
}

void deleteatbeg()

if(head==NULL)

printf("The list is empty");

else

node* temp=head;

head=temp->next;

printf("The deleted element is %d\n",temp->data);

free(temp);

void deleteatend()

if(head==NULL)

printf("The list is empty");

else

node* position=head;

node* temp;

while(position->next->next!=NULL)

position=position->next;

temp=position->next;

position->next=NULL;

printf("The deleted element is : %d\n",temp->data);

free(temp);

}
}

void deleteatmid(int e)

if(head==NULL)

printf("The list is empty");

else

node* position=head;

node* temp;

while(position->next->data!=e)

position=position->next;

temp=position->next;

position->next=temp->next;

printf("The deleted element is : %d\n",temp->data);

int main()

int e,p,ch;

printf("********LIST OF CHOICE*********\n");

printf("1-insert at beginning\t2-insert at end\t3-insertatmid\n4-delete from beginning\t5-delete


from end\t6-delete from mid\n7-display\t8-exit\n");

do{

printf("Enter ur choice: ");

scanf("%d",&ch);
switch(ch)

case 1:

printf("Enter the element: ");

scanf("%d",&e);

insertatbeg(e);

break;

case 2:

printf("Enter the element: ");

scanf("%d",&e);

insertatend(e);

break;

case 3:

printf("Enter the element for p-previous element and element for e to insert: ");

scanf("%d%d",&p,&e);

insertatmid(p,e);

break;

case 4:

deleteatbeg();

break;

case 5:

deleteatend();

break;

case 6:

printf("Enter the element to delete: ");

scanf("%d",&e);

deleteatmid(e);

break;
case 7:

dis();

break;

}while(ch!=8);

return 0;

OUTPUT:

********LIST OF CHOICE*********

1-insert at beginning 2-insert at end 3-insertatmid

4-delete from beginning 5-delete from end 6-delete from mid

7-display 8-exit

Enter ur choice: 1

Enter the element: 2

Enter ur choice: 1

Enter the element: 1

Enter ur choice: 2

Enter the element: 3

Enter ur choice: 2

Enter the element: 4

Enter ur choice: 3

Enter the element for p-previous element and element for e to insert: 2

Enter ur choice: 7

The elements are : 1 2 5 3 4

Enter ur choice: 4

The deleted element is 1


Enter ur choice: 5

The deleted element is : 4

Enter ur choice: 6

Enter the element to delete: 5

The deleted element is : 5

Enter ur choice: 7

The elements are : 2 3

Enter ur choice: 8

Result

Thus the operations of singly linked list has been implemented successfully.

IMPLEMENTATION OF DOUBLY LINKED LIST


Ex.No.4 Date:

Aim

To write a c program tor implementation of insertion, deletion and traverse operation in


doubly linked list.

Algorithm

1.For insertion at the beginning, allocate memory for new node and assign data to new node, point
next of newnode to the first node and prev to node point prev of the first node to newnode, point
head to newnode.

2.To insert at the end, create a new node, if the list is empty, make the new node as the head node.
Otherwise. Traverse to the end point next of new node to NULL to prev of new node to the last
node of list before insertion.

3.For insertion in between two nodes, create a new node and assign the value of next from prev
node to the next of newnode, assign the address of new node to the next of prev data. Assign the
address prev of next node to prev of newnode and assign the address of newnode to the prev of
next node.

4.For deletion of first node, store head in temp and make head of next to point of head and prev
gtemp.

5.For deletion of last node, traverse to element just before and change its next pointer to NULL.

6.For deletion of middle, traverse to element just before the element to be deleted, and change
next pointer to next of node to be deleted and free the node.

Program

#include <stdio.h>

#include<stdlib.h>

struct Node

int data;

struct Node* prev;

struct Node* next;


};

typedef struct Node node;

node *head=NULL;

void insertatbeg(int e)

node* newnode=malloc(sizeof(node));

newnode->data=e;

if(head==NULL)

newnode->next=NULL;

newnode->prev=head;

head=newnode;

else

newnode->next=head;

newnode->next->prev=newnode;

newnode->prev=head;

head=newnode;

void insertatend(int e)

node* newnode=malloc(sizeof(node));

newnode->data=e;

newnode->next=NULL;

if(head==NULL)
{

newnode->prev=head;

head=newnode;

else

node* position=head;

while(position->next!=NULL)

position=position->next;

position->next=newnode;

newnode->prev=position;

void insertatmid(int p,int e)

node* newnode=malloc(sizeof(node));

newnode->data=e;

node* position=head;

while(position->data!=p)

position=position->next;

newnode->next=position->next;

position->next->prev=newnode;

position->next=newnode;

newnode->prev=position;

void dis()

if(head==NULL)
printf("The list is empty\n");

else

printf("The elements are : ");

node* temp=head;

while(temp!=NULL)

printf("%d ",temp->data);

temp=temp->next;

void deleteatbeg()

if(head==NULL)

printf("The list is empty");

else

node* temp=head;

head->next=temp->next;

temp->next->prev=head;

printf("The deleted element is %d\n",temp->data);

free(temp);

void deleteatend()

if(head==NULL)
printf("The list is empty");

else

node* position=head;

node* temp;

while(position->next->next!=NULL)

position=position->next;

temp=position->next;

position->next=NULL;

printf("The deleted element is : %d\n",temp->data);

free(temp);

void deleteatmid(int e)

if(head==NULL)

printf("The list is empty");

else

node* position=head;

node* temp;

while(position->next->data!=e)

position=position->next;

temp=position->next;

position->next=temp->next;

temp->next->prev=position;

printf("The deleted element is : %d\n",temp->data);

free(temp);
}

int main()

int e,p,ch;

printf("********LIST OF CHOICE*********\n");

printf("1-insert at beginning\t2-insert at end\t3-insertatmid\n4-delete from beginning\t5-delete


from end\t6-delete from mid\n7-display\t8-exit\n");

do{

printf("Enter ur choice: ");

scanf("%d",&ch);

switch(ch)

case 1:

printf("Enter the element: ");

scanf("%d",&e);

insertatbeg(e);

break;

case 2:

printf("Enter the element: ");

scanf("%d",&e);

insertatend(e);

break;

case 3:

printf("Enter the element for p-previous element and element for e to insert: ");

scanf("%d%d",&p,&e);

insertatmid(p,e);

break;

case 4:
deleteatbeg();

break;

case 5:

deleteatend();

break;

case 6:

printf("Enter the element to delete: ");

scanf("%d",&e);

deleteatmid(e);

break;

case 7:

dis();

break;

}while(ch!=8);

return 0;

OUTPUT:

********LIST OF CHOICE*********

1-insert at beginning 2-insert at end 3-insertatmid

4-delete from beginning 5-delete from end 6-delete from mid

7-display 8-exit

Enter ur choice: 1

Enter the element: 5

Enter ur choice: 1

Enter the element: 4

Enter ur choice: 2

Enter the element: 2


Enter ur choice: 2

Enter the element: 3

Enter ur choice: 3

Enter the element for p-previous element and element for e to insert: 4

Enter ur choice: 7

The elements are : 4 1 5 2 3 Enter ur choice: 4

The deleted element is 4

Enter ur choice: 5

The deleted element is : 3

Enter ur choice: 6

Enter the element to delete: 5

The deleted element is : 5

Enter ur choice: 7

The elements are : 1 2

Enter ur choice:8

Result

Thus the implementation of Doubly linked list is done and verified successfully.

IMPLEMENTATION OF CIRCULAR LINKED LIST


Ex.No.5 Date:

Aim

To write a c program to implement Circular linked list.

Algorithm

1.Insertion into circular singly linked list at beginning, create the new node , store the address of
the current first nose in the new node, point the last node to new node.

2.For insertion at the end, create a newnode, store the address of the head node to the next to next
of new node, making new node the last node. Point the current last node to new node, make
newnode as the last node.

3.For insertion in between two nodes, traverse to the node given, point the next of new node to
the next to the given node. Store the address of new node at the next of the node.

4.For deletion of first node, free the memory occupied by the node, store NULL in last.

5.For deletion of last node, find the node before the last node, let it be temp, free the memory of
last and make temp as the last node.

6.For deletion at the middle traverse to the node to be deleted, let the node be temp, free the
memory of temp.

Program

#include <stdio.h>

#include<stdlib.h>

struct Node

int data;

struct Node* next;


};

typedef struct Node node;

node *last=NULL;

void insertatbeg(int e)

node* newnode=malloc(sizeof(node));

newnode->data=e;

if(last==NULL)

newnode->next=newnode;

last=newnode;

else

newnode->next=last->next;

last->next=newnode;

void insertatend(int e)

node* newnode=malloc(sizeof(node));

newnode->data=e;

if(last==NULL)

newnode->next=last->next;

last->next=newnode;

else
{ newnode->next=last->next;

last->next=newnode;

last=newnode;

void insertatmid(int p,int e)

node* newnode=malloc(sizeof(node));

newnode->data=e;

node* temp=last->next;

while(temp->data!=p)

temp=temp->next;

newnode->next=temp->next;

temp->next=newnode;

void dis()

if(last==NULL)

printf("The list is empty\n");

else

printf("The elements are : ");

node* temp=last->next;

do{

printf("%d ",temp->data);

temp=temp->next;

}while(temp!=last->next);

printf("\n");
}

void deleteatbeg()

if(last==NULL)

printf("The list is empty");

else

node* temp=last->next;

last->next=temp->next;

printf("The deleted element is %d\n",temp->data);

free(temp);

void deleteatend()

if(last==NULL)

printf("The list is empty");

else

node* position=last->next;

node* temp;

while(position->next!=last)

position=position->next;

temp=position->next;

position->next=last->next;

last=position;

printf("The deleted element is : %d\n",temp->data);


free(temp);

void deleteatmid(int e)

node* position=last->next;

node* temp;

while(position->next->data!=e)

position=position->next;

temp=position->next;

position->next=temp->next;

printf("The deleted element is : %d\n",temp->data);

free(temp);

int main()

int e,p,ch;

printf("********LIST OF CHOICE*********\n");

printf("1-insert at beginning\t2-insert at end\t3-insertatmid\n4-delete from beginning\t5-delete


from end\t6-delete from mid\n7-display\t8-exit\n");

do{

printf("Enter ur choice: ");

scanf("%d",&ch);

switch(ch)

case 1:
printf("Enter the element: ");

scanf("%d",&e);

insertatbeg(e);

break;

case 2:

printf("Enter the element: ");

scanf("%d",&e);

insertatend(e);

break;

case 3:

printf("Enter the element for p-previous element and element for e to insert: ");

scanf("%d%d",&p,&e);

insertatmid(p,e);

break;

case 4:

deleteatbeg();

break;

case 5:

deleteatend();

break;

case 6:

printf("Enter the element to delete: ");

scanf("%d",&e);

deleteatmid(e);

break;

case 7:

dis();

break;
}

}while(ch!=8);

return 0;

OUTPUT:

********LIST OF CHOICE*********

1-insert at beginning 2-insert at end 3-insertatmid

4-delete from beginning 5-delete from end 6-delete from mid

7-display 8-exit

Enter ur choice: 1

Enter the element: 7

Enter ur choice: 1

Enter the element: 6

Enter ur choice: 2

Enter the element: 8

Enter ur choice: 2

Enter the element: 9

Enter ur choice: 3

Enter the element for p-previous element and element for e to insert: 7

Enter ur choice: 7

The elements are : 6 7 5 8 9

Enter ur choice: 4

The deleted element is 6

Enter ur choice: 5
The deleted element is : 9

Enter ur choice: 6

Enter the element to delete: 5

The deleted element is : 5

Enter ur choice: 7

The elements are : 7 8

Enter ur choice: 8

Result

Thus the Circular linked list has been implemented successfully.


POLYNOMIAL ADDITION USING STACK
Ex.No.6 Date:
Aim
To implement polynomial addition using stack.

Algorithm

1.Read the two polynomials ( p and q) from the user.


2 while p and q are not null, repeat step 3.
3. If powers of the two terms ate equal
then if the terms do not cancel then insert the sum of the terms into the sum Polynomial
Advance p
Advance q
Else if the power of the first polynomial> power of second
Then insert the term from first polynomial into sum polynomial
Advance p
Else insert the term from second polynomial into sum polynomial
Advance q
4. copy the remaining terms from the non empty polynomial into the
sum polynomial.

Program

#include<stdio.h>

#include<stdlib.h>

struct node

int coeff,pow;

struct node *next;

}*start1=NULL,*start2=NULL,*start=NULL,*start3=NULL,*p,*p1,*p2,*temp,*a=NULL;

typedef struct node node;

void create(node *);

void display(node *);

void add(node *,node *,node *);


void main()

start1=(node *)malloc(sizeof(node));

start2=(node *)malloc(sizeof(node));

start3=(node *)malloc(sizeof(node));

printf("\nEnter 1st Polynomial\n");

create(start1);

printf("\nEnter 2nd Polynomial\n");

create(start2);

printf("\n1st Polynomial\n");

display(start1);

printf("\n2nd Polynomial\n");

display(start2);

add(start1,start2,start3);

printf("\nAdded Polynomial: \n");

display(start3);

start3=NULL;

void create(node *temp)

int i, ch;

printf(“enter the number of terms”);

scanf(“%d”,&ch);

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

printf("Enter coefficient and power\n ");

scanf("%d%d",&temp->coeff,&temp->pow);

temp->next=(node *)malloc(sizeof(node));
temp=temp->next;

temp->next=NULL;

void display(node *start)

p=start;

while(p->next!=NULL)

printf("%dx^%d",p->coeff,p->pow);

p=p->next;

if(p->next!=NULL)

printf(" + ");

printf("\n");

void add(node *start1,node *start2,node *start3)

while(start1->next && start2->next)

if(start1->pow==start2->pow)

start3->coeff=start1->coeff+start2->coeff;

start3->pow=start1->pow;

start1=start1->next;

start2=start2->next;

else if(start1->pow > start2->pow)


{

start3->coeff=start1->coeff;

start3->pow=start1->pow;

start1=start1->next;

else

start3->coeff=start2->coeff;

start3->pow=start2->pow;

start2=start2->next;

start3->next=(node *)malloc(sizeof (node));

start3=start3->next;

start3->next=NULL;

while(start1->next || start2->next)

if(start1->next)

start3->pow=start1->pow;

start3->coeff=start1->coeff;

start1=start1->next;

if(start2->next)

start3->coeff=start2->coeff;

start3->pow=start2->pow;

start2=start2->next;
}

start3->next=(node *)malloc(sizeof(node));

start3=start3->next;

start3->next=NULL;

OUTPUT

Enter 1st Polynomial

enter the number of terms 2

Enter coefficient and power

42

Enter coefficient and power

71

Enter 2nd Polynomial

enter the number of terms 3

Enter coefficient and power

11 3

Enter coefficient and power

2 1

Enter coefficient and power

7 0

1st Polynomial

4x^2 + 7x^1

2nd Polynomial

11x^3 + 2x^1 + 7x^0

Added Polynomial:
11x^3 + 4x^2 + 9x^1 + 7x^0

Result
Thus the program for polynomial addition has been executed successfully.
IMPLEMENTATION OF BINARY SEARCH TREE
Ex.No.7a Date:
Aim

To write a C program to performing Binary Search Tree Operations.

Algorithm :

1. Start the program.


Search Operation in BST
2. Read the search element from the user

3. Compare, the search element with the value of root node in the tree.

4. If both are matching, then display "Given node found!!!" and terminate the function

5. If both are not matching, then check whether search element is smaller or
larger than that node value.
6. If search element is smaller, then continue the search process in left subtree.
7. If search element is larger, then continue the search process in right subtree.
8. Repeat the same until we found exact element or we completed with a leaf node
9. we reach to a leaf node and it is also not matching, then display "Element
not found" and terminate the function.
10.Stop the process

program

#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node*left;
struct node*right;
};
typedef struct node BST;
BST *LOC, *PAR;
void search(BST *root, int item)
{
BST *save,*ptr;
if (root == NULL)
{
LOC = NULL;
PAR=NULL;
}
if (item == root -> info)
{
LOC = root;
PAR = NULL;
return;
}
if (item < root->info)
{
save = root;
ptr = root->left;
}
else
{
save = root;
ptr = root -> right;
}
while( ptr != NULL)
{
if (ptr -> info == item)
{
LOC = ptr;
PAR = save;
return;
}
if(item < ptr->info)
{
save = ptr;
ptr = ptr->left;
}
else
{
save = ptr;
ptr = ptr->right;
}
}
LOC = NULL;
PAR = save;
return;
}

struct node* findmin(struct node*r)


{
if (r == NULL)
return NULL;
else if (r->left!=NULL)
return findmin(r->left);
else if (r->left == NULL)
return r;
}
struct node*insert(struct node*r, int x)
{
if (r == NULL)
{
r = (struct node*)malloc(sizeof(struct node));
r->info = x;
r->left = r->right = NULL;
return r;
}
else if (x < r->info)
r->left = insert(r->left, x);
else if (x > r->info)
r->right = insert(r->right, x);
return r;
}
struct node* del(struct node*r, int x)
{
struct node *t;
if(r == NULL)
printf("\nElement not found");
else if (x < r->info)
r->left = del(r->left, x);
else if (x > r->info)
r->right = del(r->right, x);
else if ((r->left != NULL) && (r->right != NULL))
{
t = findmin(r->right);
r->info = t->info;
r->right = del(r->right, r->info);
}
else
{
t = r;
if (r->left == NULL)
r = r->right;
else if (r->right == NULL)
r = r->left;
free(t);
}
return r;
}

int main()
{
struct node* root = NULL;
int x, c = 1, z;
int element;
char ch;
printf("\nEnter an element: ");
scanf("%d", &x);
root = insert(root, x);
printf("\nDo you want to enter another element :y or n");
scanf(" %c",&ch);
while (ch == 'y')
{
printf("\nEnter an element:");
scanf("%d", &x);
root = insert(root,x);
printf("\nPress y or n to insert another element: y or n: ");
scanf(" %c", &ch);
}
while(1)
{
printf("\n1 Insert an element ");
printf("\n2 Delete an element");
printf("\n3 Search for an element ");
printf("\n4 Exit ");
printf("\nEnter your choice: ");
scanf("%d", &c);
switch(c)
{
case 1:
printf("\nEnter the item:");
scanf("%d", &z);
root = insert(root,z);
break;
case 2:
printf("\nEnter the info to be deleted:");
scanf("%d", &z);
root = del(root, z);
break;
case 3:
printf("\nEnter element to be searched: ");
scanf("%d", &element);
search(root, element);
if(LOC != NULL)
printf("\n%d Found in Binary Search Tree !!\n",element);
else
printf("\nIt is not present in Binary Search Tree\n");
break;
case 4:
printf("\nExiting...");
return;
default:
printf("Enter a valid choice: ");

}
}
return 0;
}

Output:

Enter an element: 32
Do you want to enter another element, y or n: y

Enter an element: 54
Press y or n to insert another element, y or n: y

Enter an element: 65
Press y or n to insert another element, y or n: y

1 Insert an element
2 Delete an element
3 Search for an element
4 Exit
Enter your choice: 3

Enter element to be searched: 32


32 Found in Binary Search Tree !!
1 Insert an element
2 Delete an element
3 Search for an element

4 Exit
Enter your choice: 4
Exiting...

Result :
Thus the program for performing Binary Search Tree Operations is executed successfully.
IMPLEMENTATION OF TREE TRAVERSALS

Ex.No.7b Date:

Aim

To write a C program for performing Binary Tree Traversal.

Algorithm
1. Start the program.
PREORDER TRAVERSAL

2. Process the root node (N).

3. Traverse the left subtree of N (L).

4. Traverse the right subtree of N (R).

INORDER TRAVERSAL

5. Traverse the left subtree of N (L).

6. Process the root node (N).

7. Traverse the right subtree of N (R).

POSTORDER TRAVERSAL

8. Traverse the left subtree of N (L).

9. Traverse the right subtree of N (R).

10. Process the root node (N).

Program

#include <stdio.h>
#include <stdlib.h>

struct node {

int data;

struct node* left;

struct node* right;

};

void inorder(struct node* root){

if(root == NULL) return;

inorder(root->left);

printf("%d ->", root->data);

inorder(root->right);

void preorder(struct node* root){

if(root == NULL) return;

printf("%d ->", root->data);

preorder(root->left);

preorder(root->right);

void postorder(struct node* root) {

if(root == NULL) return;

postorder(root->left);

postorder(root->right);

printf("%d ->", root->data);

struct node* createNode(value){

struct node* newNode = malloc(sizeof(struct node));

newNode->data = value;

newNode->left = NULL;
newNode->right = NULL;

return newNode;

struct node* insertLeft(struct node *root, int value) {

root->left = createNode(value);

return root->left;

struct node* insertRight(struct node *root, int value){

root->right = createNode(value);

return root->right;

int main(){

struct node* root = createNode(1);

insertLeft(root, 12);

insertRight(root, 9);

insertLeft(root->left, 5);

insertRight(root->left, 6);

printf("Inorder traversal \n");

inorder(root);

printf("\nPreorder traversal \n");

preorder(root);

printf("\nPostorder traversal \n");

postorder(root);

Sample Input /Output:


Inorder traversal
5 ->12 ->6 ->1 ->9 ->
Preorder traversal
1 ->12 ->5 ->6 ->9 ->

Postorder traversal
5 ->6 ->12 ->9 ->1 ->

Result

Thus the program for performing binary tree traversal is executed successfully.
IMPLEMENTATION OF AVL TREES

Ex.No.7c Date:

Aim

To write a C program to implement AVL trees.

Algorithm

1. Start the program

2 .Declare all the variables that are used for tree

3.The height of the two child subtree of any node differ by at most one.

4.If they differ by more than one, re-balancing is done

5.Step 3 and Step 4 is the property of tree

6.Stop the program

Program

#include<stdio.h>

typedef struct node

int data;

struct node *left,*right;

int ht;

}node;

node *insert(node *,int);

node *Delete(node *,int);

void preorder(node *);

void inorder(node *);

int height( node *);


node *rotateright(node *);

node *rotateleft(node *);

node *RR(node *);

node *LL(node *);

node *LR(node *);

node *RL(node *);

int BF(node *);

int main()

node *root=NULL;

int x,n,i,op;

do

printf("\n1)Create:");

printf("\n2)Insert:");

printf("\n3)Delete:");

printf("\n4)Print:");

printf("\n5)Quit:");

printf("\n\nEnter Your Choice:");

scanf("%d",&op);

switch(op)

case 1: printf("\nEnter no. of elements:");

scanf("%d",&n);

printf("\nEnter tree data:");

root=NULL;

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

{
scanf("%d",&x);

root=insert(root,x);

break;

case 2: printf("\nEnter a data:");

scanf("%d",&x);

root=insert(root,x);

break;

case 3: printf("\nEnter a data:");

scanf("%d",&x);

root=Delete(root,x);

break;

case 4: printf("\nPreorder sequence:\n");

preorder(root);

printf("\n\nInorder sequence:\n");

inorder(root);

printf("\n");

break;

}while(op!=5);

return 0;

node * insert(node *T,int x)

if(T==NULL)

T=(node*)malloc(sizeof(node));

T->data=x;
T->left=NULL;

T->right=NULL;

else

if(x > T->data) // insert in right subtree

T->right=insert(T->right,x);

if(BF(T)==-2)

if(x>T->right->data)

T=RR(T);

else

T=RL(T);

else

if(x<T->data)

T->left=insert(T->left,x);

if(BF(T)==2)

if(x < T->left->data)

T=LL(T);

else

T=LR(T);

T->ht=height(T);

return(T);

node * Delete(node *T,int x)

{
node *p;

if(T==NULL)

return NULL;

else

if(x > T->data) // insert in right subtree

T->right=Delete(T->right,x);

if(BF(T)==2)

if(BF(T->left)>=0)

T=LL(T);

else

T=LR(T);

else

if(x<T->data)

T->left=Delete(T->left,x);

if(BF(T)==-2) //Rebalance during windup

if(BF(T->right)<=0)

T=RR(T);

else

T=RL(T);

else

//data to be deleted is found


if(T->right!=NULL)

{ //delete its inorder succesor

p=T->right;

while(p->left!= NULL)

p=p->left;

T->data=p->data;

T->right=Delete(T->right,p->data);

if(BF(T)==2)//Rebalance during windup

if(BF(T->left)>=0)

T=LL(T);

else

T=LR(T);\

else

return(T->left);

T->ht=height(T);

return(T);

int height(node *T)

int lh,rh;

if(T==NULL)

return(0);

if(T->left==NULL)

lh=0;

else

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

rh=0;

else

rh=1+T->right->ht;

if(lh>rh)

return(lh);

return(rh);

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

int BF(node *T)

int lh,rh;

if(T==NULL)

return(0);
if(T->left==NULL)

lh=0;

else

lh=1+T->left->ht;

if(T->right==NULL)

rh=0;

else

rh=1+T->right->ht;

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
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 C program for the concept of AVL trees was implemented successfully.
IMPLEMENTATION OF BREADTH FIRST SEARCH

Ex.No.8a Date:

Aim

To write a c program for implementation of breadth first search.

Algorithm

1.Start by putting any one of the graph's vertices at the back of a queue.
2.Take the front item of the queue and add it to the visited list.
3.Create a list of that vertex's adjacent nodes. , add the ones which are not in the visited list to
the back of the queue.
4.Keep repeating steps 2 and 3 until the queue to empty.

Program

#include <stdio.h>

#include <stdlib.h>

#define SIZE 40

struct queue

int items[SIZE];

int front;

int rear;

};

struct queue* createQueue();

void enqueue(struct queue* q, int);

int dequeue(struct queue* q);

void display(struct queue* q);

int isEmpty(struct queue* q);

void printQueue(struct queue* q);


struct node

int vertex;

struct node* next;

};

struct node* createNode(int);

struct Graph

int numVertices;

struct node** adjLists;

int* visited;

};

void bfs(struct Graph* graph, int startVertex)

struct queue* q = createQueue();

graph->visited[startVertex] = 1;

enqueue(q, startVertex);

while (!isEmpty(q))

printQueue(q);

int currentVertex = dequeue(q);

printf("Visited %d\n", currentVertex);

struct node* temp = graph->adjLists[currentVertex];

while (temp)

int adjVertex = temp->vertex;

if (graph->visited[adjVertex] == 0)

{
graph->visited[adjVertex] = 1;

enqueue(q, adjVertex);

temp = temp->next;

struct node* createNode(int v)

struct node* newNode = malloc(sizeof(struct node));

newNode->vertex = v;

newNode->next = NULL;

return newNode;

struct Graph* createGraph(int vertices)

struct Graph* graph = malloc(sizeof(struct Graph));

graph->numVertices = vertices;

graph->adjLists = malloc(vertices * sizeof(struct node*));

graph->visited = malloc(vertices * sizeof(int));

int i;

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

graph->adjLists[i] = NULL;

graph->visited[i] = 0;

return graph;

}
void addEdge(struct Graph* graph, int src, int dest)

struct node* newNode = createNode(dest);

newNode->next = graph->adjLists[src];

graph->adjLists[src] = newNode;

newNode = createNode(src);

newNode->next = graph->adjLists[dest];

graph->adjLists[dest] = newNode;

struct queue* createQueue()

struct queue* q = malloc(sizeof(struct queue));

q->front = -1;

q->rear = -1;

return q;

int isEmpty(struct queue* q)

if (q->rear == -1)

return 1;

else

return 0;

void enqueue(struct queue* q, int value)

if (q->rear == SIZE - 1)

printf("\nQueue is Full!!");

else
{

if (q->front == -1)

q->front = 0;

q->rear++;

q->items[q->rear] = value;

int dequeue(struct queue* q)

int item;

if (isEmpty(q))

printf("Queue is empty");

item = -1;

else

item = q->items[q->front];

q->front++;

if (q->front > q->rear)

printf("Resetting queue ");

q->front = q->rear = -1;

return item;

void printQueue(struct queue* q)


{

int i = q->front;

if (isEmpty(q))

printf("Queue is empty");

else

printf("\nQueue contains \n");

for (i = q->front; i < q->rear + 1; i++)

printf("%d ", q->items[i]);

int main()

struct Graph* graph = createGraph(6);

addEdge(graph, 0, 1);

addEdge(graph, 0, 2);

addEdge(graph, 1, 2);

addEdge(graph, 1, 4);

addEdge(graph, 1, 3);

addEdge(graph, 2, 4);

addEdge(graph, 3, 4);

bfs(graph, 0);

return 0;

}
OUTPUT:

Queue contains

0 Resetting queue Visited 0

Queue contains

2 1 Visited 2

Queue contains

1 4 Visited 1

Queue contains

4 3 Visited 4

Queue contains

3 Resetting queue Visited 3

Result

Thus the Breadth First Search search has been implemented successfully.
IMPLEMENTATION OF DEPTH FIRST SEARCH

Ex.No.8b Date:

Aim

To write a c program for implementation of breadth first search.

Algorithm

1.Start by putting any one of the graph's vertices on top of a stack.


2.Take the top item of the stack and add it to the visited list.
3.Create a list of that vertex's adjacent nodes.
4.Keep repeating steps 2 and 3 until the stack is empty.

#include <stdio.h>

#include <stdlib.h>

struct node

int vertex;

struct node* next;

};

struct node* createNode(int v);

struct Graph

int numVertices;

int* visited;

struct node** adjLists;

};

void DFS(struct Graph* graph, int vertex)

{
struct node* adjList = graph->adjLists[vertex];

struct node* temp = adjList;

graph->visited[vertex] = 1;

printf("Visited %d \n", vertex);

while (temp != NULL)

int connectedVertex = temp->vertex;

if (graph->visited[connectedVertex] == 0)

DFS(graph, connectedVertex);

temp = temp->next;

struct node* createNode(int v)

struct node* newNode = malloc(sizeof(struct node));

newNode->vertex = v;

newNode->next = NULL;

return newNode;

struct Graph* createGraph(int vertices)

struct Graph* graph = malloc(sizeof(struct Graph));

graph->numVertices = vertices;

graph->adjLists = malloc(vertices * sizeof(struct node*));

graph->visited = malloc(vertices * sizeof(int));

int i;

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

{
graph->adjLists[i] = NULL;

graph->visited[i] = 0;

return graph;

void addEdge(struct Graph* graph, int src, int dest)

struct node* newNode = createNode(dest);

newNode->next = graph->adjLists[src];

graph->adjLists[src] = newNode;

newNode = createNode(src);

newNode->next = graph->adjLists[dest];

graph->adjLists[dest] = newNode;

void printGraph(struct Graph* graph)

int v;

for (v = 0; v < graph->numVertices; v++)

struct node* temp = graph->adjLists[v];

printf("\n Adjacency list of vertex %d\n ", v);

while (temp)

printf("%d -> ", temp->vertex);

temp = temp->next;

printf("\n");

}
}

int main()

struct Graph* graph = createGraph(4);

addEdge(graph, 0, 1);

addEdge(graph, 0, 2);

addEdge(graph, 1, 2);

addEdge(graph, 2, 3);

printGraph(graph);

DFS(graph, 2);

return 0;

OUTPUT:

Adjacency list of vertex 0

2 -> 1 ->

Adjacency list of vertex 1

2 -> 0 ->

Adjacency list of vertex 2

3 -> 1 -> 0 ->

Adjacency list of vertex 3

2 ->

Visited 2

Visited 3

Visited 1

Visited 0

Result

Thus the Depth First Search search has been implemented successfully.
IMPLEMENTATION OF LINEAR SEARCH
Ex.No.9a Date:

Aim

To write a C program to perform Linear Search Operation.

Algorithm

1. Start the program.

2. Read the search element from the user.

3. Compare, the search element with the first element in the list.

4. If both are matching, then display "Given element found!!!" and terminate the function.

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

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

7. 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 array[10];
int i, num, keynum, found = 0;

printf("Enter the value of num \n");


scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is \n");
for (i = 0; i < num; i++)
{
printf("%dn", array[i]);
}
printf("Enter the element to be searched \n");
scanf("%d", &keynum);
/* Linear search begins */
for (i = 0; i < num ; i++)
{
if (keynum == array[i] )
{
found = 1;
break;
}
}
if (found == 1)
printf("Element is present in the array\n");
else
printf("Element is not present in the array\n");
}
Output:

Enter the value of num


5
Enter the elements one by one
456
78
90

40
100
Input array is
456
78
90
40
100
Enter the element to be searched
70
Element is not present in the array

Result:

Thus the program to perform Linear search operation is executed successfully.


IMPLEMENTATION OF BINARY SEARCH
Ex.No.9b Date:

Aim
To write a C program to perform Binary Search Operation.

Algorithm
1. Start the program.

2. Read the search element from the user

3. Find the middle element in the sorted list

4. Compare, the search element with the middle element in the sorted list.

5. If both are matching, then display "Given element found!!!" and terminate the function

6. If both are not matching, then check whether the search element is smaller or
larger than middle element.

7. If the search element is smaller than middle element, then repeat steps 2, 3, 4
and 5 for the left sublist of the middle element.

8. If the search element is larger than middle element, then repeat steps 2, 3, 4 and
5 for the right sublist of the middle element.

9. Repeat the same process until we find the search element in the list or until
sublist contains only one element.

10. If that element also doesn't match with the search element, then display
"Element not found in the list!!!" and terminate the function.

11. Stop the process.


Program

#include <stdio.h>

int main()

{
int c, n, first, last, mid, search, a[250];
printf("Please enter number of elements\n");
scanf("%d",&n);
printf("Enter the elements one by one\n", n);
for ( c = 0 ; c < n ; c++ )
{
scanf("%d",&a[c]);
}
printf("Enter the element to be searched\n");
scanf("%d",&search);
first = 0;
last = n - 1;
mid = (first+last)/2;
while( first <= last )
{
if ( a[mid] < search )

first = mid + 1;

}
else if ( a[mid] == search )

{
printf("%d is found at the location %d.\n", search, mid+1);

break;
}
else

{
last = mid - 1;
}
mid = (first + last)/2; }

if ( first > last )


printf("Element %d is not found in the list\n", search);
return 0;}

Output:

Please enter number of elements


3

Enter the elements one by one


5
3
8

Enter the element to be searched

3 is found at the location 2.

Result :
Thus the program to perform binary search operation is executed successfully.
IMPLEMENTATION OF INSERTION SORT
Ex.No.10a Date:

Aim

To write a C program to perform Insertion Sorting.

Algorithm

1. Start the program.

2. Assume that first element in the list is in sorted portion of the list and remaining
all elements are in unsorted portion.
3. Consider first element from the unsorted list and insert that element into the
sorted list in order specified.
4. Repeat the above process until all the elements from the unsorted list are moved into the
sorted list.

5. Stop the process

Program

#include<stdio.h>
int main()
{
int data[100],n,temp,i,j;
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
for(i=1;i<n;i++)
{
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
/*To sort elements in descending order, change temp<data[j] to temp>data[j] in above line.*/
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",data[i]);
return 0;
}

Output:
Enter number of terms(should be less than 100): 5

Enter elements: 12
1
2
5
3
In ascending order: 1 2 3 5 12

Result :
Thus the program to perform insertion sort is executed successfully.
IMPLEMENTATION OF QUICK SORT
Ex.No.10b Date:

Aim

To write a C program to perform Quick Sort for given ‘n’ elements.

Algorithm

1. Start the program.

2. 1. If n < = 1, then return.

3. Pick any element V in a[]. This is called the pivot.

4. Rearrange elements of the array by moving all elements xi > V right of V and
all elements xi < = V left of V. If the place of the V after re-arrangement is j, all
elements with value less than V, appear in a[0], a[1] . . . . a[j – 1] and all those
with value greater than V appear in a[j + 1] . . . . a[n – 1].

5. Apply quick sort recursively to a[0] . . . . a[j – 1] and to a[j + 1] . . . . a[n – 1].

6. Stop the program.


Program

#include <stdio.h>
#define MAX 10
void swap(int *m,int *n)
{
int temp;
temp = *m;
*m = *n;
*n = temp;
}
int get_key_position(int x,int y )
{
return((x+y) /2);
}
// Function for Quick Sort
void quicksort(int list[],int m,int n)
{
int key,i,j,k;
if( m < n)
{
k = get_key_position(m,n);
swap(&list[m],&list[k]);
key = list[m];
i = m+1;
j = n;
while(i <= j)
{
while((i <= n) && (list[i] <= key))
i++;
while((j >= m) && (list[j] > key))
j--;
if( i < j)
swap(&list[i],&list[j]);
}
swap(&list[m],&list[j]);
quicksort(list,m,j-1);
quicksort(list,j+1,n);
}
}
// Function to read the data
void read_data(int list[],int n)
{
int j;
printf("\n\nEnter the elements:\n");
for(j=0;j<n;j++)
scanf("%d",&list[j]);
}
// Function to print the data
void print_data(int list[],int n)
{
int j;
for(j=0;j<n;j++)
printf("%d\t",list[j]);
}
main()
{
int list[MAX], num;
//clrscr();
printf("\n***** Enter the number of elements Maximum [10] *****\n");
scanf("%d",&num);
read_data(list,num);
printf("\n\nElements in the list before sorting are:\n");
print_data(list,num);
quicksort(list,0,num-1);
printf("\n\nElements in the list after sorting are:\n");
print_data(list,num);
//getch();
}

Output:

Enter the number of elements Maximum [10]

Enter the elements:

56

26

16

66

06

36

Elements in the list before sorting are:

56 26 16 66 6 36

Elements in the list after sorting are:

6 16 26 36 56 66

Result
Thus the program to perform Quick sort is executed successfully.
IMPLEMENTATION OF HEAP SORT

Ex.No.10c Date:

Aim

1. Construct a Binary Tree with given list of Elements.

2. Transform the Binary Tree into Min Heap.

3. Delete the root element from Min Heap using Heapify method.

4.Put the deleted element into the Sorted list.

5.Repeat the same until Min Heap becomes empty.

6.Display the sorted list.

Program

#include <stdio.h>

void swap(int* a, int* b)

int temp = *a;

*a = *b;

*b = temp;

void heapify(int arr[], int n, int i)

int left, right, largest;


largest = i;

left = 2 * i + 1;

right = 2 * i + 2;

// Check if left child exists and is larger than its parent

if (left < n && arr[left] > arr[largest])

largest = left;

// Check if right child exists and larger than its parent

if (right < n && arr[right] > arr[largest])

largest = right;

// if root is not the largest

if (largest != i) {

swap(&arr[i], &arr[largest]); //make root the largest

heapify(arr, n, largest); // Apply heapify to the largest node

void heap_sort(int arr[], int n)

int i;

for (i = (n / 2) - 1; i >= 0; i--)

heapify(arr, n, i);
for (i = n - 1; i >= 0; i--) {

swap(&arr[0], &arr[i]); //Move the largest element at root to the end

heapify(arr, i, 0); //Apply heapify to reduced heap

int main()

int arr[] = { 20, 13, 34, 56, 12, 10 };

int n = sizeof(arr) / sizeof(arr[0]);

printf("Array:\n");

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

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

heap_sort(arr, n);

printf("\nAfter performing Heap Sort:\n");

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

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

return 0;
}

Output

Array:

20 13 34 56 12 10

After performing heap sort:

10 12 13 20 34 56

Result

Thus the Heap sort has been implemented successfully.

You might also like