Data Structures & Algorithms Lab Manual
Data Structures & Algorithms Lab Manual
Zero Lab
Turbo C++
C++ tutorial provides basic and advanced concepts of C++. Our C++ tutorial is designed for
beginners and professionals.
Our C++ tutorial includes all topics of C++ such as first example, control statements, objects
and classes, inheritance, constructor, destructor, this, static, polymorphism, abstraction, abstract
class, interface, namespace, encapsulation, arrays, strings, exception handling, File IO, etc.
What is C++?
C++ is a general purpose, case-sensitive, free-form programming language that supports object-
oriented, procedural, and generic programming. C++ is a middle-level language, as it
encapsulates both high and low-level language features.
C++ supports the object-oriented programming, the four major pillar of object-oriented
programming (OOPs) used in C++ are:
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
o The core library includes the data types, variables and literals, etc.
o The standard library includes the set of functions manipulating strings, files, etc.
o The Standard Template Library (STL) includes the set of methods manipulating a data
structure.
Data Structure & Algorithm Lab Manual
Usage of C++
By the help of C++ programming language, we can develop different types of secured and
robust applications:
o Window application
o Client-Server application
o Device drivers
o Embedded firmware etc
C++ Program: In this tutorial, all C++ programs are given with C++ compiler so that you can easily
change theC++ program code.
File: [Link]
1. #include <iostream>
2. using namespace std;
3. int main() {
4. cout << "Hello C++ Programming";
5. return 0;
6. }
History of C++ language is interesting to know. Here we are going to discuss brief history of
C++ language. C++ programming language was developed in 1980 by Bjarne Stroustrup at bell
laboratoriesof AT&T (American Telephone & Telegraph), located in U.S.A.
It was develop for adding a feature of OOP (Object Oriented Programming) in C without
significantly changing the C component.
There are many compilers available for C++. You need to download anyone. Here, we are going to use Turbo
C++. It will work for both C and C++. To install the Turbo C++ software, you need to follow following steps.
2. Create turbo c directory inside c drive and extract the [Link] inside c:\turboc
4. Click on the tc application file located inside c:\TC\BIN to write the c program
Data Structure & Algorithm Lab Manual
EXPERIMENT-1
OBJECTIVE
Introduction: Objective, scope and outcome of the course.
THEORY
The course is designed to develop skills to design and analyze simple linear and nonlinear data
structures. It strengthens the ability to the students to identify and apply the suitable data structure for the
given real-world problem. It enables them to gain knowledge in practical applications of data structures.
At the end of this lab session, the student will
· Be able to design and analyze the time and space efficiency of the data structure
· Be capable to identity the appropriate data structure for given problem
· Have practical knowledge on the applications of data structures
SCOPE
DSA has great importance in the recruitment process of software companies as well. Recruiters use DSA
to test the ability of the programmer because it shows the problem-solving capability of the candidate.
OUTCOMES
Upon the completion of Data Structure & Algorithm practical course, the student will be able to:
3. To evaluate traversing, insertion and deletion operations on Linear and nonlinear data
structures.
EXPERIMENT-2
OBJECTIVE
Write a simple C program on a 32 bit compiler to understand the concept of array storage, size of a
word. The program shall be written illustrating the concept of row major and column major storage.
Find the address of element and verify it with the theoretical value. Program may be written for arrays
up to 4-dimensions.
PROGRAM
Part 1
#include <stdio.h>
int main()
{
int arr[] = { 1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14 };
printf("Number of elements:%d", sizeof(arr) / sizeof(arr[0]));
return 0;
}
Part 2
#include <stdio.h>
void main ()
{ int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d", &arr[i][j]);
}
}
printf("\n printing the elements .....\n");
for (i=0;i<3;i++)
{ printf("\n");
for (j=0;j<3;j++)
{ printf("%d\t", arr[i][j]);
} }}
Data Structure & Algorithm Lab Manual
EXPERIMENT-3
OBJECTIVE
Simulate a stack, queue, circular queue and dequeue using a one-dimensional array as storage element.
The program should implement the basic addition, deletion and traversal operations.
PROGRAM
Part 1
#include<stdio.h>
int stack[10], choice, n, top, x, i; // Declaration of variables
void push();
void pop();
void display();
int main()
{
top = -1; // Initially there is no element in stack
printf("\n Enter the size of STACK : ");
scanf("%d", &n);
printf("\nSTACK IMPLEMENTATION USING ARRAYS\n");
do
{
printf("\[Link]\[Link]\[Link]\[Link]\n");
printf("\nEnter the choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
Data Structure & Algorithm Lab Manual
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
break;
}
default:
{
printf ("\nInvalid Choice\n");
}}}
while(choice!=4);
return 0;
}
void push()
{
if(top >= n - 1)
{
printf("\nSTACK OVERFLOW\n");
}
else
{
printf("Enter a value to be pushed : ");
scanf("%d",&x);
top++; // TOP is incremented after an element is pushed
stack[top] = x; // The pushed element is made as TOP
}}
void pop()
{
if(top <= -1)
Data Structure & Algorithm Lab Manual
{
printf("\nSTACK UNDERFLOW\n");
}
else
{
printf("\nThe popped element is %d",stack[top]);
top--; // Decrement TOP after a pop
}}
void display()
{
if(top >= 0)
{
// Print the stack
printf("\nELEMENTS IN THE STACK\n\n");
for(i = top ; i >= 0 ; i--)
printf("%d\t",stack[i]);
}
else
{
printf("\nEMPTY STACK\n");
}}
Output:
Data Structure & Algorithm Lab Manual
Part 2
#include<stdio.h>
#define MAX 50
void enqueue();
void dequeue();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while(1)
{
printf("[Link] element to queue \n");
printf("[Link] element from queue \n");
printf("[Link] all elements of queue \n");
printf("[Link] \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */
void enqueue()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
Data Structure & Algorithm Lab Manual
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() */
void dequeue()
{
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() */
void 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");
}
}
Output:
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4. Quit
}
// display function prints all the value of deque.
void display()
{
int i=f;
printf("\nElements in a deque are: ");
while(i!=r)
{
printf("%d ",deque[i]);
i=(i+1)%size;
}
printf("%d",deque[r]);
}
// getfront function retrieves the first value of the deque.
void getfront()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else
{
printf("\nThe value of the element at front is: %d", deque[f]);
} }
// getrear function retrieves the last value of the deque.
void getrear()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else
{
printf("\nThe value of the element at rear is %d", deque[r]);
} }
// delete_front() function deletes the element from the front
void delete_front()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else if(f==r)
{
printf("\nThe deleted element is %d", deque[f]);
f=-1;
r=-1;
}
else if(f==(size-1))
{
printf("\nThe deleted element is %d", deque[f]);
f=0;
}
else
{
printf("\nThe deleted element is %d", deque[f]);
f=f+1;
} }
// delete_rear() function deletes the element from the rear
void delete_rear()
{
if((f==-1) && (r==-1))
{
printf("Deque is empty");
}
else if(f==r)
{
printf("\nThe deleted element is %d", deque[r]);
f=-1;
r=-1;
}
else if(r==0)
{
printf("\nThe deleted element is %d", deque[r]);
r=size-1;
}
else
{
printf("\nThe deleted element is %d", deque[r]);
r=r-1;
}
}
int main()
{
insert_front(20);
insert_front(10);
insert_rear(30);
insert_rear(50);
insert_rear(80);
display(); // Calling the display function to retrieve the values of deque
getfront(); // Retrieve the value at front-end
getrear(); // Retrieve the value at rear-end
delete_front();
delete_rear();
display(); // calling display function to retrieve values after deletion
return 0;
}
Output:
EXPERIMENT-4
OBJECTIVE
Represent a 2-variable polynomial using array. Use this representation to implement addition of
polynomials.
PROGRAM
Part 1
#include <stdio.h>
#include<stdlib.h>
struct Term
{
int coeff;
int exp;
};
struct Poly
{
int n;
struct Term *terms;
};
i = j = k = 0;
sum->n = k;
return sum;
}
int main()
{
struct Poly p1, p2, *p3;
return 0;
}
Output:
Part 2
#include<stdio.h>
/* function prototypes */
int readPoly(struct poly []);
int addPoly(struct poly [],struct poly [],int ,int ,struct poly []);
void displayPoly( struct poly [],int terms);
int main()
{
int t1,t2,t3;
return 0;
}
int addPoly(struct poly p1[10],struct poly p2[10],int t1,int t2,struct poly p3[10])
{
int i,j,k;
i=0;
j=0;
k=0;
i++;
j++;
k++;
}
else if(p1[i].expo>p2[j].expo)
{
p3[k].coeff=p1[i].coeff;
p3[k].expo=p1[i].expo;
i++;
k++;
}
else
{
p3[k].coeff=p2[j].coeff;
p3[k].expo=p2[j].expo;
j++;
k++;
}
}
for(k=0;k<term-1;k++)
printf("%d(x^%d)+",p[k].coeff,p[k].expo);
printf("%d(x^%d)",p[term-1].coeff,p[term-1].expo);
}
Output:
OBJECTIVE
Represent a sparse matrix using array. Implement addition and transposition operations using the
representation.
PROGRAM
#include<stdio.h>
#define MAX 20
void printsparse(int[][3]);
void readsparse(int[][3]);
void transpose(int[][3],int[][3]);
int main()
{
int b1[MAX][3],b2[MAX][3],m,n;
printf("Enter the size of matrix (rows,columns):");
scanf("%d%d",&m,&n);
b1[0][0]=m;
b1[0][1]=n;
readsparse(b1);
transpose(b1,b2);
printsparse(b2);
}
void readsparse(int b[MAX][3])
{
int i,t;
printf("\nEnter no. of non-zero elements:");
scanf("%d",&t);
b[0][2]=t;
for(i=1;i<=t;i++)
{
printf("\nEnter the next triple(row,column,value):");
scanf("%d%d%d",&b[i][0],&b[i][1],&b[i][2]);
}
}
void printsparse(int b[MAX][3])
{
int i,n;
n=b[0][2]; //no of 3-triples
printf("\nAfter Transpose:\n");
printf("\nrow\t\tcolumn\t\tvalue\n");
for(i=0;i<=n;i++)
printf("%d\t\t%d\t\t%d\n",b[i][0],b[i][1],b[i][2]);
}
void transpose(int b1[][3],int b2[][3])
{
int i,j,k,n;
b2[0][0]=b1[0][1];
b2[0][1]=b1[0][0];
b2[0][2]=b1[0][2];
k=1;
n=b1[0][2];
for(i=0;i<b1[0][1];i++)
for(j=1;j<=n;j++)
//if a column number of current triple==i then insert the current triple in b2
if(i==b1[j][1])
{
b2[k][0]=i;
b2[k][1]=b1[j][0];
b2[k][2]=b1[j][2];
k++;
}
}
Output:
Enter the size of matrix (rows,columns):3 4
Enter no. of non-zero elements:4
Enter the next triple(row,column,value):1 0 5
Enter the next triple(row,column,value):1 2 3
Enter the next triple(row,column,value):2 1 1
Enter the next triple(row,column,value):2 3 2
After Transpose:
row column value
434
015
121
213
322
EXPERIMENT-6
OBJECTIVE
Implement singly, doubly and circularly connected linked lists illustrating operations like addition at
different locations, deletion from specified locations and traversal.
PROGRAM
Part 1
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int Data;
Struct Node *next;
};
void insertStart (struct Node **head, int data)
{
struct Node *newNode = (struct Node *) malloc (sizeof (struct Node));
newNode - > data = data;
newNode - > next = *head;
100 Inserted
80 Inserted
60 Inserted
40 Inserted
20 Inserted
20 deleted
40 deleted
Part 2
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int data;
int key;
struct node *next;
struct node *prev;
};
//this link always point to first Link
struct node *head = NULL;
//this link always point to last Link
struct node *last = NULL;
struct node *current = NULL;
//is list empty
bool isEmpty() {
return head == NULL;
}
int length() {
int length = 0;
struct node *current;
for(current = head; current != NULL; current = current->next){
length++;
}
return length;
}
//display the list in from first to last
void displayForward() {
//start from the beginning
struct node *ptr = head;
//navigate till the end of the list
printf("\n[ ");
while(ptr != NULL) {
printf("(%d,%d) ",ptr->key,ptr->data);
ptr = ptr->next;
}
printf(" ]");
}
//display the list from last to first
void displayBackward() {
//start from the last
struct node *ptr = last;
//navigate till the start of the list
printf("\n[ ");
while(ptr != NULL) {
//print data
printf("(%d,%d) ",ptr->key,ptr->data);
//move to next item
ptr = ptr ->prev;
}}
//insert link at the first location
void insertFirst(int key, int data) {
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(isEmpty()) {
//make it the last link
last = link;
} else {
//update first prev link
head->prev = link;
}
//point it to old first link
link->next = head;
//point first to new first link
head = link;
}
//insert link at the last location
void insertLast(int key, int data) {
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(isEmpty()) {
//make it the last link
last = link;
} else {
//make link a new last link
last->next = link;
//mark old last node as prev of new link
link->prev = last;
}
//point last to new last node
last = link;
}
//delete first item
struct node* deleteFirst() {
//save reference to first link
struct node *tempLink = head;
//if only one link
if(head->next == NULL){
last = NULL;
} else {
head->next->prev = NULL;
}
head = head->next;
//return the deleted link
return tempLink;
}
//delete link at the last location
struct node* deleteLast() {
//save reference to last link
struct node *tempLink = last;
//if only one link
if(head->next == NULL) {
head = NULL;
} else {
last->prev->next = NULL;
}
last = last->prev;
//return the deleted link
return tempLink;
}
//delete a link with given key
Output:
List (First to Last):
[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]
List (Last to first):
[ (1,10) (2,20) (3,30) (4,1) (5,40) (6,56) ]
List , after deleting first record:
[ (5,40) (4,1) (3,30) (2,20) (1,10) ]
List , after deleting last record:
[ (5,40) (4,1) (3,30) (2,20) ]
List , insert after key(4) :
[ (5,40) (4,1) (7,13) (3,30) (2,20) ]
List , after delete key(4) :
[ (5,40) (4,13) (3,30) (2,20) ]
Part 3
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
void beginsert ();
void lastinsert ();
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 7)
{
printf("\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\n===============================================\n");
printf("\[Link] in begining\[Link] at last\[Link] from Beginning\[Link] from
last\[Link] for an element\[Link]\[Link]\n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
beginsert();
break;
case 2:
lastinsert();
break;
case 3:
begin_delete();
break;
case 4:
last_delete();
break;
case 5:
search();
break;
case 6:
display();
break;
case 7:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void beginsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter the node data?");
scanf("%d",&item);
ptr -> data = item;
if(head == NULL)
{
head = ptr;
ptr -> next = head;
}
else
{
temp = head;
while(temp->next != head)
temp = temp->next;
ptr->next = head;
temp -> next = ptr;
head = ptr;
}
printf("\nnode inserted\n");
}
}
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW\n");
}
else
{
printf("\nEnter Data?");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
head = ptr;
ptr -> next = head;
}
else
{
temp = head;
while(temp -> next != head)
{
temp = temp -> next;
}
temp -> next = ptr;
ptr -> next = head;
}
printf("\nnode inserted\n");
}
}
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nUNDERFLOW");
}
else if(head->next == head)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{ ptr = head;
while(ptr -> next != head)
ptr = ptr -> next;
ptr->next = head->next;
free(head);
head = ptr->next;
printf("\nnode deleted\n");
}
}
void last_delete()
{
struct node *ptr, *preptr;
if(head==NULL)
{
printf("\nUNDERFLOW");
}
else if (head ->next == head)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
while(ptr ->next != head)
{
preptr=ptr;
ptr = ptr->next;
}
preptr->next = ptr -> next;
free(ptr);
printf("\nnode deleted\n");
}
}
void search()
{
struct node *ptr;
int item,i=0,flag=1;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
if(head ->data == item)
{
printf("item found at location %d",i+1);
flag=0;
}
else
{
while (ptr->next != head)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
}
if(flag != 0)
{
printf("Item not found\n");
} } }
void display()
{
struct node *ptr;
ptr=head;
if(head == NULL)
{
printf("\nnothing to print");
}
else
{ printf("\n printing values ... \n");
while(ptr -> next != head)
{
printf("%d\n", ptr -> data);
ptr = ptr -> next;
}
printf("%d\n", ptr -> data);
} }
Output:
Choose one option from the following list ...
===============================================
1. Insert in begining
2. Insert at last
3. Delete from Beginning
4. Delete from last
5. Search for an element
6. Show
7. Exit
Enter your choice?
1
Enter the node data?10
node inserted
EXPERIMENT-7
OBJECTIVE
Repeat experiment 3, 4, 5 with linked structure.
PROGRAM
Part 1
#include <stdio.h>
#include <stdlib.h>
if (top1 == NULL)
{
printf("\nStack Underflow\n");
return -1;
}
else
top1 = top1->ptr;
int popped = top->info;
free(top);
top = top1;
count--;
return popped;
}
void display() {
// Display the elements of the stack
top1 = top;
if (top1 == NULL)
{
printf("\nStack Underflow\n");
return;
}
1. Push
2. Pop
3. Display
4. Exit
1. Push
2. Pop
3. Display
4. Exit
1. Push
2. Pop
3. Display
4. Exit
OBJECTIVE
Implementation of binary tree with operations like addition, deletion, traversal.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
struct bst{
int data;
struct bst* left;
struct bst* right;
}*root;
struct bst* insert(struct bst* root, int num)
{
if(root==NULL)
{
root=(struct bst*)malloc(sizeof(struct bst));
root->data=num;
root->left=NULL;
root->right=NULL;
}
else
{
if(num<root->data)
{
root->left=insert(root->left,num);
}
else
{
root->right=insert(root->right,num);
}
}
return root;
}
void in_order(struct bst* root)
{
if(root!=NULL)
{
in_order(root->left);
printf("%d\t",root->data);
in_order(root->right);
}
}
void search(struct bst* root,int num)
{
if(root==NULL)
{
printf("\nnumber not found.");
}
else if(root->data==num)
{
printf("\ndata is found %d",num);
}
else if(root->data>num)
{
search(root->left,num);
}
else
{
search(root->right,num);
}
}
struct bst* Delete(struct bst* root,int num)
{
if(root==NULL)
{
printf("\nnumber not found.");
}
else if(root->data==num)
{
if(root->left==NULL&&root->right==NULL)
{
struct bst * temp = root;
free(temp);
printf("\nNo. is deleted.");
return NULL;
}
else if(root->left==NULL && root->right!=NULL)
{
struct bst*temp=root;
root=root->right;
free(temp);
printf("\nNo. is deleted.");
return root;
}
else if(root->left!=NULL && root->right==NULL)
{
struct bst*temp=root;
root=root->left;
free(temp);
printf("\nNo. is deleted.");
return root;
}
else
{
struct bst *temp;temp=root; root=root->right;
while(root->left!=NULL)
{
root=root->left;
}
temp->data=root->data;
temp->right=Delete(temp->right, root-
>data);return temp;
}
}
else if(root->data>num)
{
root->left=Delete(root->left,num);
}
else
{
root->right=Delete(root->right,num);
}
return root;
}
void main()
{
int arr[] = {20, 17, 6, 8,9, 25, 5, 27,7};
int i;
for(i=0;i<9;i++)
root=insert(root,arr[i]);
OUTPUT:
EXPERIMENT-9
OBJECTIVE
Depth first and breadth first traversal of graphs represented using adjacency matrix and list.
PROGRAM
// BFS in C
#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;
};
// BFS algorithm
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;
} }}
// Creating a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode; }
// Creating a graph
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;}
// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Add edge from dest to src
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;}
// Create a queue
struct queue* createQueue() {
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;}
// Check if the queue is empty
int isEmpty(struct queue* q) {
if (q->rear == -1)
return 1;
else
return 0;}
// Adding elements into queue
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; }}
// Removing elements from queue
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;}
// Print the queue
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:
DFS in C
PROGRAM
#include <stdio.h>
#include <stdlib.h>
struct node {
int vertex;
struct node* next;
};
struct node* createNode(int v);
struct Graph {
int numVertices;
int* visited;
// We need int** to store a two dimensional array.
// Similary, we need struct node** to store an array of Linked lists
struct node** adjLists;
};
// DFS algo
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;
}}
// Create a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Create graph
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;
}
// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Add edge from dest to src
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
// Print the graph
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:
EXPERIMENT-10
OBJECTIVE
Implementation of binary search in arrays and on linked Binary Search Tree.
PROGRAM
#include <stdio.h>
int binarySearch(int a[], int beg, int end, int val)
{
int mid;
if(end >= beg)
{ mid = (beg + end)/2;
/* if the item to be searched is present at middle */
if(a[mid] == val)
{
return mid+1;
}
/* if the item to be searched is smaller than middle, then it can only be in left subarray */
OUTPUT:
EXPERIMENT-11
OBJECTIVE
Implementation of different sorting algorithm like insertion, quick, heap, bubble and many
more sorting algorithms.
Bubble sort
PROGRAM
#include<stdio.h>
void print(int a[], int n) //function to print array elements
{ int i;
for(i = 0; i < n; i++)
{ printf("%d ",a[i]);
}}
void bubble(int a[], int n) // function to implement bubble sort
{ int i, j, temp;
for(i = 0; i < n; i++)
{
for(j = i+1; j < n; j++)
{
if(a[j] < a[i])
{
temp = a[i];a[i] = a[j]; a[j] = temp;
}
}}}
void main ()
{
int i, j,temp;
66
elements are - \n");print(a, n);
}
OUTPUT
SELECTION SORT
PROGRAM
#include <stdio.h>
void selection(int arr[], int n)
{
int i, j, small;
for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
{
small = i; //minimum element in unsorted array
67
int i;
for (i = 0; i < n; i++)printf("%d ", a[i]);
}
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
Output:
INSERTION SORT
PROGRAM
#include <stdio.h>
void insert(int a[], int n) /* function to sort an aay with insertion sort */
{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;
while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one
68
positionahead from their current position*/
{
a[j+1] = a[j];j = j-1;
}
a[j+1] = temp;
}
}
void printArr(int a[], int n) /* function to print the array */
{ int i;
for (i = 0; i < n; i++)
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}
Output:
69
QUICK SORT
PROGRAM
#include <stdio.h>
int partition (int a[], int start, int end)
{
int pivot = a[end]; // pivot element
a[i] = a[j];
a[j]=t;
} }
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1); }
void quick(int a[], int start, int end)
{ if (start < end)
{ int p = partition(a, start, end); //p is the partitioning index
70
int main()
{ int a[] = { 24, 9, 29, 14, 19, 27 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");printArr(a, n);
quick(a, 0, n - 1);
printf("\nAfter sorting array elements are - \n");printArr(a, n);
return 0; }
Output:
71