DSA Lab Record
DSA Lab Record
DSA Lab Record
INDEX
Sr. No Program Page No
int push()
{
int temp;
if(top==5)
cout<<"\n Stack is Overflow";
else
{
cout<<"\n Enter element in stack = ";
cin>>temp;
top++;
stack[top]=temp;
return top;
}
}
int pop()
{
int temp;
if(top==-1)
cout<<"\n Stack is Underflow ";
else
{
temp=stack[top];
top--;
cout<<"\n deleted element = "<<temp;
}
return top;
}
void display(int n)
{
int i;
if(top==-1)
cout<<"\n Stack is empty";
else
Go to Index Page 4 of 89
{
for(i=n;i>=0;i--)
{
cout<<"\n "<<stack[i];
n--;
}
}
}
int main()
{
int choice,status;
cout<<"\n 1 - Push element is stack";
cout<<"\n 2 - Pop element from stack";
cout<<"\n 3 - Display elements of stack";
cout<<"\n 4 - Quit";
do
{
cout<<"\n*******************************\n";
cout<<"\n\n Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
status=push();
break;
case 2:
status=pop();
break;
case 3:
display(status);
break;
case 4:
exit(0);
}
}while(choice!=4);
cout<<"\n\n Thank you for visiting";
return 0;
}
Go to Index Page 5 of 89
Go to Index Page 6 of 89
class Stack_Node
{
public:
int data;
Stack_Node *link;
};
class Stack{
private:
Stack_Node *Top;
int size;
public:
Stack(){
Top=NULL;
size=0;
}
int GetTop();
int IsEmpty();
int Pop();
void Push(int Element);
int CurrSize();
};
int Stack::IsEmpty(){
if(Top==NULL){
cout<<"Stack is Empty";
return 1;
}
else
return 0;
}
newnode->data=Element;
newnode->link=NULL;
newnode->link=Top;
Top=newnode;
}
int Stack::Pop(){
Stack_Node* tmp=Top;
int data=Top->data;
if(!IsEmpty()){
Top=Top->link;
delete tmp;
return(data);
}
}
int Stack::GetTop(){
if(!IsEmpty())
return(Top->data);
}
int main() {
int choice, data;
Stack S;
cout<<"\n 1 - Insert element in queue";
cout<<"\n 2 - Delete element from queue";
cout<<"\n 3 - Display top of queue";
cout<<"\n 4 - Exit";
do
{
cout<<"\n*****************************";
cout<<"\n Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\n Enter value of element : ";
cin>>data;
S.Push(data);
break;
case 2:
cout<<"Pop : "<<S.Pop()<<"\n";
Go to Index Page 8 of 89
break;
case 3:
cout<<"Top of Stack : "<<S.GetTop()<<"\n";
break;
}
}while(choice<4);
return 0;
}
Go to Index Page 9 of 89
#include<iostream.h>
int queue[5];
int rear=0;
int front=0;
void insert()
{
int elem;
if(rear>4)
cout<<"\n No space in queue";
else
{
cout<<"\n Enter element in queue = ";
cin>>elem;
queue[rear]=elem;
rear++;
cout<<"\n Element added in queue";
}
}
void deQueue()
{
int temp;
if(front>4 || rear==0)
cout<<"\n Queue is empty";
else
{
temp=queue[front];
front++;
cout<<"\n Deleted element is "<<temp;
}
}
void display()
{
int i;
if(rear==0 || front>4)
cout<<"\n Queue is empty";
else
Go to Index Page 10 of 89
{
for(i=front;i<rear;i++)
{
cout<<"\n "<<queue[i];
}
}
}
int main()
{
int choice;
cout<<"\n 1 - Insert element in queue";
cout<<"\n 2 - Delete element from queue";
cout<<"\n 3 - Display element of queue";
cout<<"\n 4 - Exit";
do
{
cout<<"\n*****************************";
cout<<"\n Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
insert();
break;
case 2:
deQueue();
break;
case 3:
display();
break;
}
}while(choice<4);
return 0;
}
Go to Index Page 11 of 89
Go to Index Page 12 of 89
#include<stdlib.h>
#include<iostream.h>
template <class T>
class node
{
public:
T data;
node<T>*next;
};
{
rear
->next=p;
rear=p;
}
cout<<"\nInserted into Queue Sucesfully....\n";
}
//code to delete an element
template <class T>
void queue<T>::delete_q() {
node<T>*t;
if(front==NULL)
cout<<"\nqueue is Underflow";
else
{
item=front
->data;
t=front;
front=front
->next;
cout<<"\n"<<item<<" is deleted Sucesfully from
queue....\n";
}
delete(t);
}
//code to display elements in queue
template <class T>
void queue<T>::display_q()
{
node<T>*t;
if(front==NULL)
cout<<"\nqueue Under Flow";
else
{
cout<<"\nElements in the queue are....\n";
t=front;
while(t!=NULL)
{
cout<<"|"<<t->data<<"|<-";
t=t->next;
}
Go to Index Page 14 of 89
}
}
int main()
{
int choice;
queue<int>q1;
cout<<"\n\n***Menu for Queue operations***\n\n";
cout<<"1.Insert\n2.Delete\n3.DISPLAY\n4.EXIT\n";
while(1)
{
cout<<"\nEnter Choice:";
cin>>choice;
switch(choice)
{
case 1: q1.insert_q();
break;
case 2: q1.delete_q();
break;
case 3: q1.display_q();
break;
case 4: exit(0);
default:cout<<"Invalid choice...Try again...\n";
}
}
return 0;
}
Go to Index Page 15 of 89
Go to Index Page 16 of 89
#include <iostream.h>
int Queue[7];
int front=-1, rear=-1, n=7;
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;
Go to Index Page 17 of 89
if (front == -1) {
cout<<"Queue is empty"<<endl;
return;
}
cout<<"Queue elements are :\n";
if (f <= r) {
while (f <= r){
cout<<Queue[f]<<" ";
f++;
}
} else {
while (f <= n - 1) {
cout<<Queue[f]<<" ";
f++;
}
f = 0;
while (f <= r) {
cout<<Queue[f]<<" ";
f++;
}
}
cout<<endl;
}
int main() {
case 2:
Go to Index Page 18 of 89
deleteCQ();
break;
case 3:
displayCQ();
break;
case 0:
cout<<"Exit\n";
break;
default: cout<<"Incorrect!\n";
}
} while(choice != 0);
return 0;
}
Go to Index Page 19 of 89
Go to Index Page 20 of 89
#include<iostream.h>
class node{
public:
int data;
node *link;
};
class create
{
private:
node *head,*curr;
public:
create()
{
head=curr=NULL;
}
int counter=1;
node *temp;
curr=head;
if(head==NULL)
cout<<"\n List is Empty";
else if(pos==1)
head=head->link;
else
{
while(counter<pos)
{
if(curr->link==NULL)
break;
temp=curr;
curr=curr->link;
counter++;
}
if(counter==pos)
temp->link=curr->link;
else
cout<<"Position not found";
}
}
//Delete element from first position
void create::deleteAtFirst()
{
if(head==NULL)
cout<<"\n List is Empty";
else
head=head->link;
}
//Delete element from last position
void create::deleteAtLast()
{
node *temp;
curr=head;
if(head==NULL)
cout<<"\n List is empty";
else
{
while(1)
Go to Index Page 22 of 89
{
if(curr->link==NULL)
break;
temp=curr;
curr=curr->link;
}
temp->link=NULL;
}
}
//Add element at specified position
void create::addAtPosition(int pos,int value)
{
int flag=1,counter=2;
node *temp;
curr=head;
if(head==NULL)
{
temp=createNode(value);
head=temp;
}
else if(pos==1)
{
temp=createNode(value);
temp->link=head;
head=temp;
}
else
{
temp=createNode(value);
while(counter<pos)
{
if(curr->link==NULL)
break;
curr=curr->link;
counter++;
}
if(counter==pos)
{
temp->link=curr->link;
Go to Index Page 23 of 89
curr->link=temp;
}
else
cout<<"Position not found";
}
}
while(d!=NULL)
{
cout<<d->data<<"\t";
d=d->link;
}
}
//main() method
int main()
{
char ans;
int choice,element,pos;
create L1;
cout<<"\n 1 - Insert node at first position";
cout<<"\n 2 - Insert node at specified position";
cout<<"\n 3 - Insert node at last position";
cout<<"\n 4 - Delete node from first position";
cout<<"\n 5 - Delete node from specified position";
#include <stdio.h>
#include<iostream.h>
class node
{
public:
int info;
node *next, *last;
node(){
next=last=NULL;
}
};
/*Class Declaration */
class circular_llist
{
private:
node *last, *next;
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;
}
};
/*
* Main :contains menu
*/
int main()
{
int choice, element, position;
circular_llist cl;
Go to Index Page 28 of 89
while (1)
{
cout<<endl<<"---------------------------"<<;
cout<<endl<<"Circular singly linked list"<<;
cout<<endl<<"---------------------------"<<endl;
cout<<"1.Create Node"<<endl;
cout<<"2.Add at beginning"<<endl;
cout<<"3.Add after"<<endl;
cout<<"4.Delete"<<endl;
cout<<"5.Search"<<endl;
cout<<"6.Display"<<endl;
cout<<"7.Update"<<endl;
cout<<"8.Sort"<<endl;
cout<<"9.Quit"<<endl;
cout<<"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:
cout<<"Enter the element for deletion: ";
cin>>element;
Go to Index Page 29 of 89
cl.delete_element(element);
cout<<endl;
break;
case 5:
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)
{
node *temp;
temp = new node;
temp->info = value;
if (last == NULL)
{
last = temp;
temp->next = last;
}
Go to Index Page 30 of 89
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;
}
node *temp;
temp = new 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;
}
node *temp, *s;
s = last->next;
for (int i = 0;i < pos-1;i++)
{
s = s->next;
if (s == last->next)
Go to Index Page 31 of 89
{
cout<<"There are less than ";
cout<<pos<<" in the list"<<endl;
return;
}
}
temp = new 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)
{
node *temp, *s;
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
return;
}
else
{
s = last->next;
/* If List has only one element*/
if (last->next == last && last->info == value)
{
temp = last;
last = NULL;
free(temp);
return;
}
Go to Index Page 32 of 89
/*
* Search element in the list
*/
void circular_llist::search_element(int value)
{
node *s;
int counter = 0;
Go to Index Page 33 of 89
if (last == NULL)
{
cout<<"List Empty!! Can't search"<<endl;
return;
}
else
{
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()
{
node *s;
if (last == NULL)
{
cout<<"List is empty, nothing to display"<<endl;
return;
}
Go to Index Page 34 of 89
s = last->next;
cout<<"\nCircular 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;
}
Go to Index Page 35 of 89
/*
* Sort Circular Link List
*/
void circular_llist::sort()
{
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;
}
}
Go to Index Page 36 of 89
Go to Index Page 37 of 89
#include<iostream.h>
class DLL_Node{
public:
int data;
DLL_Node *pre,*next;
DLL_Node()
{
pre=NULL;
next=NULL;
}
};
class DList{
private:
DLL_Node *head ,*tail;
public:
DList()
{
head=tail=NULL;
}
void create();
DLL_Node* GetNode();
void Append(DLL_Node* newNode);
void Traverse();
void DeleteNode(int val);
void Delete_Pos(int pos);
void Insert_Pos(DLL_Node* newNode, int pos);
};
DLL_Node* DList::GetNode()
{
DLL_Node* newNode;
newNode= new DLL_Node;
cout<<"Enter the data to insert in node: \t";
cin>>newNode->data;
return (newNode);
}
void DList::Append(DLL_Node * newNode)
Go to Index Page 38 of 89
{
if(head==NULL)
{
head=newNode;
tail=newNode;
}
else{
tail->next=newNode;
newNode->pre=tail;
tail=newNode;
}
}
void DList::create()
{
char ans;
DLL_Node *newNode;
while(1)
{
cout<<"\nAny more node want to ceate (y/n) : ";
cin>>ans;
if(ans=='n'||ans=='N')break;
newNode=GetNode();
Append(newNode);
}
}
void DList::Traverse()
{
DLL_Node *curr;
curr=head;
if(curr==NULL)
cout<<"\nList Is Empty";
else
{
cout<<"\n\n Final list:\n\n";
while(curr!=NULL){
cout<<curr->data<<"\t";
curr=curr->next;
}
}
Go to Index Page 39 of 89
int main()
{
int choice, pos;
DList D1;
DLL_Node* newNode;
newNode= new DLL_Node;
D1.create();
D1.Traverse();
//DLL_Node NewNode;
//NewNode=D1.GetNode();
D1.Insert_Pos(newNode, pos);
D1.Traverse();
break;
case 2:
cout<<"\nEnter value of node whcih is to
be deleted : ";
cin>>pos;
D1.DeleteNode(pos);
D1.Traverse();
break;
case 3:
cout<<"\nEnter position whcih is to be
deleted : ";
cin>>pos;
Go to Index Page 40 of 89
D1.Delete_Pos(pos);
D1.Traverse();
break;
default:
cout<<"Invalid choice";
}
return 0;
}
else if (pos==1)
{
NewNode->next=head;
head->pre=NewNode;
head=NewNode;
}
else{
while(count!=pos){
temp=temp->next;
if(temp!=NULL)
count++;
else
break;
}
if (count== pos)
{
(temp->pre)->next=NewNode;
NewNode->pre=temp->pre;
temp->pre=NewNode;
NewNode->next=temp;
Go to Index Page 41 of 89
}
else
cout<<"\n Postion not found";
}
}
void DList::Delete_Pos(int pos)
{
int count=1;
DLL_Node *temp=head, *curr;
if(head==NULL)
cout<<"\nList is empty";
else if(pos==1)
{
temp=head;
head=head->next;
//release memory
delete temp;
}
else
{
while(count!=pos)
{
temp=temp->next;
//curr=temp->pre;
if(temp!=NULL)
count++;
else
break;
}
if(count==pos)
{
if(temp->next==NULL)
{
(temp->pre)->next=temp->next;
}
else
{
(temp->pre)->next=temp->next;
(temp->next)->pre=temp->pre;
}
//release memory
Go to Index Page 42 of 89
delete temp;
}
else
cout<<"\n Position not found\n List is \n";
}
}
void DList::DeleteNode(int val)
{
int flag=0;
DLL_Node *temp=head, *curr;
if(head==NULL)
cout<<"\nList is empty";
else if(head->data==val)
{
temp=head;
head=head->next;
delete temp;
}
else
{
while(1)
{
if(temp!=NULL)
{
if(temp->data==val)
{
flag=1;
break;
}
}
temp=temp->next;
//curr=temp->pre;
if(temp==NULL)
break;
}
if(flag==1)
{
if(temp->next==NULL)
{
(temp->pre)->next=temp->next;
}
Go to Index Page 43 of 89
else
{
(temp->pre)->next=temp->next;
(temp->next)->pre=temp->pre;
}
//release memory
delete temp;
}
else
cout<<"\n Oops! Node not found";
}
}
Go to Index Page 44 of 89
Go to Index Page 45 of 89
#include<iostream.h>
class node{
public:
int data;
node *link;
};
class create
{
private:
node *head,*curr;
public:
create()
{
head=curr=NULL;
}
node *temp;
curr=head;
if(head==NULL)
{
temp=createNode(value);
head=temp;
}
else if(pos==1)
{
temp=createNode(value);
temp->link=head;
head=temp;
}
else
{
temp=createNode(value);
while(counter<pos)
{
if(curr->link==NULL)
break;
curr=curr->link;
counter++;
}
if(counter==pos)
{
temp->link=curr->link;
curr->link=temp;
}
else
cout<<"Position not found";
}
}
temp->link=head;
head=temp;
}
#include<iostream.h>
struct node {
int data;
struct node *next;
}*head = NULL;
A. Sequential Search
#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:\n";
for(i=0;i<n;i++)
cin>>list[i];
cout<<"Enter key to search: \n";
cin>>key;
pos= Lsearch (list,n,key);
if(pos==-1)
cout<<"\n Element not found.";
else
cout<<"\n Element found at index. "<<pos;
}
C. Binary Search
#include<iostream>
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: \n";
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;
}
Go to Index Page 58 of 89
Go to Index Page 59 of 89
A. Insertion Sort
#include<iostream>
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:\n";
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;
Go to Index Page 60 of 89
return 0;
}
Go to Index Page 61 of 89
B. Selection Sort
#include<iostream>
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: \n";
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;
}
}
Go to Index Page 62 of 89
Go to Index Page 63 of 89
C. Bubble Sort
#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: \n";
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;
}
}
Go to Index Page 64 of 89
Go to Index Page 65 of 89
D. Quick Sort
#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;
}
}
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: \n";
for(i=0;i<n;i++)
Go to Index Page 66 of 89
cin>>list[i];
quicksort(list,0,n-1);
cout<<" After sorting\n";
for(i=0;i<n;i++)
cout<<list[i]<<endl;
return 0;
}
Go to Index Page 67 of 89
Go to Index Page 68 of 89
E. Merge Sort
#include<iostream>
using namespace std;
#define max 15
template<class T>
void merge(T a[],int l,int m,int u)
{
T b[max];
int i,j,k;
i=l; j=m+1;
k=l;
while((i<=m)&&(j<=u))
{
if(a[i]<=a[j])
{
b[k]=a[i];
++i;
}
else
{
b[k]=a[j];
++j;
}
++k;
}
if(i>m)
{
while(j<=u)
{
b[k]=a[j];
++j;
++k;
}
}
else
{
while(i<=m)
{
b[k]=a[i];
Go to Index Page 69 of 89
++i;
++k;
}
}
for(int r=l;r<=u;r++)
a[r]=b[r];
}
template <class T>
void mergesort(T a[],int p,int q)
{
int mid;
if(p<q)
{
mid=(p+q)/2;
mergesort(a,p,mid);
mergesort(a,mid+1,q);
merge(a,p,mid,q);
}
}
int main()
{
int n,i;
int list[30];
cout<<"Enter no of elements: \n";
cin>>n;
cout<<"Enter "<<n<<" numbers: \n";
for(i=0;i<n;i++)
cin>>list[i];
mergesort (list,0,n-1);
cout<<" After Sorting\n";
for(i=0;i<n;i++)
cout<<list[i]<<endl;
return 0;
}
Go to Index Page 70 of 89
Go to Index Page 71 of 89
F. Heap Sort
#include <iostream>
void heapify(int arr[], int n, int i)
{
int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i)
{
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
// main function to do heap sort
void heapSort(int arr[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i=n-1; i>=0; i--)
{
swap(arr[0], arr[i]);
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";
Go to Index Page 72 of 89
cin>>n;
cout<<"Enter "<<n<<" numbers: \n";
for(i=0;i<n;i++)
cin>>list[i];
heapSort(list, n);
cout << "Sorted array is: \n";
printArray(list, n);
return 0;
}
Go to Index Page 73 of 89
Go to Index Page 74 of 89
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Graph {
private:
vector<pair<int, edge> > G; // graph
vector<pair<int, edge> > T; // mst
int *parent;
int V; // number of vertices/nodes in graph
public:
Graph(int V);
void AddWeightedEdge(int u, int v, int w);
int find_set(int i);
void union_set(int u, int v);
void kruskal();
void print();
};
Graph::Graph(int V) {
parent = new int[V];
//i 0 1 2 3 4 5
//parent[i] 0 1 2 3 4 5
for (int i = 0; i < V; i++)
parent[i] = i;
G.clear();
T.clear();
}
void Graph::AddWeightedEdge(int u, int v, int w) {
G.push_back(make_pair(w, edge(u, v)));
}
int Graph::find_set(int i) {
Go to Index Page 75 of 89
g.AddWeightedEdge(2, 0, 4);
g.AddWeightedEdge(2, 1, 2);
g.AddWeightedEdge(2, 3, 3);
g.AddWeightedEdge(2, 5, 2);
g.AddWeightedEdge(2, 4, 4);
g.AddWeightedEdge(3, 2, 3);
g.AddWeightedEdge(3, 4, 3);
g.AddWeightedEdge(4, 2, 4);
g.AddWeightedEdge(4, 3, 3);
g.AddWeightedEdge(5, 2, 2);
g.AddWeightedEdge(5, 4, 3);
g.kruskal();
g.print();
return 0;
}
Go to Index Page 77 of 89
B. Prim’s Algorithm
#include <cstring>
#include <iostream>
using namespace std;
int G[V][V] = {
{0, 9, 75, 0, 0},
{9, 0, 95, 19, 42},
{75, 95, 0, 51, 66},
{0, 19, 51, 0, 31},
{0, 42, 66, 31, 0}};
int main() {
int no_edge; // number of edge
int selected[V];
no_edge = 0;
selected[0] = true;
return 0;
}
Go to Index Page 79 of 89
#include<iostream>
int ary[10][10],completed[10],n,cost=0;
void takeInput()
{
int i,j;
cout<<"Enter the number of villages: ";
cin>>n;
completed[i]=0;
}
int least(int c)
{
int i,nc=999;
int min=999,kmin;
{
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c] < min)
{
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i;
}
}
if(min!=999)
cost+=kmin;
return nc;
}
void mincost(int city)
{
int i,ncity;
completed[city]=1;
cout<<city+1<<"--->";
ncity=least(city);
if(ncity==999)
{
ncity=0;
cout<<ncity+1;
cost+=ary[city][ncity];
return;
}
mincost(ncity);
}
int main()
{
takeInput();
A. DFS
class Graph {
int numVertices;
list<int> *adjLists;
bool *visited;
public:
Graph(int V);
void addEdge(int src, int dest);
void DFS(int vertex);
};
// Initialize graph
Graph::Graph(int vertices) {
numVertices = vertices;
adjLists = new list<int>[vertices];
visited = new bool[vertices];
}
// Add edges
void Graph::addEdge(int src, int dest) {
adjLists[src].push_front(dest);
}
// DFS algorithm
void Graph::DFS(int vertex) {
visited[vertex] = true;
list<int> adjList = adjLists[vertex];
Go to Index Page 83 of 89
list<int>::iterator i;
for (i = adjList.begin(); i != adjList.end(); ++i)
if (!visited[*i])
DFS(*i);
}
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.DFS(2);
return 0;
}
Go to Index Page 84 of 89
B. BFS
#include <iostream>
#include <list>
class Graph {
int numVertices;
list<int>* adjLists;
bool* visited;
public:
Graph(int vertices);
void addEdge(int src, int dest);
void BFS(int startVertex);
};
// BFS algorithm
void Graph::BFS(int startVertex) {
visited = new bool[numVertices];
for (int i = 0; i < numVertices; i++)
visited[i] = false;
list<int> queue;
Go to Index Page 85 of 89
visited[startVertex] = true;
queue.push_back(startVertex);+
list<int>::iterator i;
while (!queue.empty()) {
int currVertex = queue.front();
cout << "Visited " << currVertex << " ";
queue.pop_front();
for (i = adjLists[currVertex].begin(); i !=
adjLists[currVertex].end(); ++i) {
int adjVertex = *i;
if (!visited[adjVertex]) {
visited[adjVertex] = true;
queue.push_back(adjVertex);
}
}
}
}
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.BFS(2);
return 0;
}
Go to Index Page 86 of 89
Go to Index Page 87 of 89
#include<iostream>
#include<stdio.h>
using namespace std;
#define INFINITY 9999
#define max 5
void dijkstra(int G[max][max],int n,int startnode);
int main() {
int
G[max][max]={{0,1,0,3,10},{1,0,5,0,0},{0,5,0,2,1},{3,0,2,0,6},{1
0,0,1,6,0}};
int n=5;
int u=0;
dijkstra(G,n,u);
return 0;
}
void dijkstra(int G[max][max],int n,int startnode) {
int cost[max][max],distance[max],pred[max];
int visited[max],count,mindistance,nextnode,i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
for(i=0;i<n;i++) {
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1) {
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i]) {
mindistance=distance[i];
nextnode=i;
}
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i]) {
distance[i]=mindistance+cost[nextnode][i];
Go to Index Page 88 of 89
pred[i]=nextnode;
}
count++;
}
for(i=0;i<n;i++)
if(i!=startnode) {
cout<<"\nDistance of node"<<i<<"="<<distance[i];
cout<<"\nPath="<<i;
j=i;
do {
j=pred[j];
cout<<"<-"<<j;
}while(j!=startnode);
}
}
Go to Index Page 89 of 89