(R18A0584) Data Structures Lab Manual
(R18A0584) Data Structures Lab Manual
(R18A0584)
LABORATORY MANUAL &
RECORD
B.TECH (R18)
(II YEAR – I SEM)
(2020-21)
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
Vision
To acknowledge quality education and instill high patterns of discipline
making the students technologically superior and ethically strong which
involves the improvement in the quality of life in human race.
Mission
To achieve and impart holistic technical education using the best of
infrastructure, outstanding technical and teaching expertise to establish
the students into competent and confident engineers.
Evolving the center of excellence through creative and innovative
teaching learning practices for promoting academic achievement to
produce internationally accepted competitive and world class
professionals.
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
1. To facilitate the graduates with the ability to visualize, gather information, articulate,
analyze, solve complex problems, and make decisions. These are essential to
address the challenges of complex and computation intensive problems increasing
their productivity.
2. To facilitate the graduates with the technical skills that prepare them for immediate
employment and pursue certification providing a deeper understanding of the
technology in advanced areas of computer science and related fields, thus
encouraging to pursue higher education and research based on their interest.
3. To facilitate the graduates with the soft skills that include fulfilling the mission,
setting goals, showing self-confidence by communicating effectively, having a
positive attitude, get involved in team-work, being a leader, managing their career
and their life.
To facilitate the graduates with the knowledge of professional and ethical responsibilities by
paying attention to grooming, being conservative with style, following dress codes, safety
codes,and adapting themselves to technological advancements.
PROGRAM SPECIFIC OUTCOMES (PSOs)
After the completion of the course, B. Tech Computer Science and Engineering, the
graduates will have the following Program Specific Outcomes:
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting
time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab
with the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any)
needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation
note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the
lab sessions.Misuse of the equipment, misbehaviors with the staff and systems etc., will
attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out ; if
anybody found loitering outside the lab / class without permission during working hours
will be treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system /
seat is kept properly.
Objectives:
Outcomes:
S. No Topic Page no
Write a program that uses functions to perform the
1 following operations on singly linked list i) Creation ii) 1
Insertion iii) Deletion iv) Traversal.
Write a program that uses functions to perform the
2 following operations on doubly linked list i) Creation ii) 10
Insertion iii) Deletion iv) Traversal.
Write a program that uses functions to perform the
3 following operations on circular linked List i) Creation ii) 19
Insertion iii) Deletion iv) Traversal.
Write a program that implement stack (its operations)
4 26
using i) Arrays ii) Linked list(Pointers).
Write a program that implement Queue (its operations)
5 35
using i) Arrays ii) Linked list(Pointers).
i)Write a program that implement Circular Queue (its
operations) using Arrays .
ii) Write a program that uses both recursive and non
6 42
recursive functions to perform the following searching
operations for a Key value in a given list of integers:
a) Linear search b) Binary search.
Write a program that implements the following sorting
7 52
i) Bubble sort ii) Selection sort iii)Quick sort.
Write a program that implements the following
8 59
i) Insertion sort ii) Merge sort iii)Heap sort.
Write a program to implement all the functions of a
9 67
dictionary (ADT)using Linked List.
Write a program to perform the following operations:
a) Insert an element into a binary search tree.
10 73
b) Delete an element from a binary search tree.
c) Search for a key element in a binary search tree.
11 Write a program to implement the tree traversal methods. 82
Write a program to perform the following operations:
a) Insert an element into a AVL tree.
12 89
b) Delete an element from a AVL tree.
c) Search for a key element in a AVL tree.
Data Structures Lab Manual & Record MRCET
WEEK - 1
Write a program that uses functions to perform the following operations on singly
linked list i) Creation ii) Insertion iii) Deletion iv) Traversal.
PROGRAM:
#include<iostream>
#include<windows.h>
#include<conio.h>
using namespace std;
class list
{
struct node
{
int data;
node *link;
}*p;
public:
void inslast(int);
void insbeg(int);
void insnext(int,int);
void delelement(int);
void delbeg();
void dellast();
void disp();
int seek(int);
list(){p=NULL;}
~list();
};
void list::inslast(int x)
{
node *q,*t;
if(p==NULL)
{
p=new node;
p->data=x;
p->link=NULL;
}
else
{
q=p;
while(q->link!=NULL)
q=q->link;
t=new node;
t->data=x;
t->link=NULL;
q->link=t;
}
cout<<"Inserted successfully at the end..";
disp();
}
void list::delelement(int x)
{
node *q,*r;
q=p;
if(q->data==x)
{
p=q->link;
delete q;
return;
}
r=q;
while(q!=NULL)
{
if(q->data==x)
{
r->link=q->link;
delete q;
return;
}
r=q;
q=q->link;
}
cout<<" Element u entered "<<x<<" is not found..";
}
void list:: delbeg()
{
cout<<" The list before deletion:";
disp();
node *q;
q=p;
if(q==NULL)
{
cout<<" No data is present..";
return;
}
p=q->link;
delete q;
return;
}
disp();
node *q,*t;
q=p;
if(q==NULL)
{
cout<<" There is no data in the list..";
return;
}
if(q->link==NULL)
{
p=q->link;
delete q;
return;
}
while(q->link->link!=NULL)
q=q->link;
q->link=NULL;
return;
}
list::~list()
{
node *q;
if(p==NULL) return;
while(p!=NULL)
{
q=p->link;
delete p;
p=q;
}
}
void list::disp()
{
node *q;
q=p;
if(q==NULL)
{
cout<<" No data is in the list..";
return;
}
cout<<" The items present in the list are :";
while(q!=NULL)
{
cout<<""<<q->data;
q=q->link;
}
}
int main()
{
list l;
int ch,v,p,ps;
do
{
system("cls");
cout<<" Operations on List..";
cout<<"1.Insertion 2.Deletion 3.Display 4.Seek 5.Exit";
cout<<" Enter ur choice:";
cin>>ch;
switch(ch)
{
case 1:
cout<<"1.Insertion at begining\n2.Insertion at the end";
cout<<"3.Insertion after the mentioned position";
cout<<" Enter ur choice:";
cin>>ps;
cout<<" Enter the value to insert:";
cin>>v;
switch(ps)
{
case 1:
l.insbeg(v);
break;
case 2:
l.inslast(v);
break;
case 3:
cout<<" Enter the position to insert the value:";
cin>>p;
l.insnext(v,p);
break;
default:
cout<<" The choice is invalid";
return 0;
}
break;
case 2:
cout<<"1.Delete the first element\n2.Delete the last element";
cout<<"\n3.Enter the element to delete from the list";
cout<<" \nEnter ur choice:";
cin>>ps;
switch(ps)
{
case 1:
l.delbeg();
cout<<" The list after deletion:";
l.disp();
break;
case 2:
l.dellast();
cout<<" The list after deletion:";
l.disp();
break;
case 3:
l.disp();
cout<<" Enter the element to delete : ";
cin>>v;
l.delelement(v);
cout<<" The list after deletion:";
l.disp();
break;
default:
cout<<" The option is invalid...";
break;
}
break;
case 3:
l.disp();
break;
case 4:
l.disp();
cout<<" Enter the element to search:";
cin>>v;
cout<<" The position of the element "<< v<<" is "<<l.seek(v);
getch();
break;
case 5:
exit(1);
default:
cout<<" The option is invalid...";
return 0;
}
getch();
}while(ch!=5);
getch();
return 0;
}
Sample output
Record Notes
Record Notes
Record Notes
Week - 2
Write a program that uses functions to perform the following operations on doubly
linked list i) Creation ii) Insertion iii) Deletion iv) Traversal.
Program:
#include<iostream>
#include<cstdio>
#include<cstdlib>
/*
* Node Declaration
*/
using namespace std;
struct node
{
int info;
struct node *next;
struct node *prev;
}*start;
/*
Class Declaration
*/
class double_llist
{
public:
void create_list(int value);
void add_begin(int value);
void add_after(int value, int position);
void delete_element(int value);
void search_element(int value);
void display_dlist();
void count();
void reverse();
double_llist()
{
start = NULL;
}
};
/*
* Main: Conatins Menu
*/
int main()
{
int choice, element, position;
double_llist dl;
while (1)
{
cout<<endl<<"----------------------------"<<endl;
cout<<endl<<"Operations on Doubly linked list"<<endl;
cout<<endl<<"----------------------------"<<endl;
cout<<"1.Create Node"<<endl;
cout<<"2.Add at begining"<<endl;
cout<<"3.Add after position"<<endl;
cout<<"4.Delete"<<endl;
cout<<"5.Display"<<endl;
cout<<"6.Count"<<endl;
cout<<"7.Reverse"<<endl;
cout<<"8.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch ( choice )
{
case 1:
cout<<"Enter the element: ";
cin>>element;
dl.create_list(element);
cout<<endl;
break;
case 2:
cout<<"Enter the element: ";
cin>>element;
dl.add_begin(element);
cout<<endl;
break;
case 3:
cout<<"Enter the element: ";
cin>>element;
cout<<"Insert Element after postion: ";
cin>>position;
dl.add_after(element, position);
cout<<endl;
break;
case 4:
if (start == NULL)
{
cout<<"List empty,nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
dl.delete_element(element);
cout<<endl;
break;
case 5:
dl.display_dlist();
cout<<endl;
break;
case 6:
dl.count();
break;
case 7:
if (start == NULL)
{
cout<<"List empty,nothing to reverse"<<endl;
break;
}
dl.reverse();
cout<<endl;
break;
case 8:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
return 0;
}
/*
* Create Double Link List
*/
void double_llist::create_list(int value)
{
struct node *s, *temp;
temp = new(struct node);
temp->info = value;
temp->next = NULL;
if (start == NULL)
{
temp->prev = NULL;
start = temp;
}
else
{
s = start;
while (s->next != NULL)
s = s->next;
s->next = temp;
temp->prev = s;
}
}
/*
* Insertion at the beginning
*/
void double_llist::add_begin(int value)
{
if (start == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->prev = NULL;
temp->info = value;
temp->next = start;
start->prev = temp;
start = temp;
cout<<"Element Inserted"<<endl;
}
/*
* Insertion of element at a particular position
*/
void double_llist::add_after(int value, int pos)
{
if (start == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *tmp, *q;
int i;
q = start;
for (i = 0;i < pos - 1;i++)
{
q = q->next;
if (q == NULL)
{
cout<<"There are less than ";
cout<<pos<<" elements."<<endl;
return;
}
}
tmp = new(struct node);
tmp->info = value;
if (q->next == NULL)
{
q->next = tmp;
tmp->next = NULL;
tmp->prev = q;
}
else
{
tmp->next = q->next;
tmp->next->prev = tmp;
q->next = tmp;
tmp->prev = q;
}
cout<<"Element Inserted"<<endl;
}
/*
* Deletion of element from the list
*/
void double_llist::delete_element(int value)
{
struct node *tmp, *q;
/*first element deletion*/
if (start->info == value)
{
tmp = start;
start = start->next;
start->prev = NULL;
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}
q = start;
while (q->next->next != NULL)
{
/*Element deleted in between*/
if (q->next->info == value)
{
tmp = q->next;
q->next = tmp->next;
tmp->next->prev = q;
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}
q = q->next;
}
/*last element deleted*/
if (q->next->info == value)
{
tmp = q->next;
free(tmp);
q->next = NULL;
cout<<"Element Deleted"<<endl;
return;
}
cout<<"Element "<<value<<" not found"<<endl;
}
/*
* Display elements of Doubly Link List
*/
void double_llist::display_dlist()
{
struct node *q;
if (start == NULL)
{
cout<<"List empty,nothing to display"<<endl;
return;
}
q = start;
cout<<"The Doubly Link List is :"<<endl;
while (q != NULL)
{
cout<<q->info<<" <-> ";
q = q->next;
}
cout<<"NULL"<<endl;
}
/*
* Number of elements in Doubly Link List
*/
void double_llist::count()
{
struct node *q = start;
int cnt = 0;
while (q != NULL)
{
q = q->next;
cnt++;
}
cout<<"Number of elements are: "<<cnt<<endl;
}
/*
* Reverse Doubly Link List
*/
void double_llist::reverse()
{
struct node *p1, *p2;
p1 = start;
p2 = p1->next;
p1->next = NULL;
p1->prev = p2;
while (p2 != NULL)
{
p2->prev = p2->next;
p2->next = p1;
p1 = p2;
p2 = p2->prev;
}
start = p1;
cout<<"List Reversed"<<endl;
}
Sample Out:
Record Notes
Record Notes
Record Notes
Week - 3
Write a program that uses functions to perform the following operations on circular
linked List i) Creation ii) Insertion iii) Deletion iv) Traversal.
Program:
#include<iostream>
#include<windows.h>
#include<conio.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
//insert a new node in an empty list
struct Node *insertInEmpty(struct Node *last, int new_data)
{
// if last is not null then list is not empty, so return
if (last != NULL)
return last;
return last;
}
//insert new node at the beginning of the list
struct Node *insertAtBegin(struct Node *last, int new_data)
{
//if list is empty then add the node by calling insertInEmpty
if (last == NULL)
return insertInEmpty(last, new_data);
return last;
}
//insert new node at the end of the list
return last;
}
if (p == last)
last = temp;
return last;
}
p = p -> next;
} while(p != last -> next);
cout << "The node with data "<<after_item << " is not present in the list." << endl;
return last;
}
//traverse the circular linked list
void traverseList(struct Node *last) {
struct Node *p;
// Traverse the list starting from first node until first node is visited again
do {
cout << p -> data << "==>";
p = p -> next;
} while(p != last->next);
if(p == last->next)
cout<<p->data;
cout<<"\n\n";
}
// If the list contains only a single node,delete that node; list is empty
if((*head)->data==key && (*head)->next==*head) {
free(*head);
*head=NULL;
}
Node *last=*head,*d;
// main Program
int main()
{
struct Node *last = NULL;
Sample Output:
Record Notes
Record Notes
Record Notes
Week - 4
Write a program that implements stack (its operations) using i) Arrays ii) Linked list
(Pointers).
Aim: To write a C++ program to implement stack operations using Arrays and Linked lists.
Program:
i) Using Arrays:
# include<iostream>
using namespace std;
class Stack
{
int top;
public:
int a[10]; //Maximum size of Stack
Stack()
{
top = -1;
}
if(top < 0)
{
cout << "Stack Underflow \n";
return 0;
}
else
{
int d = a[top--];
return d;
}
}
// main function
int main() {
Stack s1;
int ch;
int num;
while(1)
{
switch(ch)
{
case 1:
cout<<"Enter Element to be inserted:";
cin>>num;
s1.push(num);
break;
case 2:
cout<<"Element deleted from stack="<<s1.pop();
break;
case 3:
s1.display();
break;
case 4:
exit(0);
}
}
Sample Output:
#include<iostream>
#include<cstdlib>
using namespace std;
/*
* Node Declaration
*/
struct node
{
int info;
struct node *link;
}*top;
/*
* Class Declaration
*/
class stack_list
{
public:
node *push(node *, int);
node *pop(node *);
void traverse(node *);
stack_list()
{
top = NULL;
}
};
/*
* Main: Contains Menu
*/
int main()
{
int choice, item;
stack_list sl;
while (1)
{
cout<<"\n-------------"<<endl;
cout<<"Operations on Stack"<<endl;
cout<<"\n-------------"<<endl;
cout<<"1.Push Element into the Stack"<<endl;
cout<<"2.Pop Element from the Stack"<<endl;
cout<<"3.Traverse the Stack"<<endl;
cout<<"4.Quit"<<endl;
cout<<"Enter your Choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter value to be pushed into the stack: ";
cin>>item;
top = sl.push(top, item);
break;
case 2:
top = sl.pop(top);
break;
case 3:
sl.traverse(top);
break;
case 4:
exit(1);
break;
default:
cout<<"Wrong Choice"<<endl;
}
}
return 0;
}
/*
* Push Element into the Stack
*/
node *stack_list::push(node *top, int item)
{
node *tmp;
tmp = new (struct node);
tmp->info = item;
tmp->link = top;
top = tmp;
return top;
}
/*
* Pop Element from the Stack
*/
node *stack_list::pop(node *top)
{
node *tmp;
if (top == NULL)
cout<<"Stack is Empty"<<endl;
else
{
tmp = top;
cout<<"Element Popped: "<<tmp->info<<endl;
top = top->link;
delete(tmp);
}
return top;
}
/*
* Traversing the Stack
*/
void stack_list::traverse(node *top)
{
node *ptr;
ptr = top;
if (top == NULL)
cout<<"Stack is empty"<<endl;
else
{
cout<<"Stack elements :"<<endl;
while (ptr != NULL)
{
cout<<ptr->info<<endl;
ptr = ptr->link;
}
}
}
Sample Output:
Record Notes
Record Notes
Record Notes
Week - 5
Write a program that implements Queue (its operations) using i) Arrays ii) Linked
list (Pointers).
Aim: To write a C++ program to implement Queue operations using Arrays and Linked lists.
Program:
i) Using Arrays:
#include <iostream>
using namespace std;
int queue[100], n = 100, front = - 1, rear = - 1;
void Insert() {
int val;
if (rear == n - 1)
cout<<"Queue Overflow"<<endl;
else {
if (front == - 1)
front = 0;
cout<<"Insert the element in queue : "<<endl;
cin>>val;
rear++;
queue[rear] = val;
}
}
void Delete() {
if (front == - 1 || front > rear) {
cout<<"Queue Underflow ";
return ;
} else {
cout<<"Element deleted from queue is : "<< queue[front] <<endl;
front++;;
}
}
void Display() {
if (front == - 1)
cout<<"Queue is empty"<<endl;
else {
cout<<"Queue elements are : ";
for (int i = front; i <= rear; i++)
cout<<queue[i]<<" ";
cout<<endl;
}
}
int main() {
int ch;
cout<<"1) Insert element to queue"<<endl;
cout<<"2) Delete element from queue"<<endl;
cout<<"3) Display all the elements of queue"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter your choice : "<<endl;
cin>>ch;
switch (ch) {
case 1: Insert();
break;
case 2: Delete();
break;
case 3: Display();
break;
case 4: cout<<"Exit"<<endl;
break;
default: cout<<"Invalid choice"<<endl;
}
} while(ch!=4);
return 0;
}
Sample Output:
#include <iostream>
#include<windows.h>
using namespace std;
struct node {
int data;
struct node *next;
};
struct node* front = NULL;
struct node* rear = NULL;
struct node* temp;
void Insert() {
int val;
cout<<"Insert the element in queue : "<<endl;
cin>>val;
if (rear == NULL) {
rear = (struct node *)malloc(sizeof(struct node));
rear->next = NULL;
rear->data = val;
front = rear;
} else {
temp=(struct node *)malloc(sizeof(struct node));
rear->next = temp;
temp->data = val;
temp->next = NULL;
rear = temp;
}
}
void Delete() {
temp = front;
if (front == NULL) {
cout<<"Underflow"<<endl;
return;
}
else
if (temp->next != NULL) {
temp = temp->next;
cout<<"Element deleted from queue is : "<<front->data<<endl;
free(front);
front = temp;
} else {
cout<<"Element deleted from queue is : "<<front->data<<endl;
free(front);
front = NULL;
rear = NULL;
}
}
void Display() {
temp = front;
if ((front == NULL) && (rear == NULL)) {
cout<<"Queue is empty"<<endl;
return;
}
cout<<"Queue elements are: ";
while (temp != NULL) {
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
int main() {
int ch;
cout<<"1) Insert element to queue"<<endl;
cout<<"2) Delete element from queue"<<endl;
cout<<"3) Display all the elements of queue"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter your choice : "<<endl;
cin>>ch;
switch (ch) {
case 1: Insert();
break;
case 2: Delete();
break;
case 3: Display();
break;
case 4: cout<<"Exit"<<endl;
break;
default: cout<<"Invalid choice"<<endl;
}
} while(ch!=4);
return 0;
}
Sample Output:
Record Notes
Record Notes
Record Notes
Week - 6
i)Write a program that implement Circular Queue (its operations) using Arrays .
ii) Write a program that uses both recursive and non recursive functions to
perform the following searching operations for a Key value in a given list of
integers:
a) Linear search b) Binary search
Aim: To write a C++ program to implement Circular queues operations using Arrays.
Programs:
i) Circular Queue:
#include <iostream>
using namespace std;
int cqueue[5];
int front = -1, rear = -1, n=5;
if (front == rear) {
front = -1;
rear = -1;
} else {
if (front == n - 1)
front = 0;
else
front = front + 1;
}
}
void displayCQ() {
int f = front, r = rear;
if (front == -1) {
cout<<"Queue is empty"<<endl;
return;
}
cout<<"Queue elements are :\n";
if (f <= r) {
while (f <= r){
cout<<cqueue[f]<<" ";
f++;
}
} else {
while (f <= n - 1) {
cout<<cqueue[f]<<" ";
f++;
}
f = 0;
while (f <= r) {
cout<<cqueue[f]<<" ";
f++;
}
}
cout<<endl;
}
int main() {
case 2:
deleteCQ();
break;
case 3:
displayCQ();
break;
case 4:
cout<<"Exit\n";
break;
default: cout<<"Incorrect!\n";
}
} while(ch != 4);
return 0;
}
Sample Output:
Aim: To write a C++ program to perform Linear Search using non-recursive function.
Program:
#include<iostream>
using namespace std;
int Lsearch(int list[ ],int n,int key);
int main()
{
int n,i,key,list[25],pos;
cout<<"enter no of elements\n";
cin>>n;
cout<<"enter "<<n<<" elements ";
for(i=0;i<n;i++)
cin>>list[i];
cout<<"enter key to search";
cin>>key;
pos= Lsearch (list,n,key);
if(pos==-1)
cout<<"\nelement not found";
else
cout<<"\n element found at index "<<pos;
}
/*function for linear search*/
int Lsearch(int list[],int n,int key)
{
int i,pos=-1;
for(i=0;i<n;i++)
if(key==list[i])
{
pos=i;
break;
}
return pos;
}
Sample Output:
Aim: To write a C++ program to perform Linear Search using recursive function.
Program:
#include<iostream>
using namespace std;
int Rec_Lsearch(int list[ ],int n,int key);
int main()
{
int n,i,key,list[25],pos;
cout<<"enter no of elements\n";
cin>>n;
cout<<"enter "<<n<<" elements ";
for(i=0;i<n;i++)
cin>>list[i];
cout<<"enter key to search";
cin>>key;
pos=Rec_Lsearch(list,n,key);
if(pos==-1)
cout<<"\nelement not found";
else
cout<<"\n element found at index "<<pos;
}
/*recursive function for linear search*/
int Rec_Lsearch(int list[],int n,int key)
{
if(n<=0)
return -1;
if(list[n]==key)
return n;
else
return Rec_Lsearch(list,n-1,key);
Sample Output:
Aim: To write a C++ program to perform Binary Search using non-recursive function.
Program:
#include<iostream>
using namespace std;
int binary_search(int list[],int key,int low,int high);
int main()
{
int n,i,key,list[25],pos;
cout<<"enter no of elements\n" ;
cin>>n;
cout<<"enter "<<n<<" elements in ascending order ";
for(i=0;i<n;i++)
cin>>list[i];
cout<<"enter key to search" ;
cin>>key;
pos=binary_search(list,key,0,n-1);
if(pos==-1)
cout<<"element not found" ;
else
cout<<"element found at index "<<pos;
}
/* function for binary search*/
int binary_search(int list[],int key,int low,int high)
{
int mid,pos=-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==list[mid])
{
pos=mid;
break;
}
else if(key<list[mid])
high=mid-1;
else
low=mid+1;
}
return pos;
}
Sample Output:
Aim: To write a C++ program to perform Binary Search using recursive function.
Program:
#include<iostream>
using namespace std;
int rbinary_search(int list[],int key,int low,int high);
int main()
{
int n,i,key,list[25],pos;
cout<<"enter no of elements\n" ;
cin>>n;
cout<<"enter "<<n<<" elements in ascending order ";
for(i=0;i<n;i++)
cin>>list[i];
cout<<"enter key to search" ;
cin>>key;
pos=rbinary_search(list,key,0,n-1);
if(pos==-1)
cout<<"element not found" ;
else
cout<<"element found at index "<<pos;
}
/*recursive function for binary search*/
int rbinary_search(int list[ ],int key,int low,int high)
{
int mid,pos=-1;
if(low<=high)
{
mid=(low+high)/2;
if(key==list[mid])
{
pos=mid;
return pos;
}
else if(key<list[mid])
return rbinary_search(list,key,low,mid-1);
else
return rbinary_search(list,key,mid+1,high);
}
return pos;
}
Sample Output:
Record Notes
Record Notes
Record Notes
Week - 7
Write a program that implements the following sorting
i) Bubble sort ii) Selection sort iii) Quick sort.
i) Bubble Sort:
Program:
#include<iostream>
using namespace std;
void bubble_sort(int list[30],int n);
int main()
{
int n,i;
int list[30];
cout<<"enter no of elements\n";
cin>>n;
cout<<"enter "<<n<<" numbers ";
for(i=0;i<n;i++)
cin>>list[i];
bubble_sort (list,n);
cout<<" after sorting\n";
for(i=0;i<n;i++)
cout<<list[i]<<endl;
return 0;
}
void bubble_sort (int list[30],int n)
{
int temp ;
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n-1;j++)
if(list[j]>list[j+1])
{
temp=list[j];
list[j]=list[j+1];
list[j+1]=temp;
}
}
Sample output:
Program:
#include<iostream>
using namespace std;
void selection_sort (int list[],int n);
int main()
{
int n,i;
int list[30];
cout<<"enter no of elements\n";
cin>>n;
cout<<"enter "<<n<<" numbers ";
for(i=0;i<n;i++)
cin>>list[i];
selection_sort (list,n);
cout<<" after sorting\n";
for(i=0;i<n;i++)
cout<<list[i]<<endl;
return 0;
}
void selection_sort (int list[],int n)
{
int min,temp,i,j;
for(i=0;i<n;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(list[j]<list[min])
min=j;
}
temp=list[i];
list[i]=list[min];
list[min]=temp;
}
}
Sample output:
Program:
#include<iostream>
using namespace std;
void quicksort(int x[],int Lb,int Ub)
{
int down,up,pivot,t;
if(Lb<Ub)
{
down=Lb;
up=Ub;
pivot=down;
while(down<up)
{
while((x[down]<=x[pivot])&&(down<Ub))down++;
while(x[up]>x[pivot])up--;
if(down<up)
{
t=x[down];
x[down]=x[up];
x[up]=t;
}/*endif*/
}
t=x[pivot];
x[pivot]=x[up];
x[up]=t;
quicksort( x,Lb,up-1);
quicksort( x,up+1,Ub);
}
}
int main()
{
int n,i;
int list[30];
cout<<"enter no of elements\n";
cin>>n;
cout<<"enter "<<n<<" numbers ";
for(i=0;i<n;i++)
cin>>list[i];
quicksort(list,0,n-1);
cout<<" after sorting\n";
for(i=0;i<n;i++)
cout<<list[i]<<endl;
return 0;
}
Sample output:
Record Notes
Record Notes
Record Notes
Week - 8
Write a program that implements the following
i) Insertion sort ii) Merge sort iii) Heap sort
i) Insertion Sort:
Program:
#include<iostream>
using namespace std;
void insertion_sort(int a[],int n)
{
int i,t,pos;
for(i=0;i<n;i++)
{
t=a[i];
pos=i;
while(pos>0&&a[pos-1]>t)
{
a[pos]=a[pos-1];
pos--;
}
a[pos]=t;
}
}
int main()
{
int n,i;
int list[30];
cout<<"enter no of elements\n";
cin>>n;
cout<<"enter "<<n<<" numbers ";
for(i=0;i<n;i++)
cin>>list[i];
insertion_sort(list,n);
cout<<" after sorting\n";
for(i=0;i<n;i++)
cout<<list[i]<<endl;
return 0;
}
Sample Output:
Program:
#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void merge(int *array, int l, int m, int r) {
int i, j, k, nl, nr;
//size of left and right sub-arrays
nl = m-l+1; nr = r-m;
int larr[nl], rarr[nr];
//fill left and right sub-arrays
for(i = 0; i<nl; i++)
larr[i] = array[l+i];
for(j = 0; j<nr; j++)
rarr[j] = array[m+1+j];
i = 0; j = 0; k = l;
//marge temp arrays to real array
while(i < nl && j<nr) {
if(larr[i] <= rarr[j]) {
array[k] = larr[i];
i++;
}else{
array[k] = rarr[j];
j++;
}
k++;
}
while(i<nl) { //extra element in left array
array[k] = larr[i];
i++; k++;
}
while(j<nr) { //extra element in right array
array[k] = rarr[j];
j++; k++;
}
}
void mergeSort(int *array, int l, int r) {
int m;
if(l < r) {
int m = l+(r-l)/2;
// Sort first and second arrays
mergeSort(array, l, m);
mergeSort(array, m+1, r);
merge(array, l, m, r);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
mergeSort(arr, 0, n-1); //(n-1) for last index
cout << "Array after Sorting: ";
display(arr, n);
}
Sample Output:
Program:
#include <iostream>
using namespace std;
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
swap(arr[i], arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// main function to do heap sort
void heapSort(int arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--)
{
// Move current root to end
swap(arr[0], arr[i]);
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
/* A utility function to print array of size n */
void printArray(int arr[], int n)
{
for (int i=0; i<n; ++i)
cout << arr[i] << " ";
cout << "\n";
}
int main()
{
int n,i;
int list[30];
cout<<"enter no of elements\n";
cin>>n;
cout<<"enter "<<n<<" numbers ";
for(i=0;i<n;i++)
cin>>list[i];
heapSort(list, n);
cout << "Sorted array is \n";
printArray(list, n);
return 0;
}
Sample Output:
Record Notes
Record Notes
Record Notes
Week - 9
Write a program to implement all the functions of a dictionary (ADT)using Linked
List.
Aim: To write a C++ program to implement functions of Dictionary ADT using Linked List.
Program:
#include<stdlib.h>
#include<iostream>
using namespace std;
class node
{
public: int key;
int value;
node*next;
};
class dictionary:public node
{ int k,data;
node *head;
public: dictionary();
void insert_d();
void delete_d();
void display_d();
};
dictionary::dictionary()
{ head=NULL;
}
//code to push an val into dictionary;
void dictionary::insert_d()
{
node *p,*curr,*prev;
cout<<"Enter an key and value to be inserted:";
cin>>k;
cin>>data;
p=new node;
p->key=k;
p->value=data;
p->next=NULL;
if(head==NULL)
head=p;
else
{
curr=head;
while((curr->key<p->key)&&(curr->next!=NULL))
{ prev=curr;
curr=curr->next;
}
if(curr->next==NULL)
{
if(curr->key<p->key)
{ curr->next=p;
prev=curr;
}
else { p->next=prev->next;
prev->next=p;
}
}
else
{
p->next=prev->next;
prev->next=p;
}
cout<<"\nInserted into dictionary Sucesfully....\n";
}
}
void dictionary::delete_d( )
{
node*curr,*prev;
cout<<"Enter key value that you want to delete...";
cin>>k;
if(head==NULL)
cout<<"\ndictionary is Underflow";
else
{ curr=head;
while(curr!=NULL)
{
if(curr->key==k)
break;
prev=curr;
curr=curr->next;
}
}
if(curr==NULL)
cout<<"Node not found...";
else
{
if(curr==head)
head=curr->next;
else
prev->next=curr->next;
delete curr;
cout<<"Item deleted from dictionary...";
}
}
void dictionary::display_d( )
{
node*t;
if(head==NULL)
cout<<"\ndictionary Under Flow";
else
{
cout<<"\nElements in the dictionary are....\n";
t=head;
while(t!=NULL)
{
cout<<"<"<<t->key<<","<<t->value<<">";
t=t->next;
}
}
}
int main( )
{
int choice;
dictionary d1;
while(1)
{
cout<<"\n\n***Menu for Dictrionay operations***\n\n";
cout<<"1.Insert\n2.Delete\n3.DISPLAY\n4.EXIT\n";
cout<<"Enter Choice:";
cin>>choice;
switch(choice)
{
case 1: d1.insert_d();
break;
case 2: d1.delete_d( );
break;
case 3: d1.display_d( );
break;
case 4: exit(0);
default:cout<<"Invalid choice...Try again...\n";
}
}
}
Sample Output:
Record Notes
Record Notes
Record Notes
Week - 10
Write a program to perform the following operations:
a) Insert an element into a binary search tree.
b) Delete an element from a binary search tree.
c) Search for a key element in a binary search tree.
Aim: To write a C++ program to perform insert, delete and search operations on Binary Search
Tree.
Program:
# include <iostream>
# include <cstdlib>
using namespace std;
struct nod//node declaration
{
int info;
struct nod *l;
struct nod *r;
}*r;
class BST
{
public://functions declaration
void search(nod *, int);
void insert(nod *, nod *);
void del(int);
void casea(nod *,nod *);
void caseb(nod *,nod *);
void casec(nod *,nod *);
void find(int, nod **, nod **);
void show(nod *, int);
BST()
{
r = NULL;
}
};
void BST::casea(nod *par, nod *loc )
{
if (par == NULL)
{
r= NULL;
}
else
{
if (loc == par->l)
par->l = NULL;
else
par->r = NULL;
}
}
void BST::caseb(nod *par, nod *loc)
{
nod *child;
if (loc->l!= NULL)
child = loc->l;
else
child = loc->r;
if (par == NULL)
{
r = child;
}
else
{
if (loc == par->l)
par->l = child;
else
par->r = child;
}
}
void BST::casec(nod *par, nod *loc)
{
nod *ptr, *ptrsave, *suc, *parsuc;
ptrsave = loc;
ptr = loc->r;
while (ptr->l!= NULL)
{
ptrsave = ptr;
ptr = ptr->l;
}
suc = ptr;
parsuc = ptrsave;
if (suc->l == NULL && suc->r == NULL)
casea(parsuc, suc);
else
caseb(parsuc, suc);
if (par == NULL)
{
r = suc;
}
else
{
if (loc == par->l)
par->l = suc;
else
par->r= suc;
}
suc->l = loc->l;
suc->r= loc->r;
}
void BST::search(nod *root, int data) //searching
{
int depth = 0;
nod *temp = new nod;
temp = root;
while(temp != NULL)
{
depth++;
if(temp->info == data)
{
}
}
void BST::find(int i, nod **par, nod **loc)//find the position of the item
{
nod *ptr, *ptrsave;
if (r == NULL)
{
*loc = NULL;
*par = NULL;
return;
}
if (i == r->info)
{
*loc = r;
*par = NULL;
return;
}
if (i < r->info)
ptr = r->l;
else
ptr = r->r;
ptrsave = r;
while (ptr != NULL)
{
if (i == ptr->info)
{
*loc = ptr;
*par = ptrsave;
return;
}
ptrsave = ptr;
if (i < ptr->info)
ptr = ptr->l;
else
ptr = ptr->r;
}
*loc = NULL;
*par = ptrsave;
}
void BST::del(int i)
{
nod *par, *loc;
if (r == NULL)
{
cout<<"Tree empty"<<endl;
return;
}
find(i, &par, &loc);
if (loc == NULL)
{
cout<<"Item not present in tree"<<endl;
return;
}
if (loc->l == NULL && loc->r == NULL)
{
casea(par, loc);
cout<<"item deleted"<<endl;
}
if (loc->l!= NULL && loc->r == NULL)
{
caseb(par, loc);
cout<<"item deleted"<<endl;
}
if (loc->l== NULL && loc->r != NULL)
{
caseb(par, loc);
cout<<"item deleted"<<endl;
}
if (loc->l != NULL && loc->r != NULL)
{
casec(par, loc);
cout<<"item deleted"<<endl;
}
free(loc);
}
void BST::show(nod *ptr, int level)//print the tree
{
int i;
if (ptr != NULL)
{
show(ptr->r, level+1);
cout<<endl;
if (ptr == r)
cout<<"Root->: ";
else
{
for (i = 0;i < level;i++)
cout<<" ";
}
cout<<ptr->info;
show(ptr->l, level+1);
}
}
int main()
{
int c, n,item;
BST bst;
nod *t;
while (1)
{
cout<<"1.Insert Element "<<endl;
cout<<"2.Delete Element "<<endl;
cout<<"3.Search Element"<<endl;
cout<<"4.Display the tree"<<endl;
cout<<"5.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>c;
switch(c)
{
case 1:
t = new nod;
cout<<"Enter the number to be inserted : ";
cin>>t->info;
bst.insert(r, t);
break;
case 2:
if (r == NULL)
{
cout<<"Tree is empty, nothing to delete"<<endl;
continue;
}
cout<<"Enter the number to be deleted : ";
cin>>n;
bst.del(n);
break;
case 3:
cout<<"Search:"<<endl;
cin>>item;
bst.search(r,item);
break;
case 4:
cout<<"Display BST:"<<endl;
bst.show(r,1);
cout<<endl;
break;
case 5:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
}
Sample Output:
Record Notes
Record Notes
Record Notes
Week - 11
Write a program to implement the tree traversal methods.
Program:
# include <iostream>
# include <cstdlib>
using namespace std;
struct nod//node declaration
{
int info;
struct nod *l;
struct nod *r;
}*r;
class BST
{
public://functions declaration
void insert(nod *, nod *);
void preorder(nod *);
void inorder(nod *);
void postorder(nod *);
void show(nod *, int);
BST()
{
r = NULL;
}
};
void BST::insert(nod *tree, nod *newnode)
{
if (r == NULL)
{
r = new nod;
r->info = newnode->info;
r->l= NULL;
r->r= NULL;
cout<<"Root Node is Added"<<endl;
return;
}
if (tree->info == newnode->info)
{
cout<<"Element already in the tree"<<endl;
return;
}
if (tree->info > newnode->info)
{
if (tree->l != NULL)
{
insert(tree->l, newnode);
}
else
{
tree->l= newnode;
(tree->l)->l = NULL;
(tree->l)->r= NULL;
cout<<"Node Added To Left"<<endl;
return;
}
}
else
{
if (tree->r != NULL)
{
insert(tree->r, newnode);
}
else
{
tree->r = newnode;
(tree->r)->l= NULL;
(tree->r)->r = NULL;
cout<<"Node Added To Right"<<endl;
return;
}
}
}
void BST::preorder(nod *ptr)
{
if (r == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
cout<<ptr->info<<" ";
preorder(ptr->l);
preorder(ptr->r);
}
}
void BST::inorder(nod *ptr)//inorder traversal
{
if (r == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
inorder(ptr->l);
cout<<ptr->info<<" ";
inorder(ptr->r);
}
}
void BST::postorder(nod *ptr)//postorder traversal
{
if (r == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
postorder(ptr->l);
postorder(ptr->r);
cout<<ptr->info<<" ";
}
}
void BST::show(nod *ptr, int level)//print the tree
{
int i;
if (ptr != NULL)
{
show(ptr->r, level+1);
cout<<endl;
if (ptr == r)
cout<<"Root->: ";
else
{
for (i = 0;i < level;i++)
cout<<" ";
}
cout<<ptr->info;
show(ptr->l, level+1);
}
}
int main()
{
int c, n,item;
BST bst;
nod *t;
while (1)
{
cout<<"1.Insert Element "<<endl;
cout<<"2.Inorder Traversal"<<endl;
cout<<"3.Preorder Traversal"<<endl;
cout<<"4.Postorder Traversal"<<endl;
cout<<"5.Display the tree"<<endl;
cout<<"6.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>c;
switch(c)
{
case 1:
t = new nod;
cout<<"Enter the number to be inserted : ";
cin>>t->info;
bst.insert(r, t);
break;
case 2:
cout<<"Inorder Traversal of BST:"<<endl;
bst.inorder(r);
cout<<endl;
break;
case 3:
cout<<"Preorder Traversal of BST:"<<endl;
bst.preorder(r);
cout<<endl;
break;
case 4:
cout<<"Postorder Traversal of BST:"<<endl;
bst.postorder(r);
cout<<endl;
break;
case 5:
cout<<"Display BST:"<<endl;
bst.show(r,1);
cout<<endl;
break;
case 6:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
}
Sample Output:
Record Notes
Record Notes
Record Notes
Week - 12
Write a program to perform the following operations:
a) Insert an element into an AVL tree.
b) Delete an element from an AVL tree.
c) Search for a key element in an AVL tree.
Aim: To write a C++ program to perform insert, delete and search operations on AVL tree.
Program:
# include <iostream>
# include <stdlib.h>
# include <conio.h>
using namespace std;
struct node
{
int element;
node *left;
node *right;
int height;
};
typedef struct node *np;
class bstree
{
public:
void insert(int,np &);
void del(int, np &);
int deletemin(np &);
void find(int,np &);
int bsheight(np);
np srl(np &);
np drl(np &);
np srr(np &);
np drr(np &);
};
int bstree::deletemin(np &p)
{
int c;
cout<<"inside deltemin";
if (p->left == NULL)
{
c=p->element;
p=p->right;
return c;
}
else
{
c=deletemin(p->left);
return c;
}
}
int bstree::bsheight(np p)
{
int t;
if (p == NULL)
return -1;
else
{
t = p->height;
return t;
}
}
np bstree:: srl(np &p1)
{
np p2;
p2 = p1->left;
p1->left = p2->right;
p2->right = p1;
p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1;
p2->height = max(bsheight(p2->left),p1->height) + 1;
return p2;
}
np bstree:: srr(np &p1)
{
np p2;
p2 = p1->right;
p1->right = p2->left;
p2->left = p1;
p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1;
p2->height = max(p1->height,bsheight(p2->right)) + 1;
return p2;
}
np bstree:: drl(np &p1)
{
p1->left=srr(p1->left);
return srl(p1);
}
np bstree::drr(np &p1)
{
p1->right = srl(p1->right);
return srr(p1);
}
// Inserting a node
void bstree::insert(int x,np &p)
{
if (p == NULL)
{
p = new node;
p->element = x;
p->left=NULL;
p->right = NULL;
p->height=0;
if (p==NULL)
cout<<"Out of Space";
}
else
{
if (x<p->element)
{
insert(x,p->left);
if ((bsheight(p->left) - bsheight(p->right))==2)
{
if (x < p->left->element)
p=srl(p);
else
p = drl(p);
}
}
else if (x>p->element)
{
insert(x,p->right);
if ((bsheight(p->right) - bsheight(p->left))==2)
{
if (x > p->right->element)
p=srr(p);
else
p = drr(p);
}
}
else
cout<<"Element Exists";
}
int m,n,d;
m=bsheight(p->left);
n=bsheight(p->right);
d=max(m,n);
p->height = d + 1;
}
// Deleting a node
void bstree::del(int x,np &p)
{
np d;
if (p==NULL)
cout<<"Element not found ";
else if ( x < p->element)
del(x,p->left);
else if (x > p->element)
del(x,p->right);
else if ((p->left == NULL) && (p->right == NULL))
{
d=p;
free(d);
p=NULL;
cout<<" Element deleted !";
}
else if (p->left == NULL)
{
d=p;
free(d);
p=p->right;
cout<<" Element deleted !";
}
else if (p->right == NULL)
{
d=p;
p=p->left;
free(d);
cout<<" Element deleted !";
}
else
p->element = deletemin(p->right);
}
//Finding an element
void bstree::find(int x,np &p)
{
if (p==NULL)
cout<<" Element not found ";
else
if (x < p->element)
find(x,p->left);
else
if (x>p->element)
find(x,p->right);
else
cout<<" Element found !";
}
int main()
{
//clrscr();
np root,root1,min,max;//,flag;
int a,choice,findele,delele,leftele,rightele,flag;
char ch='y';
bstree bst;
//system("clear");
root = NULL;
root1=NULL;
while(1)
{
cout<<" \nAVL Tree\n";
cout<<" ========\n";
cout<<"1.Insertion\n2.Find\n3.Delete\n4.Exit\n";
cout<<"Enter the choice:";
cin>>choice;
switch(choice)
{
case 1:
cout<<"New node's value ?";
cin>>a;
bst.insert(a,root);
break;
case 2:
cout<<"Search node : ";
cin>>findele;
if (root != NULL)
bst.find(findele,root);
break;
case 3:
cout<<"Delete Node ?";
cin>>delele;
bst.del(delele,root);
//bst.inorder(root);
break;
case 4:exit(0);
}
}
return 0;
}
Sample Output:
Record Notes
Record Notes
Record Notes