0% found this document useful (0 votes)
3 views

CS3311 Data Structures Lab

Uploaded by

Aishwaya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CS3311 Data Structures Lab

Uploaded by

Aishwaya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

AISHWARYA

COLLEGE OF ENGINEERING AND TECHNOLOGY

RECORD NOTE BOOK

Name :

Reg no :

Department :

Subject :
AISHWARYA
COLLEGE OF ENGINEERING AND TECHNOLOGY
ANTHIYUR

Department……………………………………………………………………………………………………....

………………………………………………………………………………………………………………..Record

Name:………………………………………. Dept:……………………………………………..

Register no:………………………………. Year / Sem: .…………………………………..

Certified that this is bonafide record of work done by the above student of the

………………………………………………………………………………………………………..laboratory

During the year 20 - 20

Signature of Lab-in-charge Signature of Head of the Department

Submitted for the Practical Examination

Held on……………………………………………...

Internal Examiner External examiner


S.No Date Experiment Name Marks Sign
S.No Date Experiment Name Marks Sign
lOMoARcPSD|214 839 54

Ex: No: ARRAY IMPLEMENTATION OF LIST ADT


Date:

AIM
To implement the List ADT using arrays.
ALGORITHM
Step 1: Start.
Step 2: Declare the necessary functions for implementation.
Step 3: Get the input from the user and store it an array.
Step 4: In Insertion, half of the elements to be shifted upwards and in deletion half of
the elements to be shifted downwards.
Step 5: Display the output using an array.
Step 6: Stop.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 50
int arr[MAX_SIZE];
int size = 0;
void display(){
int i;
for(i=0;i<size;i++)
printf("%d\t",arr[i]);
}
void insertAtPos(int pos,int val){
int i;
for(i=size-1;i>=pos;i--){
arr[i+1]=arr[i];
}
arr[pos]= val;
lOMoARcPSD|214 839 54

size++;
printf("Inserted %d at pos %d",val,pos);
}
void deleteFromBeginning(){
int i;
int del=arr[0];
for(i=0;i<size;i++){
arr[i]=arr[i+1];
}
size--;
printf("Deleted %d from the beginning ",del);
}
void deleteFromPos(int pos){
int i;
int del = arr[pos];
for(i=pos;i<size;i++){
arr[i] = arr[i+1];
}
size--;
printf("Deleted %d at pos %d",del,pos);
}
void deleteEnd(){
int del=arr[size];
size--;
printf("Deleted %d from the end ",del);
}
int searchElement(int val){
int i,found=1;
for(i=0;i<size;i++){
if(val==arr[i]){
lOMoARcPSD|214 839 54

printf("Element found at %d ",i);


found=0;
}
}
return found;
}
int main(){
int choice,val,pos;
printf("\n -------- List Menu ----------- \n");
printf("1.Insert at end \n");
printf("2.Insert at specified pos \n");
printf("3.Delete at specified pos \n");
printf("4.Display\n");
printf("5.Read data from particular position \n");
printf("6.Update a value at specified position \n");
printf("7.Length of the array \n");
printf("8.Search a data \n");
printf("9.Insert at beginning \n");
printf("10.Delete at end \n");
printf("11.Delete from beginning \n");
printf("12.Exit\n");
printf("\n \n");
while(1){
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: if(size == MAX_SIZE){
printf("Array is full");
break;
}
lOMoARcPSD|214 839 54

printf("Enter the data: ");


scanf("%d",&val);
arr[size++] = val;
break;
case 2: if(size == MAX_SIZE){
printf("Array is full");
break;
}
printf("Enter the pos *pos starts at 0*: ");
scanf("%d",&pos);
if(pos<0 || pos>=size)
{
printf("Invalid position");
break;
}
printf("Enter the data: ");
scanf("%d",&val);
insertAtPos(pos,val);
break;
case 3: if(size==0){
printf("Array is empty");
break;
}
printf("Enter the pos: ");
scanf("%d",&pos);
if(pos<0 || pos>=size)
printf("Invalid position");
else
deleteFromPos(pos);
break;
lOMoARcPSD|214 839 54

case 4: display();
break;
case 5: printf("Enter a position to view its value : ");
scanf("%d",&pos);
if(pos<0 || pos >size){
printf("Invalid operation");
break;
}
printf("Value at position %d is %d",pos,arr[pos]);
break;
case 6: printf("Enter a position to update : ");
scanf("%d",&pos);
if(pos<0 || pos>size){
printf("Invalid operation");
break;
}
printf("Enter the data : ");
scanf("%d",&val);
arr[pos]=val;
break;
case 7: if(size==0){
printf("Array is empty");
break;
}
printf("Length of the list : ",size);
break;
case 8: printf("Enter a data to search : ");
scanf("%d",&val);
if(size==0){
lOMoARcPSD|214 839 54

printf("Invalid operation : Array is empty");


break;
}
int search=searchElement(val);
if(search==1){
printf("Element not found ");
break;
}
break;
case 9: printf("Enter a data to insert at beginning : ");
scanf("%d",&val);
if(size== MAX_SIZE){
printf("Array is full");
break;
}
pos=0;
insertAtPos(pos,val);
break;
case 10: if(size==0){
printf("Array is empty");
break;
}
deleteEnd();
break;
case 11: if(size==0){
printf("Array is empty ");
break;
}
deleteFromBeginning();
break;
lOMoARcPSD|214 839 54

case 12 : exit(0);
default: printf("Wrong choice");
break;
}
}
return 0;
}
OUTPUT

RESULT
Thus, a C program of list ADT using arrays was implemented successfully.
lOMoARcPSD|214 839 54

Ex: No: IMPLEMENTATION OF STACK USING ARRAY


Date:

AIM
To write a C program to implement Stack operations array.
ALGORITHM
Step 1: Start.
Step 2: Initially top = -1;
Step 3: push operation increases top by one and writes pushed element to stack.
Step 4: pop operation checks that top is not equal to -1 and decreases it by 1.
Step 5: display operation checks that top is not equal to -1 and prints the stack.
Step 6: Stop.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT");
while(1)
{
printf("\nEnter the Choice:");
scanf("%d",&choice);
switch(choice)
lOMoARcPSD|214 839 54

{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\nSTACK is over flow");
}
else
{
printf("Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
lOMoARcPSD|214 839 54

10

}
}
void pop()
{
if(top<=-1)
{
printf("\nStack is under flow");
}
else
{
printf("\nThe popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\nThe elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
}
else
{
printf("\nThe STACK is empty");
}
}
lOMoARcPSD|214 839 54

11

OUTPUT

RESULT
Thus, a C program for Stack using array was implemented successfully.
lOMoARcPSD|214 839 54

12

Ex. No: IMPLEMENTATION OF QUEUE USING ARRAY


Date:

AIM
To write a C program to implement Queue operations using array.
ALGORITHM
Step 1: Start.
Step 2: Initialize front=0; rear=-1.
Step 3: Enqueue operation inserts element at the rear.
Step 4: Dequeue operation deletes a element at the front of the list.
Step 5: Display operation displays all the element in the list.
Step 6: Stop.
PROGRAM
#include <stdio.h>
#include<stdlib.h>
#define MAX 50
void insert();
void Delete();
void display();
int queueArray[MAX];
int rear = - 1;
int front = - 1;
int main(void)
{
int choice;
printf("1.Insert\n2.Delete\n3.Display \n4.Quit\n");
while (1)
{
printf("\nEnter your choice : ");
scanf("%d", &choice);
lOMoARcPSD|214 839 54

13

switch (choice)
{
case 1:
insert();
break;
case 2:
Delete();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Enter a valid choice...\n");
}
}
}
void insert()
{
int item;
if (rear == MAX - 1)
printf("Queue Overflow");
else
{
if (front == - 1)
front = 0;
printf("Enter a value : ");
scanf("%d", &item);
rear = rear + 1;
lOMoARcPSD|214 839 54

14

queueArray[rear] = item;
}
}
void Delete()
{
if (front == - 1 || front > rear)
{
printf("Underflow");
return ;
}
else
{
printf("Deleted element : %d", queueArray[front]);
front = front + 1;
}
}
void display()
{
int i;
if (front == - 1)
printf("Queue empty ");
else
{
printf("Queue is...\n");
for (i = front; i <= rear; i++)
printf("%d\t", queueArray[i]);
printf("\n");
}
}
lOMoARcPSD|214 839 54

15

OUTPUT

RESULT
Thus, a C program for Queue using array was implemented successfully.
lOMoARcPSD|214 839 54

16

Ex. No: IMPLEMENTATION OF CIRCULAR QUEUE USING ARRAY


Date:

AIM
To implement circular queue using array.
ALGORITHM
Step 1: Start
Step 2: Define all the required functions necessary for queue operation
Step 3: Implement circular queue concept
Step 4: Use enqueue to insert few elements into the queue
Step 5: Use dequeue to delete an element and print the queue
Step 6: Stop
PROGRAM
#include <stdio.h>
#define SIZE 5
int items[SIZE];
int front = -1, rear = -1;
int isFull() {
if ((front == rear + 1) || (front == 0 && rear == SIZE - 1)) return 1;
return 0;
}
int isEmpty() {
if (front == -1) return 1;
return 0;
}
void enQueue(int element) {
if (isFull())
printf("\n Queue is full!! \n");
else {
if (front == -1) front = 0;
lOMoARcPSD|214 839 54

17

rear = (rear + 1) % SIZE;


items[rear] = element;
printf("\n Inserted -> %d", element);
}
}
int deQueue() {
int element;
if (isEmpty()) {
printf("\n Queue is empty !! \n");
return (-1);
}
else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
else {
front = (front + 1) % SIZE;
}
printf("\n Deleted element -> %d \n", element);
return (element);
}
}
void display() {
int i;
if (isEmpty())
printf(" \n Empty Queue\n");
else {
printf("\n Front -> %d ", front);
lOMoARcPSD|214 839 54

18

printf("\n Items -> ");


for (i = front; i != rear; i = (i + 1) % SIZE) {
printf("%d ", items[i]);
}
printf("%d ", items[i]);
printf("\n Rear -> %d \n", rear);
}
}
int main() {
// Fails because front = -1
deQueue();

enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);

// Fails to enqueue because front == 0 && rear == SIZE - 1


enQueue(6);

display();
deQueue();

display();

enQueue(7);
display();

// Fails to enqueue because front == rear + 1


lOMoARcPSD|214 839 54

19

enQueue(8);
return 0;
}

OUTPUT

RESULT
Thus, a C program for circular queue has been executed successfully.
lOMoARcPSD|214 839 54

20

Ex. No: IMPLEMENTATION OF SINGLY LINKED LIST


Date:

AIM
To write a C program to implement singly linked list.
ALGORITHM
Step 1: Start
Step 2: Declare all the functions beforehand.
Step 3: Create a node containing data and next pointer.
Step 4: Assign NULL to the head node.
Step 5: Define all the functions.
Step 6: Display the nodes’ data values.
Step 7: Stop.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *HEAD;

void insert_at_begin();
void insert_at_last();
void insert_random();
void delete_at_begin();
void delete_at_last();
void delete_random();
void print();
void main(){
lOMoARcPSD|214 839 54

21

int your_choice=0;
printf("1.Insertion at beginning \n2.Insertion at last\n3.Insertion at random \n4.Deletion
from the beginning \n5.Deletion at the last \n6.Deletion of a node after a specified
node\n7.Display\n8.Exit!\n");
while(your_choice != 8){
printf("Enter your choice: ");
scanf("%d",&your_choice);
switch(your_choice){
case 1:
insert_at_begin();
break;
case 2:
insert_at_last();
break;
case 3:
insert_random();
break;
case 4:
delete_at_begin();
break;
case 5:
delete_at_last();
break;
case 6:
delete_random();
break;
case 7:
print();
break;
case 8:
exit(0);
lOMoARcPSD|214 839 54

22

default:
printf("Enter a valid choice!");
}
}
}
void insert_at_begin(){
struct node *point;
int value;
point = (struct node *) malloc(sizeof(struct node *));
if(point == NULL)
{
printf("\nInvalid!!");
}
else
{
printf("Enter the value: ");
scanf("%d",&value);
point->data = value;
point->next = HEAD;
HEAD = point;
}
}
void insert_at_last(){
struct node *point,*tmp;
int value;
point = (struct node*)malloc(sizeof(struct node));
if(point == NULL)
{
printf("\nInvalid!!");
}
lOMoARcPSD|214 839 54

23

else
{
printf("Enter the value: ");
scanf("%d",&value);
point->data = value;
if(HEAD == NULL)
{
point -> next = NULL;
HEAD = point;
}
else
{
tmp = HEAD;
while (tmp -> next != NULL)
{
tmp = tmp -> next;
}
tmp->next = point;
point->next = NULL;
}
}
}
void insert_random(){
int a,pos,value;
struct node *point, *tmp;
point = (struct node *) malloc (sizeof(struct node));
if(point == NULL)
{
printf("\nInvalid!!");
}
lOMoARcPSD|214 839 54

24

else
{
printf("Enter the value of element: ");
scanf("%d",&value);
point->data = value;
printf("Enter the position where you want to insert: ");
scanf("%d",&pos);
tmp=HEAD;
for(a=0;a<pos;a++)
{
tmp = tmp->next;
if(tmp == NULL)
{
printf("\nSorry, but you cannot insert!\n");
return;
}
}
point ->next = tmp ->next;
tmp ->next = point;
}
}
void delete_at_begin(){
struct node *point;
if(HEAD == NULL)
{
printf("\nThe List is empty!\n");
}
else
{
point = HEAD;
lOMoARcPSD|214 839 54

25

HEAD = point->next;
free(point);
}
}
void delete_at_last(){
struct node *point,*point1;
if(HEAD == NULL)
{
printf("\nThe List is empty!");
}
else if(HEAD -> next == NULL)
{
HEAD = NULL;
free(HEAD);
}
else
{
point = HEAD;
while(point->next != NULL)
{
point1 = point;
point = point ->next;
}
point1->next = NULL;
free(point);
}
}
void delete_random(){
struct node *point,*point1;
int pos,a;
lOMoARcPSD|214 839 54

26

printf("Enter the position of the node after which you want to delete: ");
scanf("%d",&pos);
point=HEAD;
for(a=0;a<pos;a++)
{
point1 = point;
point = point->next;

if(point == NULL)
{
printf("\nSorry, but you cannot delete!");
return;
}
}
point1 ->next = point ->next;
free(point);
printf("\nThe Node is deleted at location: %d",pos+1);
}
void print(){
struct node *point;
point = HEAD;
if(point == NULL)
{
printf("Please enter something to print!");
}
else
{
printf("Printing the values...\n");
while (point!=NULL)
{
lOMoARcPSD|214 839 54

27

printf("%d ",point->data);
point = point -> next;
}
printf("\n");
}
}
OUTPUT

RESULT
Thus, a C program for Singly Linked List was implemented successfully.
lOMoARcPSD|214 839 54

28

Ex No: IMPLEMENTATION OF DOUBLY LINKED LIST


Date:

AIM
To write a C program to implement doubly linked list.
ALGORITHM
Step 1: Start
Step 2: Declare all required functions.
Step 3: Create a node containing data and two pointers (next and prev).
Step 4: Define all the functions.
Step 5: Display all nodes’ data values.
Step 6: Stop.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *prev;
struct node *next;
int data;
};
struct node *head;
void insertion_beginning();
void insertion_last();
void insertion_specified();
void deletion_beginning();
void deletion_last();
void deletion_specified();
void display();
void search();
lOMoARcPSD|214 839 54

29

void main ()
{
int choice =0;
printf("1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete from
beginning\n5.Delete from last\n6.Delete the node after the given data\n7.Show\n8.Exit\n");
while(choice != 9)
{
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
insertion_beginning();
break;
case 2:
insertion_last();
break;
case 3:
insertion_specified();
break;
case 4:
deletion_beginning();
break;
case 5:
deletion_last();
break;
case 6:
deletion_specified();
break;
case 7:
lOMoARcPSD|214 839 54

30

display();
break;
case 8:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void insertion_beginning()
{
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("Enter Item value: ");
scanf("%d",&item);

if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
lOMoARcPSD|214 839 54

31

}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
}
}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("Enter value: ");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
lOMoARcPSD|214 839 54

32

}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}

}
}
void insertion_specified()
{
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
temp=head;
printf("Enter the location: ");
scanf("%d",&loc);
for(i=0;i<loc;i++)
lOMoARcPSD|214 839 54

33

{
temp = temp->next;
if(temp == NULL)
{
printf("There are less than %d elements\n", loc);
return;
}
}
printf("Enter value: ");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
}
}
void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
}
else
lOMoARcPSD|214 839 54

34

{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
}
}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
}
}
lOMoARcPSD|214 839 54

35

void deletion_specified()
{
struct node *ptr, *temp;
int val;
printf("Enter the data after which the node is to be deleted: ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
}
}
void display(){
struct node *ptr;
printf("\nPrinting values...\n");
ptr = head;
while(ptr != NULL){
lOMoARcPSD|214 839 54

36

printf("%d\t",ptr->data);
ptr=ptr->next;
}
printf("\n");
}
OUTPUT

RESULT
Thus, a C program for doubly linked list has been executed successfully.
lOMoARcPSD|214 839 54

37

Ex. No: IMPLEMENTATION OF STACK USING LINKED LIST


Date:

AIM
To write a C program to implement Stack operations using linked list.
ALGORITHM
Step 1: Start.
Step 2: push operation inserts an element at the front.
Step 4: pop operation deletes an element at the front of the list.
Step 5: display operation displays all the elements in the list.
Step 6: Stop.
PROGRAM
#include <stdio.h>
#include <stdlib.h>
struct lnode
{
int data;
struct lnode *next;
};
typedef struct lnode node;
node* top = NULL;
void push(int value)
{
node *newNode;
newNode = (node*)malloc(sizeof(node));
newNode->data = value;
if (top == NULL)
{
newNode->next = NULL;
}
lOMoARcPSD|214 839 54

38

else
{
newNode->next = top;
}
top = newNode;
}
int pop()
{
if (top == NULL)
{
printf("\nStack Underflow\n");
}
else
{
node *temp = top;
int temp_data = top->data;
top = top->next;
free(temp);
return temp_data;
}
}
void display()
{
if (top == NULL)
{
printf("\nStack Underflow\n");
}
else
{
printf("The stack is \n");
lOMoARcPSD|214 839 54

39

node *temp = top;


while (temp->next != NULL)
{
printf("%d--->", temp->data);
temp = temp->next;
}
printf("%d--->NULL\n\n", temp->data);
}
}
int main()
{
int choice, value;
printf("1.Push\n2.Pop\n3.Display\n4.Exit\n");
while (1)
{
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("\nEnter the value : ");
scanf("%d", &value);
push(value);
break;
case 2:
printf("Popped element :%d\n", pop());
break;
case 3:
display();
break;
lOMoARcPSD|214 839 54

40

case 4:
exit(0);
default:
printf("\nEnter a valid choice..\n");
}
}
}
OUTPUT

RESULT
Thus, a C program for Stack using linked list was implemented successfully.
lOMoARcPSD|214 839 54

41

Ex. No: IMPLEMENTATION OF QUEUE USING LINKED LIST


Date:

AIM
To write a C program to implement Queue operations using linked list.
ALGORITHM
Step 1: Start.
Step 2: enqueue operation inserts an element at the rear of the list.
Step 3: dequeue operation deletes an element at the front of the list.
Step 4: display operation displays all the element in the list.
Step 5: Stop.
PROGRAM
#include <stdio.h>
#include <stdlib.h>
struct lnode {
int data;
struct lnode *next;
};
struct lnode *front = NULL;
struct lnode *rear = NULL;
typedef struct lnode node;
void enqueue(int value) {
node *ptr;
ptr = (node *)malloc(sizeof(node));
ptr->data = value;
ptr->next = NULL;
if ((front == NULL) && (rear == NULL)) {
front = rear = ptr;
} else {
rear->next = ptr;
lOMoARcPSD|214 839 54

42

rear = ptr;
}
}
int dequeue() {
if (front == NULL) {
printf("\nUnderflow\n");
return -1;
} else {
node *temp = front;
int temp_data = front->data;
front = front->next;
free(temp);
return temp_data;
}
}
void display() {
node *temp;
if ((front == NULL) && (rear == NULL)) {
printf("\nQueue is Empty\n");
} else {
printf("The queue is \n");
temp = front;
while (temp) {
printf("%d--->", temp->data);
temp = temp->next;
}
printf("NULL\n\n");
}
}
int main() {
lOMoARcPSD|214 839 54

43

int choice, value;


printf("1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");
while (1) {
printf("\nEnter your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter the value : ");
scanf("%d", &value);
enqueue(value);
break;
case 2:
printf("Popped element :%d\n", dequeue());
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\nEnter a valid choice..\n");
}
}
return 0;
}
lOMoARcPSD|214 839 54

44

OUTPUT

RESULT
Thus, a C program for Queue using linked list was implemented successfully.
lOMoARcPSD|214 839 54

45

Ex. No: POLYNOMIAL MANIPULATION USING LINKED LIST-


Date: ADDITION

AIM
To implement polynomial addition in C program.

ALGORITHM
Step 1: Start.
Step 2: Get two polynomial equations from the user using linked lists.
Step 3: Addition can be done based on the power of the terms in those equations.
Step 4: Display the result on the screen.
Step 5: Stop.
PROGRAM
#include <stdio.h>
#include<stdlib.h>
struct Term{
int coeff;
int exp;
};
struct Poly{
int n;
struct Term *terms;
};
void create (struct Poly *p)
{
int i;
printf ("Enter Number of terms: ");
scanf ("%d", &p->n);
p->terms = (struct Term *) malloc (p->n * sizeof (struct Term));
printf ("Enter terms:\n");
lOMoARcPSD|214 839 54

46

for (i = 0; i < p->n; i++)


scanf ("%d%d", &p->terms[i].coeff, &p->terms[i].exp);
printf ("\n");
}
void display (struct Poly p)
{
int i;
for (i = 0; i < p.n; i++)
{
printf ("%dx^%d", p.terms[i].coeff, p.terms[i].exp);
if (i + 1 < p.n)
printf (" + ");
}
printf ("\n");
}
struct Poly *add (struct Poly *p1, struct Poly *p2)
{
int i, j, k;
struct Poly *sum;

sum = (struct Poly *) malloc (sizeof (struct Poly));


sum->terms = (struct Term *) malloc ((p1->n + p2->n) * sizeof (struct Term));

i = j = k = 0;

while (i < p1->n && j < p2->n)


{
if (p1->terms[i].exp > p2->terms[j].exp)
sum->terms[k++] = p1->terms[i++];
lOMoARcPSD|214 839 54

47

else if (p1->terms[i].exp < p2->terms[j].exp)


sum->terms[k++] = p2->terms[j++];
else
{
sum->terms[k].exp = p1->terms[i].exp;
sum->terms[k++].coeff = p1->terms[i++].coeff + p2->terms[j++].coeff;
}
}

for (; i < p1->n; i++)


sum->terms[k++] = p1->terms[i];
for (; j < p2->n; j++)
sum->terms[k++] = p2->terms[j];

sum->n = k;
return sum;
}
int main()
{
struct Poly p1, p2, *p3;
printf ("Enter Polynomial 1:\n");
create (&p1);
printf ("Enter Polynomial 2:\n");
create (&p2);
p3 = add (&p1, &p2);
printf ("\n");
printf ("Polynomial 1 is: ");
display (p1);
printf ("\n");
lOMoARcPSD|214 839 54

48

printf ("Polynomial 2 is: ");


display (p2);
printf ("\n");
printf ("Polynomial 3 is: ");
display (*p3);
return 0;
}

OUTPUT

RESULT
Thus, polynomial addition using linked list has been implemented successfully.
lOMoARcPSD|214 839 54

49

Ex. No: INFIX TO POSTFIX EXPRESSION USING STACK


Date:

AIM
To implement the conversion of infix to postfix using stack.
ALGORITHM
Step 1: Start
Step 2: Scan the infix expression and repeat steps 3 to 6
Step 3: If an operand is encountered, add it to Y. (postfix expression)
Step 4: If a left parenthesis is encountered, push it onto Stack.
Step 5: If an operator is encountered, then:
Step 5.1: Repeatedly pop from Stack and add to Y each operator (on the top
of Stack) which has the same precedence as or higher precedence
than operator.
Step 5.2: Add operator to Stack.
[End of If]
Step 6: If a right parenthesis is encountered, then:
Step 6.1: Repeatedly pop from Stack and add to Y each operator (on the top of
Stack) until a left parenthesis is encountered.
Step 6.2: Remove the left Parenthesis.
[End of If]
[End of If]
Step 7: Stop
PROGRAM
#include<stdio.h>
#include<ctype.h>

char stack[100];
int top = -1;
lOMoARcPSD|214 839 54

50

void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
if(x == '^')
return 3;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
lOMoARcPSD|214 839 54

51

printf("Postfix expression is: ");


e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}
return 0;
}
lOMoARcPSD|214 839 54

52

OUTPUT

RESULT
Thus, the infix has been converted into postfix successfully.
lOMoARcPSD|214 839 54

53

Ex. No: EVALUATION OF POSTFIX EXPRESSION USING STACK


Date:

AIM
To write a C program to implement the evaluation of postfix expression using stack.
ALGORITHM
Step 1: Start
Step 2: Scan the postfix string from left to right
Step 3: Initialize an empty stack
Step 4: If the scanned character is operand, add it to stack. If it is an operator, there
will be atleast two operands in the stack.
Step 5: If the scanned is an operator, then we store the top most element of the stack
in a variable temp. Pop the stack. Now evaluate topStack(operator) temp.
Step 6: Return top element.
Step 7: Stop
PROGRAM
#include<stdio.h>
int stack[20];
int top = -1;

void push(int x)
{
stack[++top] = x;
}

int pop()
{
return stack[top--];
}

int main()
lOMoARcPSD|214 839 54

54

{
char exp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the expression : ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
lOMoARcPSD|214 839 54

55

case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nResult is %d \n",pop());
return 0;
}

OUTPUT

RESULT
Thus, the postfix expression has been evaluated successfully.
lOMoARcPSD|214 839 54

56

Ex.no: IMPLEMENTATION OF BINARY SEARCH TREE AND PERFORM


Date: INSERTION, DELETION, SEARCHING, DISPLAY OF TREE

AIM
To implement binary search trees and perform operations on them.
ALGORITHM
Step 1: Start.
Step 2: Declare the necessary function for implementation.
Step 3: Create the new node and insert the element into the node.
Step 4: In insertion the new element can be insert at any position and in deletion, any
element can be deleted.
Step 5: Display the element stored in the node after implementation.
Step 6: Stop.
PROGRAM
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *root = NULL;
struct node *create_node(int);
void insert(int);
struct node *delete (struct node *, int)
int search(int);
void inorder();
void postorder();
void preorder();
struct node *smallest_node(struct node *);
lOMoARcPSD|214 839 54

57

struct node *largest_node(struct node *);


int get_data();
int main()
{
int userChoice;
int data;
struct node* result = NULL;
printf("------- Binary Search Tree ------
\n1.Insert\n2.Delete\n3.Preorder\n4.Postorder\n5.Inorder\n6.Exit\n");
while (1)
{
printf("\nEnter Your Choice: ");
scanf("%d", &userChoice);
switch(userChoice)
{
case 1:
data = get_data();
insert(data);
break;
case 2:
data = get_data();
root = delete(root, data);
break;
case 3:
preorder(root);
break;
case 4:
postorder(root);
break;
case 5:
lOMoARcPSD|214 839 54

58

inorder(root);
break;
case 6:
printf("\nProgram was terminated\n");
exit(0);
break;
default:
printf("\nInvalid Choice\n");
break;
}
}
return 0;
}
struct node *create_node(int data)
{
struct node *new_node = (struct node *)malloc(sizeof(struct node));
if (new_node == NULL)
{
printf("\nMemory for new node can't be allocated");
return NULL;
}
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
void insert(int data) {
struct node *new_node = create_node(data);
if (new_node != NULL)
{
lOMoARcPSD|214 839 54

59

if (root == NULL)
{
root = new_node;
return;
}
struct node *temp = root;
struct node *prev = NULL;
while (temp != NULL)
{
prev = temp;
if (data > temp->data)
temp = temp->right;
else
temp = temp->left;
}
if (data > prev->data)
prev->right = new_node;
else
prev->left = new_node;
}
}
struct node *delete (struct node *root, int key)
{
if (root == NULL)
return root;
if (key < root->data)
root->left = delete (root->left, key);
else if (key > root->data)
root->right = delete (root->right, key);
else
lOMoARcPSD|214 839 54

60

{
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
struct node *temp = smallest_node(root->right);
root->data = temp->data;
root->right = delete (root->right, temp->data);
}
return root;
}
struct node *smallest_node(struct node *root)
{
struct node *curr = root;
while (curr != NULL && curr->left != NULL)
curr = curr->left;
return curr;
}
void preorder(struct node *root){
if (root == NULL)
return;
printf("%d ", root->data);
lOMoARcPSD|214 839 54

61

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);
}
void inorder(struct node *root){
if (root == NULL)
return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
int get_data()
{
int data;
printf("Enter Data: ");
scanf("%d", &data);
return data;
}
lOMoARcPSD|214 839 54

62

OUTPUT

RESULT
Thus, a C-Program to implement the binary search tree and perform the insertion,
deletion, searching, display the tree.
lOMoARcPSD|214 839 54

63

Ex.No: IMPLEMENTATION OF AVL TREES


Date:

AIM
To implement the AVL tree in C program.

ALGORITHM
Step 1: Start

Step 2: Declare the necessary functions.


Step 3: Get and pass the input to the functions.
Step 4: Creating and inserting values in heap.
Step 5: Display the output.

Step 6: Stop

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

struct Node {

int key;
struct Node *left;
struct Node *right;

int height;
};
int max(int a, int b);

int height(struct Node *N) {


if (N == NULL)

return 0;

return N->height;
}

int max(int a, int b) {


return (a > b) ? a : b;
lOMoARcPSD|214 839 54

64

}
struct Node *newNode(int key) {

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


node->key = key;

node->left = NULL;
node->right = NULL;
node->height = 1;

return (node);

}
struct Node *rightRotate(struct Node *y) {
struct Node *x = y->left;
struct Node *T2 = x->right;
x->right = y;

y->left = T2;
y->height = max(height(y->left), height(y->right)) + 1;

x->height = max(height(x->left), height(x->right)) + 1;


return x;

}
struct Node *leftRotate(struct Node *x) {
struct Node *y = x->right;

struct Node *T2 = y->left;


y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;

return y;

}
int getBalance(struct Node *N) {
if (N == NULL)
lOMoARcPSD|214 839 54

65

return 0;
return height(N->left) - height(N->right);

}
struct Node *insertNode(struct Node *node, int key) {

if (node == NULL)

return (newNode(key));
if (key < node->key)
node->left = insertNode(node->left, key);
else if (key > node->key)
node->right = insertNode(node->right, key);

else
return node;

node->height = 1 + max(height(node->left),
height(node->right));
int balance = getBalance(node);

if (balance > 1 && key < node->left->key)


return rightRotate(node);

if (balance < -1 && key > node->right->key)


return leftRotate(node);
if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);

return rightRotate(node);
}

if (balance < -1 && key < node->right->key) {


node->right = rightRotate(node->right);
return leftRotate(node);

}
return node;
}
lOMoARcPSD|214 839 54

66

struct Node *minValueNode(struct Node *node) {


struct Node *current = node;

while (current->left != NULL)


current = current->left;

return current;
}

struct Node *deleteNode(struct Node *root, int key) {


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) || (root->right == NULL)) {


struct Node *temp = root->left ? root->left : root->right;
if (temp == NULL) {

temp = root;
root = NULL;
} else
*root = *temp;

free(temp);

} else {

struct Node *temp = minValueNode(root->right);


root->key = temp->key;

root->right = deleteNode(root->right, temp->key);


}

}
if (root == NULL)
lOMoARcPSD|214 839 54

67

return root;
root->height = 1 + max(height(root->left),

height(root->right));

int balance = getBalance(root);

if (balance > 1 && getBalance(root->left) >= 0)


return rightRotate(root);
if (balance > 1 && getBalance(root->left) < 0) {
root->left = leftRotate(root->left);

return rightRotate(root);
}

if (balance < -1 && getBalance(root->right) <= 0)


return leftRotate(root);
if (balance < -1 && getBalance(root->right) > 0) {
root->right = rightRotate(root->right);

return leftRotate(root);
}
return root;

void printPreOrder(struct Node *root) {


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

}
int main() {

struct Node *root = NULL;


root = insertNode(root, 1);
lOMoARcPSD|214 839 54

68

root = insertNode(root, 2);


root = insertNode(root, 3);

root = insertNode(root, 4);


root = insertNode(root, 5);

root = insertNode(root, 6);


root = insertNode(root, 7);
root = insertNode(root, 8);

printPreOrder(root);
root = deleteNode(root, 3);

printf("\nAfter deletion: ");


printPreOrder(root);

return 0;
}

OUTPUT

RESULT
Thus, the C program for implementing AVL trees was executed successfully.
lOMoARcPSD|214 839 54

69

Ex.no: IMPLEMENTATION OF HEAP USING PRIORITY QUEUE


Date:

AIM
To implement heap using priority queue.
ALGORITHM
Step 1: Start
Step 2: Declare the necessary functions for implementation
Step 3: Get the input from the user and store it in array
Step 4: Creating and inserting values in heap
Step 5: Display the output using array
Step 6: Stop
PROGRAM
#include<stdio.h>
#include<stdlib.h>
#define MAX 10
int arr[MAX];
int i;
int n;
void insert(int num)
{
if(n<MAX)
{
arr[n]=num;
n++;
}
else
printf("\nArray is full");
}
void makeheap()
lOMoARcPSD|214 839 54

70

{
for(i=1;i<n;i++)
{
int val=arr[i];
int j=i;
int f=(j-1)/2;
while(j>0 &&arr[f]<val) //creating a MAX heap
{
arr[j]=arr[f];
j=f;
f=(j-1)/2;
}
arr[j]=val;
}
}
void display()
{
printf("\n");
for(i=0;i<n;i++)
printf("\t%d",arr[i]);
}
int main()
{
insert(14);
insert(12);
insert(9);
insert(8);
insert(7);
insert(10);
insert(18);
lOMoARcPSD|214 839 54

71

printf("\nThe elements are...");


display();
makeheap();
printf("\nHeapified");
display();
return 0;
}

OUTPUT

RESULT
Thus, the C program for implementing heap using priority queue was implemented
successfully.
lOMoARcPSD|214 839 54

72

Ex. No: GRAPH REPRESENTATION AND TRAVERSAL ALGORITHM


Date: BREADTH FIRST TRAVERSAL

AIM
To implement a traversal algorithm Breadth First Traversal
ALGORITHM
Step 1: Start
Step 2: Push DFS starting node in the queue, mark it visited
Step 3: While queue is not empty
Step 4: Get first node from the queue say it v
Step 5: Check all adjacent nodes from v
Step 6: Push adjacent nodes in queue and mark it visited
Step 7: Stop
PROGRAM
#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v)
{
for (i=1;i<=n;i++)
if(a[v][i] && !visited[i])
q[++r]=i;
if(f<=r)
{
visited[q[f]]=1;
bfs(q[f++]);
}
}
lOMoARcPSD|214 839 54

73

void main()
{
int v;
printf("\nEnter the number of vertices: ");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
printf("\nEnter graph data in matrix form:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the starting vertex: ");
scanf("%d",&v);
bfs(v);
printf("\nThe node which are reachable are: \n");
for (i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i);
else
printf("\n Bfs is not possible");
getch();
}
lOMoARcPSD|214 839 54

74

OUTPUT

RESULT
Thus, Breadth First Traversal has been executed successfully.
lOMoARcPSD|214 839 54

75

Ex. No: GRAPH REPRESENTATION AND TRAVERSAL ALGORITHM


Date: DEPTH FIRST TRAVERSAL

AIM
To implement Depth First Traversal algorithm.
ALGORITHM
Step 1: Start
Step 2: Take the graph as a input
Step 3: Start at some vertex and traverse it using DFS
Step 4: Apply the above procedure for all nodes
Step 5: Display the result
Step 6: Stop
PROGRAM
#include <stdio.h>
void dfs(int);
int g[10][10],visited[10],n,vertex[10];
void main()
{
int i,j;
printf("Enter number of vertices: ");
scanf("%d",&n);
printf("Enter the value of vertex:\n");
for(i=0;i<n;i++)
scanf("%d",&vertex[i]);
printf("\nEnter adjacency matrix of the graph: \n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&g[i][j]);
lOMoARcPSD|214 839 54

76

for(i=0;i<n;i++)
visited[i]=0;
dfs(0);
}
void dfs(int i)
{
int j;
printf("%d -> ",vertex[i]);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&g[i][j]==1)
dfs(j);
}

OUTPUT

RESULT
Thus, the Depth First Traversal algorithm has been executed successfully.
lOMoARcPSD|214 839 54

77

Ex. No: APPLICATION OF GRAPH-IMPLEMENTATION OF


Date: TOPOLOGICAL SORT

AIM
To implement a topological sort. (Application of graph)
ALGORITHM
Step 1: Start
Step 2: Find the degrees of all vertices
Step 3: Remove each vertex based on the degrees
Step 4: Remove and repeat step 2 and step 3
Step 5: Display the result
Step 6: Stop
PROGRAM
#include <stdio.h>
int main()
{
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
printf("Enter the no of vertices:\n");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=0;i<n;i++)
{
printf("Enter row %d\n",i+1);
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
for(i=0;i<n;i++)
{
indeg[i]=0;
flag[i]=0;
lOMoARcPSD|214 839 54

78

}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];
printf("\nThe topological order is:");
while(count<n)
{
for(k=0;k<n;k++)
{
if((indeg[k]==0) && (flag[k]==0))
{
printf("%d ",(k+1));
flag [k]=1;
}
for(i=0;i<n;i++)
{
if(a[i][k]==1)
indeg[k]--;
}
}
count++;
}
return 0;
}
lOMoARcPSD|214 839 54

79

OUTPUT

RESULT
Thus, the topological sort has been executed successfully.
lOMoARcPSD|214 839 54

80

Ex. No: APPLICATION OF GRAPH-IMPLEMENTATION OF


Date: SHORTEST PATH -DIJKSTRA’S ALGORITHM

AIM
To implement Dijkstra’s algorithm to find the shortest path.
ALGORITHM
Step 1: Start
Step 2: Create a graph matrix of input values
Step 3: Define all the necessary functions to find the minimum distance function
Step 4: Print the acquired solution
Step 5: Stop
PROGRAM
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#define V 9
int minDistance(int dist[], bool sptSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
void printSolution(int dist[])
{
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
}
lOMoARcPSD|214 839 54

81

void dijkstra(int graph[V][V], int src) {


int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v]
&& dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist);
}
int main() {
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
dijkstra(graph, 0);
return 0;
}
lOMoARcPSD|214 839 54

82

OUTPUT

RESULT
Thus, Dijkstra’s algorithm to find the shortest path has been executed successfully.
lOMoARcPSD|214 839 54

83

Ex. No: IMPLEMENTATION OF PRIM’S ALGORITHM


Date:

AIM
To implement Prim’s algorithm in C language.
ALGORITHM
Step 1: Start
Step 2: Create a matrix graph for input values
Step 3: Execute Prim’s Algorithm
Step 4: Print the solution
Step 5: Stop
PROGRAM
#include<stdio.h>
#include<stdbool.h>
#define INF 9999999
#define V 5
int G[V][V] = {
{0, 9, 75, 0, 0},
{9, 0, 95, 19, 42},
{75, 95, 0, 51, 66},
{0, 19, 51, 0, 31},
{0, 42, 66, 31, 0}};
int main() {
int no_edge;
int selected[V];
memset(selected, false, sizeof(selected));
no_edge = 0;
selected[0] = true;
int x;
int y;
lOMoARcPSD|214 839 54

84

printf("Edge : Weight\n");
while (no_edge < V - 1)
{
int min = INF;
x = 0;
y = 0;
for (int i = 0; i < V; i++)
{
if (selected[i])
{
for (int j = 0; j < V; j++)
{
if (!selected[j] && G[i][j])
{
if (min > G[i][j])
{
min = G[i][j];
x = i;
y = j;
}
}
}
}
}
printf("%d - %d : %d\n", x, y, G[x][y]);
selected[y] = true;
no_edge++;
}
return 0;
}
lOMoARcPSD|214 839 54

85

OUTPUT

RESULT
Thus, the Prim’s Algorithm has been executed successfully.
lOMoARcPSD|214 839 54

86

Ex. No: IMPLEMENTATION OF LINEAR SEARCH


Date:

AIM
To implement Searching Algorithm - Linear Search
ALGORITHM
Step 1: Start
Step 2: Get the array from the user
Step 3: Traverse the array and search the key element one by one
Step 4: If found print the index value
Step 5: Stop
PROGRAM
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int a[30],search,length,value=0;
printf("Enter the size of the array required: ");
scanf("%d",&length);
printf("Enter the array elements: \n");
for(int i=0;i<length;i++)
{
scanf("%d",&a[i]);
}
printf("Enter search element: ");
scanf("%d",&search);
for(int i=0;i<length;i++)
{
if(a[i]==search)
{
lOMoARcPSD|214 839 54

87

printf("Search element found at %d\n",i+1);


value=1;
}
}
if(value==0)
{
printf("Element not found\n");
}
else
{
return 0;
}
}
OUTPUT

RESULT
Thus, the C program for Linear Search has been executed successfully.
lOMoARcPSD|214 839 54

88

Ex. No: IMPLEMENTATION OF BINARY SEARCH


Date:

AIM
To implement a searching algorithm – Binary Search
ALGORITHM
Step 1: Start
Step 2: Get the array from the user in ascending order
Step 3: Check the key with the mid of the array
Step 4: If found print found, else continue the approach recursively
Step 5: If not found at the end, print not found
Step 6: Stop
PROGRAM
#include<stdio.h>
#include<stdlib.h>
int main(void) {
int arr[50],length,search,flag=0,first,last,mid;
printf("Enter size of array: ");
scanf("%d",&length);
printf("Enter array element(ascending order): \n");
for(int i=0;i<length;++i)
scanf("%d",&arr[i]);
printf("Enter the element to search: ");
scanf("%d",&search);
first=0; last=length-1;
while(first<=last) {
mid=(first+last)/2;
if(search==arr[mid]) {
flag=1;
break;
lOMoARcPSD|214 839 54

89

}
else
if(search>arr[mid])
first=mid+1;
else
last=mid-1;
}
if(flag==1)
printf("Element found at Position %d\nIndex %d\n",mid+1,mid);
else
printf("Element not found\n");
}
OUTPUT

RESULT
Thus, the C program for Binary Search has been executed successfully.
lOMoARcPSD|214 839 54

90

Ex. No: IMPLEMENTATION OF INSERTION SORT


Date:

AIM
To implement sorting algorithm – Insertion Sort
ALGORITHM
Step 1: Start
Step 2: If it is the first element, it is already sorted. return 1;
Step 3: Pick next element
Step 4: Compare with all elements in the sorted sub-list
Step 5: Shift all the elements in the sorted sub-list that is greater than the value to be
sorted
Step 6: Insert the value
Step 7: Repeat until list is sorted
Step 8: Stop
PROGRAM
#include<stdio.h>
void insertion_sort(int[]);
void main()
{
int num[5];
printf("Enter the five elements to sort: \n");
for(int count=0;count<5;count++)
scanf("%d",&num[count]);
insertion_sort(num); /*function call for insertion sort*/
printf("Elements after sorting:\n");
for(int count=0;count<5;count++)
printf("%d\n",num[count]);
}
lOMoARcPSD|214 839 54

91

void insertion_sort(int num[]) /* function definition for insertion sort*/


{
int i,j,k;
for(j=1;j<5;j++)
{
k=num[j];
for(i=j-1;i>=0&&k<num[i];i--)
num[i+1]=num[i];
num[i+1]=k;
}
}
OUTPUT

RESULT
Thus, Insertion Sort has been executed successfully.
lOMoARcPSD|214 839 54

92

Ex. No: IMPLEMENTATION OF MERGE SORT


Date:

AIM
To implement sorting algorithm – Merge Sort.
ALGORITHM
Step 1: Start
Step 2: If it is only one element in the list it is already sorted, return.
Step 3: Divide the list recursively into two halves until it can no more be divided.
Step 4: Merge the smaller lists into new list in sorted order.
Step 5: Stop
PROGRAM
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

/* create temp arrays */


int L[n1], R[n2];

/* Copy data to temp arrays L[] and R[] */


for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

/* Merge the temp arrays back into arr[l..r]*/


lOMoARcPSD|214 839 54

93

i = 0; // Initial index of first subarray


j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int l, int r)


{
if (l < r) {
int m = l + (r - l) / 2;
lOMoARcPSD|214 839 54

94

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{
int length,arr[30];
printf("Enter the size of array: ");
scanf("%d",&length);
printf("Enter the array elements: \n");
for(int i=0;i<length;i++)
{
scanf("%d",&arr[i]);
}
printf("Given array is...\n");
printArray(arr, length);
mergeSort(arr, 0, length - 1);
printf("Sorted array is...\n");
printArray(arr, length);
return 0;
}
lOMoARcPSD|214 839 54

95

OUTPUT

RESULT
Thus, the Merge sort has been executed successfully.
lOMoARcPSD|214 839 54

96

Ex. No: IMPLEMENTATION OF QUICK SORT


Date:

AIM
To implement sorting algorithm – Quick Sort
ALGORITHM
Step 1: Start
Step 2: Choose the highest index as pivot
Step 3: Use partition function to divide and swap the array
Step 4: Call the quicksort function recursively to sort the array
Step 5: Display the sorted array
Step 6: Stop
PROGRAM
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int array[], int low, int high) {
int pivot = array[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {
i++;
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[high]);
return (i + 1);
lOMoARcPSD|214 839 54

97

}
void quickSort(int array[], int low, int high) {
if (low < high) {
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int arr[50];
int length;
printf("Enter the size of array: ");
scanf("%d",&length);
printf("Enter the array elements: \n");
for(int i=0;i<length;i++)
{
scanf("%d",&arr[i]);
}

printf("Unsorted Array...\n");
printArray(arr, length);

quickSort(arr, 0, length- 1);


lOMoARcPSD|214 839 54

98

printf("Sorted array in ascending order...\n");


printArray(arr, length);
}

OUTPUT

RESULT
Thus, the Quick Sort has been executed successfully.
lOMoARcPSD|214 839 54

99

Ex. No: IMPLEMENTATION OF SELECTION SORT


Date:

AIM
To implement sorting algorithm – Selection Sort
ALGORITHM
Step 1: Start
Step 2: Set min_id to location 0
Step 3: Search the minimum element in the list
Step 4: Swap with value at location min_id
Step 5: Increment min_id to point to next element
Step 6: Repeat until list is sorted
Step 7: Stop
PROGRAM
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void selectionSort(int array[], int size)
{
for (int step = 0; step < size - 1; step++)
{
int min_id= step;
for (int i = step + 1; i < size; i++)
{
if (array[i] < array[min_id])
min_id = i;
lOMoARcPSD|214 839 54

100

}
swap(&array[min_id], &array[step]);
}
}
void printArray(int array[], int size)
{
for (int i = 0; i < size; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
}
int main()
{
int arr[50];
int length;
printf("Enter the size of array: ");
scanf("%d",&length);
printf("Enter the array elements: \n");
for(int i=0;i<length;i++)
{
scanf("%d",&arr[i]);
}
selectionSort(arr, length);
printf("Sorted array in Ascending Order...\n");
printArray(arr,length);
}
lOMoARcPSD|214 839 54

101

OUTPUT

RESULT
Thus, selection sort has been executed successfully.
lOMoARcPSD|214 839 54

102

Ex. No: IMPLEMENTATION OF SHELL SORT


Date:

AIM
To implement sorting algorithm – Shell Sort.
ALGORITHM
Step 1: Start
Step 2: Initialize the value of h
Step 3: Divide the list into smaller dub-list of equal interval h
Step 4: Sort these sub-lists using insertion sort
Step 5: Repeat until complete list is sorted
Step 6: Stop
PROGRAM
#include <stdio.h>
void shellsort(int array[], int n)
{
for (int interval = n / 2; interval > 0; interval /= 2)
{
for (int i = interval; i < n; i += 1)
{
int temp = array[i];
int j;
for (j = i; j >= interval && array[j - interval] > temp; j -= interval)
{
array[j] = array[j - interval];
}
array[j] = temp;
}
}
}
lOMoARcPSD|214 839 54

103

void printArray(int array[], int size)


{
for (int i = 0; i < size; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
}
int main()
{
int data[50],length;
printf("Enter the size of array: ");
scanf("%d",&length);
printf("Enter array elements: \n");
for(int i=0;i<length;i++)
{
scanf("%d",&data[i]);
}
printf("Array before sorting...\n");
printArray(data,length);
shellsort(data, length);

printf("Sorted Array in Ascending Order...\n");


printArray(data, length);
}
lOMoARcPSD|214 839 54

104

OUTPUT

RESULT
Thus, shell sort has been executed successfully.
lOMoARcPSD|214 839 54

105

Ex. No: IMPLEMENTATION OF BUBBLE SORT


Date:

AIM
To implement sorting algorithm – Bubble Sort
ALGORITHM
Step 1: Start
Step 2: Get the array from the user
Step 3: Find the length of the array
Step 4: Pass the array to the bubble sort function
Step 5: Sorting occurs by comparing two consecutive terms in each iteration
Step 6: Display the sorted array
Step 7: Stop
PROGRAM
#include <stdio.h>
void bubbleSort(int array[], int size)
{
for (int step = 0; step < size - 1; ++step)
{
for (int i = 0; i < size - step - 1; ++i)
{
if (array[i] > array[i + 1])
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}
lOMoARcPSD|214 839 54

106

void printArray(int array[], int size)


{
for (int i = 0; i < size; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
}
int main()
{
int data[50],length;
printf("Enter the size of array: ");
scanf("%d",&length);
printf("Enter array elements: \n");
for(int i=0;i<length;i++)
{
scanf("%d",&data[i]);
}
printf("Array before sorting...\n");
printArray(data,length);
bubbleSort(data, length);
printf("Sorted Array in Ascending Order...\n");
printArray(data, length);
}
lOMoARcPSD|214 839 54

107

OUTPUT

RESULT
Thus, bubble sort has been executed successfully.
lOMoARcPSD|214 839 54

108

Ex. No: IMPLEMENTATION OF OPEN ADDRESSING


Date: (LINEAR PROBING AND QUADRATIC PROBING)

AIM
To implement linear addressing and quadratic probing.
ALGORITHM
Step 1: Start
Step 2: Declare the required functions for both linear and quadratic probing.
Step 3: Choose the probing type via switch statement
Step 4: Pass the array to the respective functions
Step 5: Print the resultant hash table
Step 6: Stop
PROGRAM
#include <stdio.h>
#include <conio.h>
int tsize;

int hasht(int key)


{
int i ;
i = key%tsize ;
return i;
}
//-------LINEAR PROBING-------
int rehashl(int key)
{
int i ;
i = (key+1)%tsize ;
return i ;
}
lOMoARcPSD|214 839 54

109

//-------QUADRATIC PROBING-------
int rehashq(int key, int j)
{
int i ;
i = (key+(j*j))%tsize ;
return i ;
}
void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;
printf ("Enter the size of the hash table: ");
scanf ("%d",&tsize);

printf ("\nEnter the number of elements: ");


scanf ("%d",&n);

for (i=0;i<tsize;i++)
hash[i]=-1 ;

printf ("Enter Elements: ");


for (i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
do
{
printf("\n\n1.Linear Probing\n2.Quadratic Probing \n3.Exit \nEnter your option: ");
scanf("%d",&op);
switch(op)
{
lOMoARcPSD|214 839 54

110

case 1:
for (i=0;i<tsize;i++)
hash[i]=-1 ;

for(k=0;k<n;k++)
{
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashl(i);
}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;

case 2:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
j=1;
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
lOMoARcPSD|214 839 54

111

{
i = rehashq(i,j);
j++ ;
}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
}
}while(op!=3);
getch() ;
}
lOMoARcPSD|214 839 54

112

OUTPUT

RESULT
Thus, the implementation of open addressing (linear and quadratic probing) has been
executed successfully.

You might also like