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

Ds Record Complete

The document describes experiments on implementing various data structures in C++. It includes algorithms and source code for implementing a stack and queue using arrays, and a singly linked list. The results showed that insertion and deletion operations on stacks were successfully executed using C++.

Uploaded by

Sourav Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Ds Record Complete

The document describes experiments on implementing various data structures in C++. It includes algorithms and source code for implementing a stack and queue using arrays, and a singly linked list. The results showed that insertion and deletion operations on stacks were successfully executed using C++.

Uploaded by

Sourav Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

EXP.

NO: 1

Date:

IMPLEMENTATION OF STACK & QUEUE



AIM:
To implement insertion and deletion operations on Stack and Queue
using arrays on C++.



ALGORITHM:


Algorithm to PUSH an element in a stack:
Step 1: IF TOP = MAX-1, then

PRINT OVERFLOW Goto Step 4
[END OF IF]
Step 2: SET TOP = TOP + 1
Step 3: SET STACK [TOP] = VALUE
Step 4: END










Algorithm to POP an element from a stack:
Step 1: IF TOP = NULL, then PRINT UNDERFLOW
Go to Step 4
[END OF IF]
Step 2: SET VAL = STACK [TOP]
Step 3: SET TOP = TOP 1
Step 4: END


Algorithm for Peep Operation for STACK:
Step 1: IF TOP =NULL, then PRINT STACK IS EMPTY
Go TO Step 3
[END OF IF]
Step 2: RETURN STACK [TOP]
Step 3: END










Algorithm to insert an element in the Queue
Step 1: IF REAR=MAX-1, then;

Write OVERFLOW

[END OF IF]
Step 2: IF FRONT == -1 and REAR = -1, then;


SET FRONT = REAR = 0

ELSE


SET REAR = REAR + 1

[END OF IF]
Step 3: SET QUEUE[REAR] = NUM
Step 4: Exit





Algorithm to delete an element from the Queue
Step 1: IF FRONT = -1 OR FRONT > REAR, then;

Write UNDERFLOW
ELSE

SET FRONT = FRONT + 1 SET VAL = QUEUE[FRONT]

[END OF IF]
Step 2: Exit


















PROGRAM SOURCE:


Stack Program:
#include<iostream>
#include<stdlib.>
#include<conio.h>
using namespace std;
#define SIZE 5
void push(int *STACK,int x);
void pop(int *a);
void display(int *a);
int TOP=-1;
int STACK[SIZE];
void main()
{
int x,ch;
clrscr();
while(1)
{
cout<<Select Your Choice:\n;
cout<<(1) PUSH\n;
cout<<(2) POP\n;
cout<<(3) PEEK\n;
cout<<(4) QUIT\n
cout<<Enter Your Choice\n;
cin>>ch;
switch(ch)
{
case 1:
cout<<Enter Element:;
cin>>x;
push(STACK,x);
break;
case 2:
pop(STACK);
break;
case 3:
display(STACK);
break;
case 4:
exit(0);
}
}

void push(int *STACK,int x)


{

if(TOP>=SIZE-1)
cout<<Stack is Overflow;
else
{TOP=TOP+1;
STACK[TOP]=x;
}

}
void pop(int *STACK)
{ int x;
if(TOP==-1)
cout<<Stack is Underflow;
else
{ cout<<Deleted Element is: <<STACK[TOP];
TOP=TOP-1;
}
}
void display(int *STACK)
{ int i;
if(TOP==-1)
cout<<Stack is Empty\n;
else
{ for(i=TOP;i>=0;i--)
cout<<STACK[i]<<\n;
}
}

Queue Program

#include<iostream.h>
#include<conio.h>
class queue
{
public:
int q[5],front,rear,x,result;
void enq();
void dque();
void disp();
queue()
{
front=0;
rear=0;
}
};
void queue::enq()
{
if(rear>=5)
cout<<"\nQueue overflow!!\n";
else
{
cout<<"\nEnter the number to be inserted: ";
cin>>x;
rear++;
q[rear]=x;
cout<<"\nNumber pushed in the queue:"<<q[rear];
}
}
void queue::dque()
{
if(rear==0)
cout<<"\nQueue underflow!!\n";
else
{
if(front==rear)
{
front=0;
rear=0;
}
else
front++;
}
cout<<"\nDeleted element is:";
result=q[front];
cout<<result;
}

void queue::disp()
{
if(rear==0)
cout<<"\nQueue underflow!!\n";
else
cout<<"\nContents of queue is:";
for(int i=front+1;i<=rear;i++)
cout<<q[i]<<"\t";
}
void main()
{
int c;
queue qu;
clrscr();
cout<<"\n*****";
cout<<"\nQUEUE";
cout<<"\n*****";

do
{
cout<<"\n1.Insertion\n2.Deletion\n3.Display\n";
cout<<"\nEnter your choice:";
cin>>c;
switch(c)
{
case 1:
qu.enq();
break;
case 2:
qu.dque();
break;
case 3:
qu.disp();
break;
default:
cout<<"\nInvalid choice!!\n";
}
}
while(c<4);
getch();

RESULT:
The C++ program to implement insertion and deletion operations on Stacks were
successfully executed using C++.

EXP.NO: 2

Date:




SINGLY LINKED LIST



AIM:
To implement Singly Linked List using C++.

ALGORITHM:

Algorithm to insert a new node after a node that has value num
Step 1: IF AVAIL = NULL, then

Write OVERFLOW Go to Step 12

[END OF IF]
Step 2: SET New_Node = AVAIL
Step 3: SET AVAIL = AVAIL->NEXT
Step 4: SET New_Node->DATA = VAL
Step 5: SET PTR = START
Step 6: SET PREPTR = PTR
Step 7: Repeat Steps 8 and 9 while PREPTR->DATA != NUM
Step 8: SET PREPTR = PTR
Step 9: SET PTR = PTR->NEXT
[END OF LOOP]
Step 10: PREPTR->NEXT = New_Node
Step 11: SET New_Node->NEXT = PTR
Step 12: EXIT

Algorithm to delete the node after a given node from the linked list
Step 1: IF START = NULL, then

Write UNDERFLOW Go to Step 10
[END OF IF]
Step 2: SET PTR = START
Step 3: SET PREPTR = PTR
Step 4: Repeat Step 5 and 6 while PRETR->DATA != NUM
Step 5: SET PREPTR = PTR
Step 6: SET PTR = PTR->NEXT
[END OF LOOP]
Step 7: SET TEMP = PTR->NEXT
Step 8: SET PREPTR->NEXT = TEMP->NEXT
Step 9: FREE TEMP
Step 10: EXIT

PROGRAM SOURCE:

#include<iostream>
#include<conio.h>
struct node{
int data;
node *next;
};
node *start, *ptr, *new_node;
void insertAtFirst(){
new_node->next = start;
start = new_node;
}
void insertAtLast(){
ptr = start;
while (ptr->next != NULL)
ptr = ptr->next;
ptr->next = new_node;
}
void insertAtN(int position){
ptr = start;
int ctr = 1;
while (ptr->next != NULL && ctr < position-1){
ptr = ptr->next;
ctr++;
}
new_node->next = ptr->next;
ptr->next = new_node;
}
void insert(){
clrscr();
int choice, value;
cout << "What value to insert to the list?\n@";
cin >> value;
new_node = new node;
new_node->data = value;
new_node->next = NULL;
if (start == NULL){
start = new_node;
cout << "This is going to be your first node.\n";

getch();
return;

do{

clrscr();
cout << "Where should I insert the value?\n"
<< "1. At the first position\n"
<< "2. At a custom position\n"
<< "3. At the last position\n"
<< "4. Return to the previous menu\n";
cin >> choice;
switch (choice){
case 1:insertAtFirst();
break;
case 2:int position;
cout << "\n\nType in a position number\n"
<< "(Giving a position greater than the
last position will put the number in the last position)\n";
do{ cin >> position; } while (position < 1);
{

}
insertAtN(position);
break;
case 3:insertAtLast();
break;
default: break;
}
} while (choice < 1 && choice > 4);

void removeFirst(){
ptr = start;
start = start->next;
delete ptr;
}
void removeLast(){
ptr = start;
while (ptr->next->next != NULL)
ptr = ptr->next;
node *temp = ptr->next;
ptr->next=NULL;
delete temp;
}
void removeFromN(int position){
ptr = start;

int ctr = 1;
while (ptr->next->next != NULL && ctr<position-1){
ptr = ptr->next;
ctr++;
}
node *temp = ptr->next;
ptr->next = ptr->next->next;
delete temp;
}
void remove(){
clrscr();
if (start == NULL){
cout << "The list is empty.\n";
getch();
return;
}
if (start->next == NULL){
delete start;
start = NULL;
cout << "There was only one node in your list and we
deleted it.\n";
getch();
return;
}
int choice;
do{
clrscr();
cout << "Where should I delete the element from?\n"
<< "1. First\n"
<< "2. Custom Position\n"
<< "3. Last\n"
<< "4. Return to Main Menu\n";
cin >> choice;
switch (choice){
case 1:removeFirst();
break;
case 2:int position;
cout << "Enter the position from which the
element has to be deleted...\n";
do{ cin >> position; } while (position < 1);
{
}
removeFromN(position);
break;
case 3:removeLast();
break;
default: break;

}
} while (choice < 1 && choice>4);

void displayList(){
ptr = start;
cout << endl << endl;
if (start != NULL){
cout << "The List:\n";
while (true){
cout << ptr->data << "\t";
if (ptr->next == NULL) break;
ptr = ptr->next;
}
}
else{
cout << "The list is empty.\n";
}

cout << endl;


getch();

void menu(){
int choice;
do{
clrscr();
cout << "Choose an option:\n"
<< "1. Insert a node\n"
<< "2. Delete a node\n"
<< "3. Display the List\n"
<< "4. Exit Program\n";
cin >> choice;
switch (choice){
case 1:
insert();
break;
case 2: remove();
break;
case 3:
displayList();
break;
default: break;
}
} while (choice != 4);
}

void main(){
start = NULL;
menu();
getch();
}

RESULT:
The C++ program to implement simply linked list has been successfully designed
and executed using C++.


EXP.NO:
3

Date:

DOUBLY LINKED LIST




AIM:
To implement doubly linked list using C++.

ALGORITHM:

















Algorithm to insert a new node after a node that has value NUM
Step 1: IF AVAIL = NULL, then

Write OVERFLOW

Go to Step 11
[END OF IF]
Step 2: SET New_Node = AVAIL
Step 3: SET AVAIL = AVAIL->NEXT
Step 4: SET New_Node->DATA = VAL
Step 5: SET PTR = START
Step 6: Repeat Step 8 while PTR->DATA != NUM
Step 7: SET PTR = PTR->NEXT
[END OF LOOP]
Step 8: New_Node->NEXT = PTR->NEXT
Step 9: SET New_Node->PREV = PTR
Step 10: SET PTR->NEXT = New_Node
Step 11: EXIT

Algorithm to delete the node after a given node from the doubly linked list
Step 1: IF START = NULL, then

Write UNDERFLOW

Go to Step 9
[END OF IF]
Step 2: SET PTR = START
Step 3: Repeat Step 4 while PTR->DATA != NUM
Step 4: SET PTR = PTR->NEXT
[END OF LOOP]
Step 5: SET TEMP = PTR->NEXT
Step 6: SET PTR->NEXT = TEMP->NEXT
Step 7: SET TEMP->NEXT->PREV = PTR
Step 8: FREE TEMP
Step 9: EXIT

PROGRAM SOURCE:

#include<iostream.h>
#include<conio.h>
struct node{
int data;
node *next;
node *prev;
};
node *start, *ptr, *new_node;
void insertAtFirst(){
new_node->next = start;
start->prev = new_node;
start = start->prev;
}
void insertAtLast(){
ptr = start;
while (ptr->next != NULL)
ptr = ptr->next;

ptr->next = new_node;
new_node->prev = ptr;

void insertAtN(int position){


ptr = start;
int ctr = 1;
while (ptr->next != NULL && ctr < position){
ptr = ptr->next;
ctr++;
}

if (ptr->prev == NULL){
insertAtFirst();
return;
}
if (ptr->next == NULL){
insertAtLast();
return;
}
ptr->prev->next = new_node;
new_node->prev = ptr->prev;
new_node->next = ptr;
ptr->prev = new_node;

void insert(){
clrscr();
int choice, value;
cout << "What value to insert to the list?\n@";
cin >> value;
new_node = new
new_node->data
new_node->prev
new_node->next

node;
= value;
= NULL;
= NULL;

if (start == NULL){
start = new_node;
cout << "This is going to be your first node.\n";
getch();
return;
}
do{

clrscr();
cout << "Where should I insert the value?\n"
<< "1. At the first position\n"
<< "2. At a custom position\n"
<< "3. At the last position\n"
<< "4. Return to the previous menu\n";
cin >> choice;
switch (choice){
case 1:insertAtFirst();
break;
case 2:int position;
cout << "\n\nType in a position number\n"
<< "(Giving a position greater than the
last position will put the number in the last position)\n";
do{ cin >> position; } while (position < 1);
{

}
insertAtN(position);
break;
case 3:insertAtLast();
break;
default: break;
}
} while (choice < 1 && choice > 4);

void removeFirst(){
ptr = start;
start = start->next;
delete ptr;}

void removeLast(){
ptr = start;
while (ptr->next != NULL)
ptr = ptr->next;
if (ptr->prev != NULL) ptr->prev->next = NULL;
delete ptr;
}
void removeFromN(int position){
ptr = start;
int ctr = 1;
while (ptr->next != NULL && ctr<position){
ptr = ptr->next;
ctr++;
}
if (ptr->next == NULL){
removeLast();
return;
}
if (ptr->prev == NULL){
removeFirst();
return;
}
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
ptr->next->prev = NULL;
delete ptr;
}
void remove(){
clrscr();
if (start == NULL){
cout << "The list is empty.\n";
getch();
return;
}
if (start->next == NULL){
delete start;
start = NULL;
cout << "There was only one node in your list and we
deleted it.\n";
getch();
return;
}
int choice;

do{
clrscr();
cout << "Where should I delete the element from?\n"
<< "1. First\n"
<< "2. Custom Position\n"
<< "3. Last\n"
<< "4. Return to Main Menu\n";
cin >> choice;
switch (choice){
case 1:removeFirst();
break;
case 2:int position;
cout << "Enter the position from which the
element has to be deleted...\n";
do{ cin >> position; } while (position < 1);
{
}
removeFromN(position);
break;
case 3:removeLast();
break;
default: break;
}
} while (choice < 1 && choice>4);
}
void displayList(){
ptr = start;
cout << endl << endl;
if (start != NULL){
cout << "The List:\n";
while (true){
cout << ptr->data << "\t";
if (ptr->next == NULL) break;
ptr = ptr->next;
}
}
else{
cout << "The list is empty.\n";
}

cout << endl;


getch();

void menu(){
int choice;
do{
clrscr();
cout << "Choose an option:\n"
<< "1. Insert a node\n"
<< "2. Delete a node\n"
<< "3. Display the List\n"
<< "4. Exit Program\n";
cin >> choice;
switch (choice){
case 1:
insert();
break;
case 2: remove();
break;
case 3:
displayList();
break;
default:
break;
}
} while (choice != 4);
}
void main(){
start = NULL;
menu();
getch();
}
















RESULT:
The C++ program to implement Doubly Linked List was successfully designed
and executed.

EXP.NO:
4


BINARY TREE IMPLEMENTATIONS
Date:
AND TRAVERSALS




AIM:
To perform Binary Tree Implementations and Traversals using C++.


ALGORITHM:


PreOrder Traversal Algorithm:


Step 1: If ROOT = NULL then

Write Tree is Empty
Else
Write ROOT->INFO
Step 2: If ROOT->LPTR NULL then
Call PREORDER (ROOT->LPTR)
Step 3: If ROOT->RPTR NULL then
Call PREORDER (ROOT->RPTR)


InOrder Traversal Algorithm:
Step 1: If ROOT = NULL then
Write Tree is Empty
Step 2: If ROOT->LPTR NULL then
Call INORDER (ROOT->LPTR)
Step 3: Write ROOT->INFO
Step 4: If ROOT->RPTR NULL then
Call INORDER (ROOT->RPTR)


PostOrder Traversal Algorithm:
Step 1: If ROOT = NULL then
Write Tree is Empty
Step 2: If ROOT->LPTR NULL then
Call POSTORDER (ROOT->LPTR)
Step 3: If ROOT->RPTR NULL then
Call POSTORDER (ROOT->RPTR)
Step 4: Write ROOT->INFO


PROGRAM SOURCE:
#include<conio.h>
#include<stdlib.h>
#include<iostream.h>
struct node
{
int info;
struct node *left;
struct node *right;
};
typedef struct node tree ;
tree *root=NULL;
class BIN
{
int num;
tree *p,*prev,*temp;
public:
void insert();
void inorder(tree *);
void postorder(tree *);
void preorder(tree *);
void display();
};
void BIN:: insert()
{
p=new(tree);
cout<<"\n Enter number:";
cin>>num;
p->info=num;
p->left=p->right=NULL;
if(root==NULL)
{
root=p;
return;
}
temp=root;
while(temp!=NULL)
{
if(num>=temp->info)
{
prev=temp;
temp=temp->right;
}
else
{
prev=temp;
temp=temp->left;
}
}

if(num>=prev->info)
prev->right=p;
else
prev->left=p;
}
void BIN::preorder(tree *temp)
{
if(temp!=NULL)
{
cout<<" "<<temp->info;
preorder(temp->left);
preorder(temp->right);
}
}
void BIN:: inorder(tree *temp)
{
if(temp!=NULL)
{
inorder(temp->left);
cout<<" "<<temp->info;
inorder(temp->right);
}
}
void BIN::postorder(tree *temp)
{
if(temp!=NULL)
{
postorder(temp->left);
postorder(temp->right);
cout<<" "<<temp->info;
}
}
void BIN:: display()
{
if(root==NULL)
{
cout<<"\n ***EMPTY TREE**** \n";
return;
}
cout<<"\n\n THE PREORDER DISPLAY IS:
";
preorder(root);
cout<<"\n\n THE INORDER DISPLAY IS:
";
inorder(root);
cout<<"\n\n THE POSTORDER DISPLAY IS:
";
postorder(root);
}

void main()
{
BIN o;
int ch=1;
int count=0;
clrscr();
while(ch)
{
cout<<"\n***********MENU***********";
cout<<"\n1:INSERT-IN-TREE\n2:DISPLAY\n3.QUIT\n";
cout<<"\nEnter your choice:\n";
cin>>ch;
switch(ch)
{
case 1:clrscr();
count++;
o.insert();
break;
case 2:clrscr();
cout<<"\n\n THE NUMBER OF NODES IN THE BST is "<< count;
o.display();
break;
case 3:exit(0);
}
}
getch();
}














RESULT:
The Binary Tree Implementations and Traversals were successfully designed
and executed using C++.


EXP.NO: 5

SORTING TECHNIQUES:
Date:
INSERTION , SELECTION SORT




AIM:
To write a C++ program to implement Insertion and selection sort on arrays.

ALGORITHM:


Insertion sort:


Step 1:
Start

Get array elements from User
Step 2:

Step 3:
Repeat up to step 6 for I = 1 to N

Step 4:
KEY = a [I]


Step 5:
Repeat step 6 for J = I to 0

If KEY < a [J - 1] then

TEMP = a [J]

Step 6:
a [J] = a [J - 1]

a [J - 1] = TEMP




Selection Sort


Step 1:
Start

Step 2:
Get array elements from User

Step 3:
Repeat up to Step 7 for I = 0 to N-1


MIN = a [I]
Step 4:

POS=I

Step 5:
Repeat step 5 for J=I+1 to N

If a [J] < MIN then

Step 6:
MIN =a [J]

POS = J

TEMP = a [I]

Step 7:
a [I] = a [POS]
a [POS] = TEMP


PROGRAM SOURCE:


#include<iostream>
using namespace std;
void insertArray(int *array,int length){
int i;
cout << "Please enter the (" << length << ")values for the
array...\n";
for (i = 0; i < length; i++){
cout << "@";
cin >> array[i];
}
}
int
insertionSort (int arr[], int length){
int j, temp;
for (int i = i; i < length; i++){
j = i;
while (j>0 && arr[j]<arr[j-1]){
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j--;
}
}
return 0;
}
int selectSort(int arr[], int n)
{
int pos_min,temp;
for (int i=0; i < n-1; i++)
{pos_min = i;
for (int j=i+1; j < n; j++)
{if (arr[j]<arr[pos_min])
pos_min=j;
}
if (pos_min != i)
{temp = arr[i];
arr[i] = arr[pos_min];
arr[pos_min] = temp;
}
}
return 0;
}

int main()
{
int *array,length, choice;
cout <<"What is the length of the array?\t";
cin >> length;
array = new int[length];
insertArray(array,length);
int i;
cout <<"The unsorted array \n";
for (i = 0; i < length; i++)
cout<< "[" << i << "]\t" << array[i] << endl;
cout<<"\n\nEnter your choice of
Sorting:\n1.Insertion\n2.Selection\n3.Exit";
cin>>choice;
switch(choice)
{
case 1: { insertionSort(array,length);
cout <<"The sorted list (Insertion
Sort)\n";
for (i = 0; i < length;i++)
cout << "["<< i << "]\t" << array[i] << endl; break;
}
case 2: { selectSort(array,length);
cout << "The sorted list (Selection
Sort\n";

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


cout << "[" << i << "]\t" << array[i] << endl; break;

}
return 0 ;
}

}
case 3: exit(0);

RESULT:
The C++ program to implement Insertion and Selection sorts on array, was
successfully designed and executed.

EXP.NO: 6


SORTING TECHNIQUES:
Date:
QUICK SORT, MERGE SORT




AIM:
To write a C++ program to implement Quick Sort and Merge Sort on arrays.


ALGORITHM:



Quick sort:

Step 1: Start
Step 2: Get array elements from User
Step 3: PIVOT=(LOW+HIGH)/2
Step 4: Repeat thru Step 8 while LOW<HIGH
Step 5: Repeat while A[LOW]<A[PIVOT]
LOW=LOW+1
Step 6: Repeat while A[HIGH]>A[PIVOT]
HIGH=HIGH-1
Step 7: if (LOW<HIGH) then

A[LOW] <--> A[HIGH]

LOW=LOW+1

HIGH=HIGH-1
Step 8: IF(FIRST<HIGH)

call QUICK_SORT(A,FIRST,HIGH)
IF (LOW<LAST)

call QUICK_SORT(A,LOW,LAST)
Step 9: Stop













Merge sort:

Step 1: Start
Step 2: Get array elements from user.
Step 3: I = 0

J = 0

K = 0
Step 4: Repeat
Step 5: while I <= N1 1 and J <= N2 1
Step 6: If List1 [I] < List2 [J] then

List3[K] = List1 [I]


I = I + 1


K= K + 1

Else


List3 [K] = List2 [J]


J = J + 1


K = K + 1
Step 7: Repeat Step 7 while I <= N1-1
Step 8: List3[K] = List1 [I]

I = I + 1

K= K + 1
Step 9: Repeat Step 9 while J <= N2-1
Step 10: List3[K] = List2[J]

J = J + 1

K= K + 1

















PROGRAM SOURCE:

#include<iostream.h>
#include<conio.h>
void insertArray(int *array,int length){
int i;
cout << "Please enter the (" << length << ")values for the
array...\n";
for (i = 0; i < length; i++){
cout << "@";
cin >> array[i];
}
}
int split(int *array, int low, int high){
int leftIndex = low + 1;
int rightIndex = high;
int pivot = array[low]; //Puts the pivot
element
int temp;
while (true){
while (leftIndex <= rightIndex){
if (array[leftIndex] > pivot)
break;
else
leftIndex++;
}
while (rightIndex > leftIndex){
if (array[rightIndex] <= pivot)
break;
else
rightIndex--;
}
if (leftIndex >= rightIndex) break;
temp = array[leftIndex];
array[leftIndex++] = array[rightIndex];
array[rightIndex--] = temp;
}
array[low] = array[leftIndex - 1];
array[leftIndex - 1] = pivot;
return leftIndex - 1;

as

the

first

}
void quickSort(int *array, int low, int high){
if ((high-low) <= 0) return;
int pivot=split(array,low,high);
quickSort(array, low, pivot-1);// Left sub-array recursion
quickSort(array, pivot + 1, high); //Right sub-array
recursion
}
void merge(int *array,int low, int middle, int high){
int i=low;
int j=middle+1;
int k;
int position=low;
int *tempArray;
while (i<=middle && j<=high){
if (array[i] <= array[j])
tempArray[position++] = array[i++];
else
tempArray[position++] = array[j++];
}
if (i > middle)
for (k = j; k <= high; k++)
tempArray[position++] = array[k];
else
for (k = i; k <= middle; k++)
tempArray[position++] = array[k];
for (k = low; k <= high; k++)

array[k]=tempArray[k];

}
void mergeSort(int *array,int low, int high){
int middle;
if (low < high){
middle = (low + high) / 2;
mergeSort(array,low, middle);
mergeSort(array,middle + 1, high);
merge(array,low, middle, high);
}}

void main()
{
int *array,length, choice;
cout << "What is the length of the array?\t";
cin >> length;
array = new int[length];
insertArray(array,length);
clrscr();
int i;
cout << "The unsorted array ...\n";
for (i = 0; i < length; i++)
cout << "[" << i << "]\t" << array[i] << endl;
cout<<"\n\nEnter
your
Sorting:\n1.QuickSort\n2.MergeSort";
cin>>choice;

choice

of

switch(choice)
{
case 1: { quickSort(array, 0, length-1);
cout << "The sorted list (QuickSort)...\n";
for (i = 0; i < length;i++)
cout << "[" << i << "]\t" << array[i] << endl;
break;
}
case 2: { mergeSort(array,0, length-1);
cout << "The sorted list (MergeSort...\n";
for (i = 0; i < length;i++)
cout << "[" << i << "]\t" << array[i] << endl;
break;
}
}
getch();
}



RESULT:
The C++ program to implement Quick and Merge Sort on arrays, was
successfully designed and executed.

EXP.NO:

7


GREEDY METHOD
Date:
KNAPSACK PROBLEM




AIM:
To write a C++ program to implement a solution for the Knapsack problem
using Greedy Method.


ALGORITHM:


FractionalKnapsack(S,W):
Step 1: Input: Set S of items i with weight wi and benefit bi all positive.
Knapsack capacity W>0.

Step 2: Output: Amount xi of i that maximizes the total benefit without
exceeding the capacity.

Step 3: for each i in S do
o xi 0 { for items not chosen in next phase }
o vi bi/wi { the value of item i "per pound" }
o w W { remaining capacity in knapsack }

Step 4: while w > 0 do
o remove from S an item of maximal value { greedy choice }
o xi min(wi,w) { can't carry more than w more }
o w w-xi

PROGRAM SOURCE:

# include<iostream>
void knapsack(int n, float weight[], float profit[], float
capacity) {
float x[20], tp = 0;
int i, j, u;
u = capacity;
for (i = 0; i < n; i++)
x[i] = 0.0;
for (i = 0; i < n; i++) {
if (weight[i] > u)
break;
else {
x[i] = 1.0;
tp = tp + profit[i];
u = u - weight[i];
}
}
if (i < n)
x[i] = u / weight[i];
tp = tp + (x[i] * profit[i]);
cout<<"\nThe result vector is:- ";
for (i = 0; i < n; i++)
cout<<"\t"<<x[i];
cout<<"\nMaximum profit is:-<<tp;
}
int main() {
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;
cout<<"\nEnter the no. of objects:- ";
cin>>num;
cout<<"\nEnter the wts and profits of each object:- ";
for (i = 0; i < num; i++) {
cin>>weight[i]>>profit[i];
}
cout<<"\nEnter the capacityacity of knapsack:- ";
cin>>capacity;

for (i = 0; i < num; i++) {


ratio[i] = profit[i] / weight[i];
}
for (i = 0; i < num; i++) {
for (j = i + 1; j < num; j++) {
if (ratio[i] < ratio[j]) {
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;

}
}

temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;

knapsack(num, weight, profit, capacity);


return(0);
}


















RESULT:
The C++ program to implement a solution for the Knapsack problem using
Greedy Method was successfully executed.

EXP.NO:

8

Date:


TRAVERSAL TECHNIQUE
BREADTH FIRST PROBLEM &
DEPTH FIRST PROBLEM



AIM:
To write a C++ program to implement Breadth-first search (BFS) and Depth-
First search (DFS) algorithms for travsering in graph date Structure.


ALGORITHM:


Algorithm for breadth-first search in a graph G beginning at a starting node A

Step 1: SET STATUS = 1 (ready state) for each node in G.
Step 2: Enqueue the starting node A and set its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until QUEUE is empty
Step 4: Dequeue a node N. Process it and set its STATUS = 3 (processed state).
Step 5: Enqueue all the neighbors of N that are in the ready state (whose STATUS

=1) and set their STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT




Algorithm for depth-first search in a graph G beginning at a starting node A

Step 1: SET STATUS = 1 (ready state) for each node in G.
Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until STACK is empty
Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state).
Step 5: Push on to the stack all the neighbors of N that are in the ready state (whose

STATUS = 1) and set their STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT




PROGRAM SOURCE:

1. Breadth First Method


#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v) {
for (i=1;i<=n;i++)
if(a[v][i] && !visited[i])
q[++r]=i;
if(f<=r) {
printf("\n The node visited %d:\n",q[f]);
visited[q[f]]=1;
bfs(q[f++]);
}
}
int main() {
int v;int flag=0;
//clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for (i=1;i<=n;i++) {
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The node which are reachable are:\n");
for (i=1;i<=n;i++)
if(visited[i]==1)
{
flag=1;
printf("%d\t",i);
}
if(!flag)
{
printf("Null");
printf("\n BFS is Not possible for this node");
}
return 0;
}}


2. Depth First Method

#include<stdio.h>
int a[20][20],reach[20],n;
void dfs(int v)
{
int i;
reach[v]=1;
for(i=1;i<=n;i++)
if(a[v][i] && !reach[i])
{
printf("\n %d->%d",v,i);
dfs(i);
}
}
int main()
{
int i,j,count=0;
printf("\n Enter number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
reach[i]=0;
for(j=1;j<=n;j++)
a[i][j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1);
printf("\n");
for(i=1;i<=n;i++)
{
if(reach[i])
count++;
}
if(count==n)
printf("\n Graph is connected");
else
printf("\n Graph is not connected");
return 0;
//getch();
}








































RESULT:
The C++ program to implement Breadth-first search (BFS) and
Depth-First search (DFS) algorithms for travsering in graph date Structure was
designed and executed successfully.

EXP.NO: 9

Date:

BACKTRACKING:
8 QUEENS PROBLEM

AIM:
To write a C++ program to solve the 8-Queens Problem by implementing
Backtracking Algorithms.


ALGORITHM:

Step 1: Start in the leftmost column


Step 2: If all queens are placed
return true
Step 3: Try all rows in the current column. Do following for every tried row.
a) If the queen can be placed safely in this row then mark this [row,column]
as part of the solution and recursively check if placing queen here leads
to a solution.
b) If placing queen in [row, column] leads to a solution then return true.
c) If placing queen doesn't lead to a solution then umark this [row,column]
(Backtrack) and go to step (a) to try other rows.
Step 4: If all rows have been tried and nothing worked, return false to trigger
backtracking.


















PROGRAM SOURCE:


#include <iostream>
#include <stdio>
#include <stdlib>
#define N 8
using namespace std;
void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
cout<<board[i][j]<<" ";
cout<<endl;
}
}
/* check if a queen can be placed on board[row][col]*/
bool isSafe(int board[N][N], int row, int col)
{
int i, j;
for (i = 0; i < col; i++)
{
if (board[row][i])
return false;
}
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if (board[i][j])
return false;
}
for (i = row, j = col; j >= 0 && i < N; i++, j--)
{
if (board[i][j])
return false;
}
return true;
}

/*solve N Queen problem */


bool solveNQUtil(int board[N][N], int col)
{
if (col >= N)
return true;
for (int i = 0; i < N; i++)
{
if ( isSafe(board, i, col) )
{
board[i][col] = 1;
if (solveNQUtil(board, col + 1) == true)
return true;
board[i][col] = 0;
}
}
return false;
}
/* solves the N Queen problem using Backtracking.*/
bool solveNQ()
{
int board[N][N] = {0};
if (solveNQUtil(board, 0) == false)
{
cout<<"Solution does not exist"<<endl;
return false;
}
printSolution(board);
return true;
}
// Main
int main()
{
solveNQ();
return 0;
}

RESULT:
The C++ program to solve the 8-Queens Problem by implementing
Backtracking Algorithms was designed and executed successfully.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy