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

DSTCpp Lab Manual 2019

The document is a lab manual for Data Structures through C++ at St. Mary's Women's Engineering College, detailing various experiments such as linked lists, stacks, and sorting algorithms. It includes implementations for singly and doubly linked lists, as well as stack operations, with example C++ code provided for each. The manual serves as a practical guide for students to understand and apply data structure concepts using C++.

Uploaded by

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

DSTCpp Lab Manual 2019

The document is a lab manual for Data Structures through C++ at St. Mary's Women's Engineering College, detailing various experiments such as linked lists, stacks, and sorting algorithms. It includes implementations for singly and doubly linked lists, as well as stack operations, with example C++ code provided for each. The manual serves as a practical guide for students to understand and apply data structure concepts using C++.

Uploaded by

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

St.

Mary’s Womens Engineering College


(Approved by the AICTE, New Delhi and affiliated to JNTUK, Kakinada)

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY KAKINADA

Department of
COMPUTER SCIENCE AND ENGINEERING

DATA STRUCTURES Through C++ Lab Manual

2018-2019
Data Structures through C++ Lab

List of Experiments

1. Implementation of Singly linked list.


2. Implementation of Doubly linked list.
3. Implementation of Multistack in a Single Array.
4. Implementation of Circular Queue
5. Implementation of Binary Search trees.
6. Implementation of Hash table.
7. Implementation of Heaps.
8. Implementation of Breadth First Search Techniques.
9. Implementation of Depth First Search Techniques.
10. Implementation of Prim’s Algorithm.
11. Implementation of Dijkstra’s Algorithm.
12. Implementation of Kruskal’s Algorithm
13. Implementation of MergeSort
14. Implementation of Quick Sort
15. Implementation of Data Searching using divide and conquer
technique
Program 1: To Implement Single Linked List.
Single Linked List: Single linked list is a sequence of elements in which
every element has link to its next element in the sequence. In any single
linked list, the individual element is called as "Node". Every "Node"
contains two fields, data and next. The data field is used to store actual
value of that node and next field is used to store the address of the next
node in the sequence.

The graphical representation of a node in a single linked list is as follows...

NOTE:

☀ In a single linked list, the address of the first node is always stored in
a reference node known as "front" (Some times it is also known as
"head").
☀ Always next part (reference part) of the last node must be NULL.

Example

Program :

// C++ Program that uses functions to create a Singly Linked List.


#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
/* Node Declaration */
struct node
{
int info;
struct node *next;
} *start;

/* Class Declaration*/
class single_list
{
public:
node *create_node(int);
void insert_begin( );
void insert_pos( );
void insert_last( );
void delete_pos( );
void display( );
single_list( )
{
start = NULL;
}
};

/* Creating Node */
node *single_list::create_node(int value)
{
struct node *temp, *s;
temp = new(struct node);
if (temp == NULL)
{
cout<<"Memory not allocated "<<endl;
return 0;
}
else
{
temp->info = value;
temp->next = NULL;
return temp;
}
}

/* Inserting element in beginning */


void single_list::insert_begin()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *p;
temp = create_node(value);
if (start == NULL)
{
start = temp;
start->next = NULL;
}
else
{
p = start;
start = temp;
start->next = p;
}
cout<<"Element Inserted at beginning"<<endl;
}

/* Inserting Node at last */


void single_list::insert_last()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *s; temp
= create_node(value); s =
start;
while (s->next != NULL)
{
s = s->next;
}
temp->next = NULL;
s->next = temp;
cout<<"Element Inserted at last"<<endl;
}

/* Insertion of node at a given position */


void single_list::insert_pos()
{
int value, pos, counter = 0;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *s, *ptr;
temp = create_node(value);
cout<<"Enter the postion at which node to be inserted: ";
cin>>pos;
int i;
s = start;
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos == 1)
{
if (start == NULL)
{
start = temp;
start->next = NULL;
}
else
{
ptr = start;
start = temp;
start->next = ptr;
}
}

else if (pos > 1 && pos <= counter)


{
s = start;
for (i = 1; i < pos; i++)
{
ptr = s;
s = s->next;
}
ptr->next = temp;
temp->next = s;
}
else
{
cout<<"Positon out of range"<<endl;
}
}
/* Delete element at a given position */
void single_list::delete_pos()
{
int pos, i, counter = 0;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the position of value to be deleted: ";
cin>>pos;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start = s->next;
}
else
{
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos > 0 && pos <= counter)
{
s = start;
for (i = 1;i < pos;i++)
{
ptr = s;
s = s->next;
}
ptr->next = s->next;
}
else
{
cout<<"Position out of range"<<endl;
}
free(s);
cout<<"Element Deleted"<<endl;
}
}
/* Display Elements of a link list */
void single_list::display()
{
struct node *temp;
if (start == NULL)
{
cout<<"The List is Empty"<<endl;
return;
}
temp = start;
cout<<"Elements of list are: "<<endl;
while (temp != NULL)
{
cout<<temp->info<<"->";
temp = temp->next;
}
cout<<"NULL"<<endl;
}

/* Main : contains menu */


main( )
{
int choice, nodes, element, position, i;
single_list sl;
start = NULL;
clrscr();
while (1)
{
cout<<endl<<"---------------------------------------"<<endl;
cout<<endl<<"Operations on singly linked list"<<endl;
cout<<endl<<"---------------------------------------"<<endl;
cout<<"1. Insert Node at beginning"<<endl;
cout<<"2. Insert node at last"<<endl;
cout<<"3. Insert node at position"<<endl;
cout<<"4. Delete a Particular Node"<<endl;
cout<<"5. Display Linked List"<<endl;
cout<<"6. Exit "<<endl<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Inserting Node at Beginning: "<<endl;
sl.insert_begin();
cout<<endl;
break;
case 2:
cout<<"Inserting Node at Last: "<<endl;
sl.insert_last();
cout<<endl;
break;
case 3:
cout<<"Inserting Node at a given position:"<<endl;
sl.insert_pos();
cout<<endl;
break;
case 4:
cout<<"Delete a particular node: "<<endl;
sl.delete_pos();
break;
case 5:
cout<<"Display elements of link list"<<endl;
sl.display();
cout<<endl;
break;
case 6:
cout<<"Exiting..."<<endl;
exit(1);
break;
default:
cout<<"Wrong choice"<<endl;
}
}
}
Program 2 : To implement Double Linked List
Double Linked List: In a single linked list, every node has link to its next
node in the sequence. So, we can traverse from one node to other node
only in one direction and we can not traverse back. We can solve this kind
of problem by using double linked list. Double linked list can be defined
as follows...

Double linked list is a sequence of elements in which every element has


links to its previous element and next element in the sequence.

In double linked list, every node has link to its previous node and next
node. So, we can traverse forward by using next field and can traverse
backward by using previous field. Every node in a double linked list
contains three fields and they are shown in the following figure...

Here, 'link1' field is used to store the address of the previous node in the
sequence, 'link2' field is used to store the address of the next node in the
sequence and 'data' field is used to store the actual value of that node.

Example

NOTE
☀ In double linked list, the first node must be always pointed by head.
☀ Always the previous field of the first node must be NULL.
☀ Always the next field of the last node must be NULL.
Program :

// C++ Program to Implement Doubly Linked List


#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

// Node Declaration
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


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

// 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;
}
Program 3: Implementing Stack using Linked List

Stack: A stack is a Last In First Out (LIFO) data structure in which all
insertions and deletions are takes place at one end, called the top. Stack
maintains a variable called top, which keeps track of the top most elements in
the stack. Any insertions or deletions should be based upon the value of top.
In the stack, the elements are removed in the reverse order of that in which
they were added to the stack that is last element inserted is to be deleted
first.
Basic Stack Operations:
push/insert : To insert an item into stack
pop/delete : To delete an item from
stack traverse/display : To display an items
isFull : To know whether the stack is full or not
isEmpty : To know whether the stack is empty or not

Program:
// C++ program to implement basic stack operations using Linked List
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

struct Node
{
int data;
Node *next;
} *top=NULL,*p;

Node *newNode(int x)
{
p=new Node;
p->data=x;
p->next=NULL;
return(p);
}
void push(Node *q)
{
if(top==NULL)
top=q;
else
{
q->next=top;
top=q;
}
}

void pop( )
{
if(top==NULL)
{
cout<<"Stack is empty!!";
}
else
{
cout<<"Deleted element is : "<<top->data;
p=top;
top=top->next;
delete(p);
}
}

void display( )
{
Node *q;
q=top;
if(top==NULL)
{
cout<<"Stack is empty!!";
}
else
{
while(q!=NULL)
{
cout<<q->data<<"
"; q=q->next;
}
}
}

int main()
{
int ch, x;
Node *nptr;
while(1)
{
cout<<”\n STACK OPERATIONS “<<endl;
cout<<”\n --------------------------------“<<endl;
cout<<"\n 1.Push \n 2.Pop \n 3.Display \n 4.Exit";
cout<<"\n\n Enter your choice(1-4) : ";
cin>>ch;
switch(ch)
{
case 1: cout<<"\n Enter Data Elements :"<<endl;
cin>>x;
nptr=newNode(x);
push(nptr);
break;
case 2: pop( );
break;
case 3: display( );
break;
case 4: exit(0);
default: cout<<"\nWrong choice!!";
}
}
return 0;
}
Program 4) Implement Circular Queue using Linked list

Circular Queue: Circular Queue is a linear data structure in which the


operations are performed based on FIFO (First In First Out) principle and
the last position is connected back to the first position to make a circle.
Graphical representation of a circular queue is as follows...

Implementation of Circular Queue


To implement a circular queue data structure using array, we first perform
the following steps before we implement actual operations.

 Step 1: Include all the header files which are used in the program
and define a constant 'SIZE' with specific value.
 Step 2: Declare all user defined functions used in circular queue
implementation.
 Step 3: Create a one dimensional array with above defined SIZE (int
cQueue[SIZE])
 Step 4: Define two integer variables 'front' and 'rear' and initialize
both with '-1'. (int front = -1, rear = -1)
 Step 5: Implement main method by displaying menu of operations
list and make suitable function calls to perform operation selected by
the user on circular queue.

Program:
// C++ Program to Implement Circular Linked List
#include<iostream>
#include<stdlib.h>
using namespace std;
// Node Declaration
struct node
{
int info;
struct node *next;
} *last;
// Class Declaration
class circular_llist
{
public:
void create_node(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_list( );
void update( );
void sort( );
circular_llist( )
{
last = NULL;
}
};

int main( ) // Main menu


{
int choice, element, position;
circular_llist cl;
while (1)
{
cout<<endl<<"---------------------------"<<endl;
cout<<endl<<"Circular Singly Linked List Operations"<<endl;
cout<<endl<<"---------------------------------------------------"<<endl;
cout<<"\n 1. Create Node ";
cout<<"\n 2. Add at Beginning ";
cout<<"\n 3. Add After ";
cout<<"\n 4. Delete ";
cout<<"\n 5. Search ";
cout<<"\n 6. Display ";
cout<<"\n 7. Update ";
cout<<"\n 8. Sort ";
cout<<"\n 9. Quit ";
cout<<"\n\n Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter the element : ";
cin>>element;
cl.create_node(element);
cout<<endl;
break;
case 2:
cout<<"Enter the element : ";
cin>>element;
cl.add_begin(element);
cout<<endl;
break;

case 3:
cout<<"Enter the element : ";
cin>>element;
cout<<"Insert element after position : ";
cin>>position;
cl.add_after(element, position);
cout<<endl;
break;
case 4:
if (last == NULL)
{
cout<<"List is empty, nothing to delete "<<endl;
break;
}
cout<<"Enter the element for deletion : ";
cin>>element;
cl.delete_element(element);
cout<<endl;
break;
case 5:
if (last == NULL)
{
cout<<"List Empty!! Can't search"<<endl;
break;
}
cout<<"Enter the element to be searched : ";
cin>>element;
cl.search_element(element);
cout<<endl;
break;
case 6:
cl.display_list();
break;
case 7:
cl.update();
break;
case 8:
cl.sort();
break;
case 9:
exit(1);
break;
default:
cout<<"Wrong choice"<<endl;
}
}
return 0;
}

// Create Circular Link List


void circular_llist::create_node(int value)
{
struct node *temp;
temp = new(struct node);
temp->info = value;
if (last == NULL)
{
last = temp;
temp->next = last;
}
else
{
temp->next = last->next;
last->next = temp;
last = temp;
}
}
// Insertion of element at beginning
void circular_llist::add_begin(int
value)
{
if (last == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->info = value;
temp->next = last->next;
last->next = temp;
}

// Insertion of element at a particular place


void circular_llist::add_after(int value, int pos)
{
if (last == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp, *s;
s = last->next;
for (int i = 0;i < pos-1;i++)
{
s = s->next;
if (s == last->next)
{
cout<<"There are less than ";
cout<<pos<<" in the list"<<endl;
return;
}
}
temp = new(struct node);
temp->next = s->next;
temp->info = value;
s->next = temp;
/*Element inserted at the end*/
if (s == last)
{
last=temp;
}
}
// Deletion of element from the list
void circular_llist::delete_element(int value)
{
struct node *temp, *s;
s = last->next;
/* If List has only one element*/
if (last->next == last && last->info == value)
{
temp = last;
last = NULL;
free(temp);
return;
}
if (s->info == value) /*First Element Deletion*/
{
temp = s;
last->next = s->next;
free(temp);
return;
}
while (s->next != last)
{
/*Deletion of Element in between*/
if (s->next->info == value)
{
temp = s->next;
s->next = temp->next;
free(temp);
cout<<"Element "<<value;
cout<<" deleted from the list"<<endl;
return;
}
s = s->next;
}
/*Deletion of last element*/
if (s->next->info == value)
{
temp = s->next;
s->next = last->next;
free(temp);
last = s;
return;
}
cout<<"Element "<<value<<" not found in the list"<<endl;
}

// Search element in the list


void circular_llist::search_element(int value)
{
struct node *s;
int counter = 0;
s = last->next;
while (s != last)
{
counter++;
if (s->info == value)
{
cout<<"Element "<<value;
cout<<" found at position "<<counter<<endl;
return;
}
s = s->next;
}
if (s->info == value)
{
counter++;
cout<<"Element "<<value;
cout<<" found at position "<<counter<<endl;
return;
}
cout<<"Element "<<value<<" not found in the list"<<endl;
}
// Display Circular Link List
void circular_llist::display_list()
{
struct node *s;
if (last == NULL)
{
cout<<"List is empty, nothing to display"<<endl;
return;
}
s = last->next;
cout<<"Circular Link List: "<<endl;
while (s != last)
{
cout<<s->info<<"->";
s = s->next;
}
cout<<s->info<<endl;
}
// Update Circular Link List
void circular_llist::update()
{
int value, pos, i;
if (last == NULL)
{
cout<<"List is empty, nothing to update"<<endl;
return;
}
cout<<"Enter the node position to be updated: ";
cin>>pos;
cout<<"Enter the new value: ";
cin>>value;
struct node *s;
s = last->next;
for (i = 0;i < pos - 1;i++)
{
if (s == last)
{
cout<<"There are less than "<<pos<<" elements.";
cout<<endl;
return;
}
s = s->next;
}
s->info = value;
cout<<"Node Updated"<<endl;
}
// Sort Circular Link List
void circular_llist::sort()
{
struct node *s, *ptr;
int temp;
if (last == NULL)
{
cout<<"List is empty, nothing to sort"<<endl;
return;
}
s = last->next;
while (s != last)
{
ptr = s->next;
while (ptr != last->next)
{
if (ptr != last->next)
{
if (s->info > ptr->info)
{
temp = s->info;
s->info = ptr->info;
ptr->info = temp;
}
}
else
{
break;
}
ptr = ptr->next;
}
s = s->next;
}
}
Program 5 : Implementation of Binary Search trees.
Binary Search Tree: Binary Search Tree is a binary tree in which
every node contains only smaller values in its left sub-tree and only
larger values in its right sub-tree.
Binary Search Tree, is a node-based binary tree data structure which
has the following properties:
 The left sub-tree of a node contains only nodes with keys lesser than
the node’s key.
 The right sub-tree of a node contains only nodes with keys greater
than the node’s key.
 The left and right sub-tree each must also be a binary search tree.
There must be no duplicate nodes.

For Example: The following tree is a Binary Search Tree. In this tree, left
sub-tree of every node contains nodes with smaller values and right sub-tree
of every node contains larger values.
Program:
// C++ program to implement binary search tree
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

struct node
{
int key;
struct node *left, *right;
};

// A utility function to create a new BST node


struct node *newNode(int item)
{
struct node *temp = (struct node *) malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

// A utility function to do preorder traversal of BST


void preorder(struct node *root)
{
if (root != NULL)
{
cout<<root->key<<” “
preorder(root->left);
preorder(root->right);
}
}

// A utility function to do inorder traversal of BST


void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
cout<< root->key<<” “;
inorder(root->right);
}
}

// A utility function to do postorder traversal of BST


void postorder(struct node *root)
{
if (root != NULL)
{
postorder(root->left);
postorder(root->right);
cout<< root->key<<” “;
}
}

/* A utility function to insert a new node with given key in BST


*/
struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);

/* Otherwise, recur down the tree */


if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);

/* return the (unchanged) node pointer */


return node;
}

// Driver Program to test above functions


int main()
{

/* Let us create following BST


50
/ \
30 70
/ \ / \
20 40 60 80 */

struct node *root = NULL;


root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
// print preoder traversal of the BST
cout<<” PreOrder Traversal : “;
preorder(root);
// print inoder traversal of the BST
cout<<” InOrder Traversal : “;
inorder(root);
// print postoder traversal of the BST
cout<<” PostOrder Traversal : “;
postorder(root);

return 0;
}
Program 6 : Implementation of Hash table.

A hash table uses a hash function to compute an index into an array of


buckets or slots, from which the corresponding value can be found. We
will go through a basic Hash Map implementation in C++ with generic
type key-value pairs by using templates.

Hashing is when you take any type of data, and assign an integer value to
it. Basically you end up storing it in an array of some sort that can be
accessed based on that "key", which is the integer. A hash function is
something that takes the data as a parameter, and returns the integer value
that is the key.

Program:
// Program to implement Hash Table
#include<iostream.h>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<conio.h>
//using namespace std;

const int TABLE_SIZE=128;


// HashEntry Class Declaration
class HashEntry
{
public:
int key;
int value;
HashEntry(int key, int value)
{
this->key = key;
this->value = value;
}
};

// HashMap Class Declaration


class HashMap
{
private:
HashEntry **table;
public:
HashMap()
{
table=new HashEntry *[TABLE_SIZE];
for(int i=0; i<TABLE_SIZE; i++)
{
table[i] = NULL;
}
}

// Hash Function
int HashFunc(int key)
{
return key % TABLE_SIZE;
}

// Insert Element at a key


void Insert(int key, int value)
{
int hash=HashFunc(key);
while(table[hash] != NULL && table[hash]->key != key)
{
hash = HashFunc(hash + 1);
}
if(table[hash] != NULL)
delete table[hash];
table[hash] = new HashEntry(key, value);
}
// Search Element at a key
int Search(int key)
{
int hash=HashFunc(key);
while(table[hash] != NULL && table[hash]->key != key)
{
hash=HashFunc(hash+1);
}
if(table[hash]==NULL)
return -1;
else
return table[hash]->value;
}
// Remove Element at a key
void Remove(int key)
{
int hash=HashFunc(key);
while (table[hash] != NULL)
{
if(table[hash]->key == key)
break;
hash = HashFunc(hash + 1);
}
if(table[hash] == NULL)
{
cout<<"No Element found at key : "<<key<<endl;
return;
}
else
{
delete table[hash];
}
cout<<"Element Deleted"<<endl;
}
~HashMap()
{
for(int i=0; i<TABLE_SIZE; i++)
{
if(table[i] != NULL)
delete table[i];
delete[] table;
}
}
};

// Main Menu
int main()
{
HashMap hash;
int key, value;
int choice;
clrscr();
while (1)
{
cout<<"\n----------------------"<<endl;
cout<<"Operations on Hash Table"<<endl;
cout<<"----------------------"<<endl;
cout<<"1.Insert element into the table"<<endl<<endl;
cout<<"2.Search element from the key"<<endl<<endl;
cout<<"3.Delete element at a key"<<endl<<endl;
cout<<"4.Exit"<<endl<<endl;
cout<<"Enter your choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter element to be inserted : ";
cin>>value;
cout<<"Enter key at which element to be inserted : ";
cin>>key;
hash.Insert(key, value);
break;
case 2:
cout<<"Enter key of the element to be searched : ";
cin>>key;
if(hash.Search(key) == -1)
{
cout<<"No element found at key : "<<key<<endl;
continue;
}
else
{
cout<<"Element at key :"<<key<<" : ";
cout<<hash.Search(key)<<endl;
}
break;
case 3:
cout<<"Enter key of the element to be deleted : ";
cin>>key;
hash.Remove(key);
break;
case 4:
exit(1);
default:
cout<<"\nEnter correct option\n";
}
}
return 0;
}
Program 7: Implementation of Heaps.

Heap: Heap is a special case of balanced binary tree data structure where
the root-node key is compared with its children and arranged accordingly.
If α has child node β then − key(α) ≥ key(β)

As the value of parent is greater than that of child, this property generates
Max Heap. Based on this criteria, a heap can be of two types −

For Input → 35 33 42 10 14 19 27 44 26 31

Min-Heap − Where the value of the root node is less than or equal to
either of its children.

Max-Heap − Where the value of the root node is greater than or equal to either
of its children.

Both trees are constructed using the same input and order of arrival.
Program:

// C++ program to demonstrate common Binary Heap Operations


#include <iostream>
#include <conio.h>

using namespace std;

// build a max heap


void max_heapify(int *a, int i, int n)
{
int j, temp;
temp = a[i];
j = 2 * i;
while (j <= n)
{
if (j < n && a[j+1] > a[j])
j = j + 1;
if (temp > a[j])
break;
else if (temp <= a[j])
{
a[j / 2] = a[j];
j = 2 * j;
}
}
a[j/2] = temp;
return;
}

void build_maxheap(int *a,int n)


{
int i;
for(i = n/2; i >= 1; i--)
{
max_heapify(a,i,n);
}
}
// build a min heap
void min_heapify(int *b, int i, int m)
{
int j, temp;
temp = b[i];
j = 2 * i;
while (j <= m)
{
if (j < m && b[j+1] < b[j])
j = j + 1;
if (temp < b[j])
break;
else if (temp >= b[j])
{
b[j / 2] = b[j];
j = 2 * j;
}
}
b[j/2] = temp;
return;
}

void build_minheap(int *b,int m)


{
int i;
for(i = m/2; i >= 1; i--)
{
min_heapify(b,i,m);
}
}

// Driver program
int main()
{
int n, i, x;
cout<<"enter no of elements of array\n";
cin>>n;
int a[20];
for (i = 1; i <= n; i++)
{
cout<<"enter element"<<(i)<<endl;
cin>>a[i];
}
build_maxheap(a,n);
cout<<"Max Heap \n";
for (i = 1; i <= n; i++)
{
cout<<a[i]<<endl;
}
build_minheap(a,n);
cout<<"Min Heap \n";
for (i = 1; i <= n; i++)
{
cout<<a[i]<<endl;
}
getch();
}
Prog 8: To Implement Breadth First Search (BFS) Techniques.
BFS (Breadth First Search): BFS traversal of a graph, produces a
spanning tree as final result. Spanning Tree is a graph without any loops.
We use Queue data structure with maximum size of total number of
vertices in the graph to implement BFS traversal of a graph.

We use the following steps to implement BFS traversal:


Step 1: Define a Queue of size total number of vertices in the graph.
Step 2: Select any vertex as starting point for traversal. Visit that vertex
and insert it into the Queue.
Step 3: Visit all the adjacent vertices of the vertex which is at front of the
Queue which is not visited and insert them into the Queue.
Step 4: When there is no new vertex to be visit from the vertex at front of
the Queue then delete that vertex from the Queue.
Step 5: Repeat step 3 and 4 until queue becomes empty.
Step 6: When queue becomes Empty, then produce final spanning tree by
removing unused edges from the graph.

Program:
// C++ program to implementation of Breadth First Search (BFS) for a given graph
#include<iostream>
#include<conio.h>
#include<stdlib.h>

using namespace std;

int cost[10][10], que[10], visit[10], visited[10], nv, ne, sv, front,


rare,i,j,k;

void main( )
{
cout<<"\n Enter no of vertices : ";
cin>>nv;
cout<<"\n Ente no of edges : ";
cin>>ne;
cout<<"\n Enter EDGES one by one : \n";
for(k=1; k<=ne; k++)
{
cin>>i>>j;
cost[i][j]=1;
}
cout<<"\n Enter Initial(starting) Vertex : ";
cin>>sv;
cout<<"\n Final Result of BFS Traversal is :
"; cout<<sv<<" ";
visited[sv]=1;
k=1;
while(k<nv)
{
for(j=1; j<=nv; j++)
if(cost[sv][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
que[rare++]=j;
}
sv=que[front++];
cout<<sv<<" ";
k++;
visit[sv]=0;
visited[sv]=1;
}
}
Prog 9: To Implement Depth First Search (DFS) Techniques.
DFS (Depth First Search): DFS traversal of a graph, produces a spanning
tree as final result. Spanning Tree is a graph without any loops. We use
Stack data structure with maximum size of total number of vertices in the
graph to implement DFS traversal of a graph.
We use the following steps to implement DFS traversal:
Step 1: Define a Stack of size total number of vertices in the graph.
Step 2: Select any vertex as starting point for traversal. Visit that vertex
and push it on to the Stack.
Step 3: Visit any one of the adjacent vertex of the vertex which is at top of
the stack which is not visited and push it on to the stack.
Step 4: Repeat step 3 until there are no new vertex to be visit from the
vertex on top of the stack.
Step 5: When there is no new vertex to be visit then use back tracking and
pop one vertex from the stack.
Step 6: Repeat steps 3, 4 and 5 until stack becomes Empty.
Step 7: When stack becomes Empty, then produce final spanning tree by
removing unused edges from the graph
Note : Back tracking is coming back to the vertex from which we came to
current vertex.
Program:
// C++ program for the implementation of Depth-first search (DFS) for a given
graph
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int cost[10][10], stk[10], visit[10], visited[10], nv, ne, sv, top, i, j,
k;
void main( )
{
cout<<"\n Enter no of vertices : ";
cin>>nv;
cout<<"\n Ente no of edges : ";
cin>>ne;
cout<<"\n Enter EDGES one by one : \n";
for(k=1; k<=ne; k++)
{
cin>>i>>j;
cost[i][j]=1;
}
cout<<"\n Enter initial(Starting) vertex : ";
cin>>sv;
cout<<"\n The Result of DFS Traversal is : ";
cout<<sv<<" ";
visited[sv]=1;
k=1;
while(k<nv)
{
for(j=nv; j>=1; j--)
if(cost[sv][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
stk[top]=j;
top++;
}
sv=stk[--top];
cout<<sv<<" ";
k++;
visit[sv]=0;
visited[sv]=1;
}
}
Program 10: Implementation of Prim’s Algorithm

In computer science, Prim's algorithm is a greedy algorithm that finds a


minimum spanning tree for a weighted undirected graph. This means it
finds a subset of the edges that forms a tree that includes every vertex,
where the total weight of all the edges in the tree is minimized.

The steps for implementing Prim's algorithm are as follows:

1. Initialize the minimum spanning tree with a vertex chosen at


random.
2. Find all the edges that connect the tree to new vertices, find the
minimum and add it to the tree
3. Keep repeating step 2 until we get a minimum spanning tree
Example of Prim's algorithm
Program:

// Implementation of Prim's Algorithm


#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;

int cost[10][10], i, j, k, n, stk[10], top, v, visit[10], visited[10], u;


int main()
{
int m, c;
cout<<"\nEnter no of vertices : ";
cin>>n;
cout<<"\nEnter no of edges : ";
cin>>m;
cout<<"\nEnter EDGES and Cost one by one \n\n";
for(k=1;k<=m;k++)
{
cin>>i>>j>>c;
cost[i][j]=c;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]==0)
cost[i][j]=31999;
cout <<"\nORDER OF VISITED VERTICES : ";
k=1;
while(k<n)
{
m=31999;
if(k==1)
{
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
if(cost[i][j]<m)
{
m=cost[i][j];
u=i;
}
}
else
{
for(j=n;j>=1;j--)
if(cost[v][j]<m && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
stk[top]=j;
top++;
m=cost[v][j];
u=j;
}
}
cost[v][u]=31999;
v=u;
cout<<v<<" ";
k++;
visit[v]=0;
visited[v]=1;
}
return 0;
}
Program 11: Implementation of Dijkstra’s Algorithm

Dijkstra's algorithm allows us to find the shortest path between any two
vertices of a graph. Dijkstra’s algorithm is very similar to Prim’s algorithm
for minimum spanning tree. Like Prim’s MST, we generate a SPT
(shortest path tree) with given source as root. We maintain two sets, one
set contains vertices included in shortest path tree, other set includes
vertices not yet included in shortest path tree. At every step of the
algorithm, we find a vertex which is in the other set (set of not yet
included) and has a minimum distance from the source.

Algorithm
1) Create a set sptSet (shortest path tree set) that keeps track of vertices
included in shortest path tree, i.e., whose minimum distance from source is
calculated and finalized. Initially, this set is empty.

2) Assign a distance value to all vertices in the input graph. Initialize all
distance values as INFINITE. Assign distance value as 0 for the source
vertex so that it is picked first.

3) While sptSet doesn’t include all vertices

a) Pick a vertex u which is not there in sptSet and has minimum distance
value.

b) Include u to sptSet.

c) Update distance value of all adjacent vertices of u. To update the


distance values, iterate through all adjacent vertices. For every adjacent
vertex v, if sum of distance value of u (from source) and weight of edge u-
v, is less than the distance value of v, then update the distance value of v.

Example of Dijkstra's algorithm

It is easier to start with an example and then think about the algorithm.
Program:
// Implementation of Dijkstra's Algorithm
#include<iostream>
#include<conio.h>
#include<stdio.h>
//using namespace std;

int shortest(int ,int);


int cost[10][10],dist[20],i,j,n,k,m,s[20],v,totcost,path[20],p;
void main( )
{
int c;
cout<<"\nEnter no of vertices : ";
cin>>n;
cout<<"\nEnter no of edges : ";
cin>>m;
cout<<"\nEnter EDGES and Cost\n\n";
for(k=1;k<=m;k++)
{
cin>>i>>j>>c;
cost[i][j]=c;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]==0)
cost[i][j]=31999; cout<<"\
nEnter initial vertex : "; cin>>v;
cout<<v<<"\n";
shortest(v,n);
}
int shortest(int v,int n)
{
int min;
for(i=1;i<=n;i++)
{
s[i]=0;
dist[i]=cost[v][i];
}
path[++p]=v;
s[v]=1;
dist[v]=0;
for(i=2;i<=n-1;i++)
{
k=-1;
min=31999;

for(j=1;j<=n;j++)
{
if(dist[j]<min && s[j]!=1)
{
min=dist[j];
k=j;
}
}
if(cost[v][k]<=dist[k])
p=1;
path[++p]=k;
for(j=1;j<=p;j++)
cout<<path[j]<<" ";
cout<<"\n";
s[k]=1;
for(j=1;j<=n;j++)
if(cost[k][j]!=31999 && dist[j]>=dist[k]+cost[k][j] && s[j]!=1)
dist[j]=dist[k]+cost[k][j];
}
return 0;
}
Program 12: Implementation of Kruskal’s Algorithm

Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an


edge of the least possible weight that connects any two trees in the forest.
It is a greedy algorithm in graph theory as it finds a minimum spanning
tree for a connected weighted graph adding increasing cost arcs at each
step.

The steps for implementing Kruskal's algorithm are as follows:

1. Sort all the edges from low weight to high


2. Take the edge with the lowest weight and add it to the spanning tree.
If adding the edge created a cycle, then reject this edge.
3. Keep adding edges until we reach all vertices.

Example of Kruskal's algorithm


Program:

// Implementation of Kruskal's Algorithm


#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int cost[10][10], i,j,k,n,m,c, visit, visited[10], l, v, count, count1, vst,
p;
void main( )
{
int dup1,dup2;
cout<<"\nEnter no of vertices : ";
cin>>n;
cout<<"\nEnter no of edges : ";
cin>>m;
cout<<"\nEnter EDGES and Cost \n";
for(k=1;k<=m;k++)
{
cin>>i>>j>>c;
cost[i][j]=c;
cost[j][i]=c;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]==0)
cost[i][j]=31999;
visit=1;
while(visit<n)
{
v=31999;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]!=31999 && cost[i][j]<v && cost[i][j]!=-1 )
{
int count=0;
for(p=1;p<=n;p++)
{
if(visited[p]==i || visited[p]==j)
count++;
}
if(count >= 2)
{
for(p=1;p<=n;p++) if(cost[i]
[p]!=31999 && p!=j)
dup1=p;
for(p=1;p<=n;p++) if(cost[j]
[p]!=31999 && p!=i)
dup2=p; if(cost[dup1]
[dup2]==-1) continue;
}
l=i;
k=j;
v=cost[i][j];
}
cout <<"\nEdge from " <<l<<"-->"<<k<<endl;
cost[l][k]=-1;
cost[k][l]=-1;
visit++;
int count=0;
count1=0;
for(i=1;i<=n;i++)
{
if(visited[i]==l)
count++;
if(visited[i]==k)
count1++;
}
if(count==0)
visited[++vst]=l;
if(count1==0)
visited[++vst]=k;
}
}
Prog 13: Implementation of Merge sort

Merge Sort: Merge Sort is a Divide and Conquer algorithm. It divides input
array in two halves, calls itself for the two halves and then merges the two
sorted halves. The merge() function is used for merging two halves.

The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r]
are sorted and merges the two sorted sub-arrays into one.

The procedure for merge sort is as follows:


MergeSort(arr[ ], l, r)

If (r > l)

1. Find the middle point to divide the array into two halves:
middle m = (l+r) / 2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)

Program:

// C++ Program to implement the Merge Sort


#include <iostream>
#include<stdlib.h>
using namespace std;

// A function to merge the two half into a sorted data.


void Merge(int *a, int low, int high, int mid)
{
// We have low to mid and mid+1 to high already sorted.
int i, j, k, temp[25];
i = low;
k = 0;
j = mid + 1;
// Merge the two parts into temp[ ].
while(i<=mid && j<=high)
{

if(a[i] < a[j])


{
temp[k]=a[i];
k++;
i++;
}
else
{
temp[k]=a[j];
k++;
j++;
}
}
// Insert all the remaining values from i to mid into temp[ ].
while(i <= mid)
{
temp[k]=a[i];
k++;
i++;
}
// Insert all the remaining values from j to high into temp[ ].
while(j <= high)
{
temp[k]=a[j];
k++;
j++;
}
// Assign sorted data stored in temp[ ] to a[ ].
for(i=low; i<=high; i++)
{
a[i]=temp[i-low];
}
}
// A function to split array into two parts.
void MergeSort(int *a, int low, int high)
{
int mid;
if(low < high)
{
mid=(low+high)/2;
// Split the data into two half.
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
// Merge them to get sorted output.
Merge(a, low, high, mid);
}
}

int main( )
{
int arr[25], n, i;
cout<<"\nEnter the number of data element to be sorted : ";
cin>>n;
cout<<endl;
for(i=0; i<n; i++)
{
cout<<"Enter "<<i+1<<" data element :";
cin>>arr[i];
}
// Before Soring the Actulal order of the data elements
cout<<"\nActual Data Elements:";
for(i=0; i<n; i++)
cout<<"-> "<<arr[i];
MergeSort(arr, 0, n-1);
// Printing the sorted data.
cout<<"\n\nSorted Data Elements:";
for(i=0; i<n; i++)
cout<<"-> "<<arr[i];
return 0;
}
Prog 14: Implementation of Quick Sort
Quick Sort: Quick sort is based on the divide-and-conquer approach based on
the idea of choosing one element as a pivot element and partitioning the array
around it such that: Left side of pivot contains all the elements that are less than
the pivot element Right side contains all elements greater than the pivot.

Quick sort algorithm:


Step 1 − Choose the highest index value has pivot
Step 2 − Take two variables to point left and right of the list excluding
pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot
Program:
// C++ Program to Implement Quick Sort
#include<iostream.h>
#include<stdlib.h>
using namespace std;
//Function for partitioning array
int part(int low, int high, int *a)
{
int i, h=high, l=low, pvt, t;
pvt=a[low];
while(low<high)
{
while(a[l]<pvt)
{
l++;
}
while(a[h]>pvt)
{
h--;
}

if(l<h)
{
t=a[l];
a[l]=a[h];
a[h]=t;
}
else
{
t=pvt;
pvt=a[l];
a[l]=t;
break;
}
}
return h;
}
void quick(int l, int h, int *a)
{
int index, i;
if(l<h)
{
index=part(l, h, a);
quick(l, index-1, a);
quick(index+1, h, a);
}
}

int main( )
{
int arr[100],n,i,l,h;
cout<<"\nEnter the number of data element to be sorted : ";
cin>>n;
cout<<endl;

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


{
cout<<"Enter "<<i+1<<" data element :";
cin>>arr[i];
}
// Before Soring the Actulal order of the data elements
cout<<"\nActual Data Elements:";
for(i=0; i<n; i++)
cout<<"-> "<<arr[i];
h=n-1;
l=0;
quick(l,h,arr);
// Printing the sorted data. cout<<"\
n\nSorted Data Elements:"; for(i=0;
i<n; i++)
cout<<"-> "<<arr[i];
return 0;
}
Prog 15: To implement Data Searching using Divide and Conquer
( Binary Search) technique.

Binary Search: Binary search is a fast search algorithm with run-time


complexity of Ο(log n). This search algorithm works on the principle of
divide and conquers. For this algorithm to work properly, the data
collection should be in the sorted form.

Binary search looks for a particular item by comparing the middle most
item of the collection. If a match occurs, then the index of item is returned.
If the middle item is greater than the item, then the item is searched in the
sub-array to the left of the middle item. Otherwise, the item is searched for
in the sub-array to the right of the middle item. This process continues on
the sub-array as well until the size of the sub array reduces to zero.

Binary Search Algorithm

Step 1 : low = 0;
Step 2 : high = size - 1;
Step 3 : while (low <= high)
{ /* Calculate mid index */
mid = (low + high) / 2;
Step 4 : /*If element is found at mid index then return the index */
if (arr[mid] == num )
{
return mid+1;
}
else if ( arr[mid] > num)
{
high = mid - 1;
}
else if ( arr[mid] < num)
{
low = mid + 1;
}
Step 5: /* If element is not found return -1 */
return -1;
}
Program:
Write a C++ program that implements Data Searching using Divide
and Conquer ( Binary Search) technique.

// Data Element Search Using Divide and Conquer method (Binary Search)

#include <iostream>
#include<stdlib.h>

#define SIZE 5

int binary_search(int list[ ], int low, int high, int target);

void main( )
{
int list[SIZE], target, index, i;
char ch;
cout<<"Enter " <<SIZE <<" elements in ascending or descending order :"<<endl;
for(i=0; i<SIZE; i++)
cin>>list[i];
do
{
cout<<"\n Enter an element that is to be searched : ";
cin>>target;
index = binary_search(list, 0, SIZE-1, target);
if(index != -1)
cout<<"\n\n Target element was found at position : "<<index+1;
else
cout<<"\n\n Sorry, target item was not found";
cout<<"\n\n Do you want to continue...(y/n) : ";
cin>>ch;
}
while(ch!='n');
}

int binary_search(int list[ ], int low, int high, int target)


{
int middle;
if(low > high)
return -1;
middle=(low+high)/2;
if(list[middle] == target)
return (middle);
else
if(list[middle] < target)
return binary_search(list,middle+1,high,target);
else
return binary_search(list,low,middle-1,target);
}

You might also like