Professional Documents
Culture Documents
RITIK DESWAL (19CSE043) DAA PRACTICAL FILE - Ruchi CSE
RITIK DESWAL (19CSE043) DAA PRACTICAL FILE - Ruchi CSE
RITIK DESWAL (19CSE043) DAA PRACTICAL FILE - Ruchi CSE
OF ALGORITHM
PRACTICAL FILE
GANGA INSTITUTE OF
TECHNOLOGY AND
MANAGEMENT
(2022-2023)
OUTPUT:-
PROGRAM-2
Aim:- Write a C++ Program to perform Merge Sort using Divide and
Conquer Technique
#include<iostream>
using namespace std;
void swapping(int &a, int &b) {
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void merge(int *array, int l, int m, int r) {
int i, j, k, nl, nr;
nl = m-l+1; nr = r-m;
int larr[nl], rarr[nr];
for(i = 0; i<nl; i++)
larr[i] = array[l+i];
for(j = 0; j<nr; j++)
rarr[j] = array[m+1+j];
i = 0; j = 0; k = l;
while(i < nl && j<nr) {
if(larr[i] <= rarr[j]) {
array[k] = larr[i];
i++;
}else{
array[k] = rarr[j];
j++;
}
k++;
}
while(i<nl) {
array[k] = larr[i];
i++; k++;
}
while(j<nr) {
array[k] = rarr[j];
j++; k++;
}
}
void mergeSort(int *array, int l, int r) {
int m;
if(l < r) {
int m = l+(r-l)/2;
mergeSort(array, l, m);
mergeSort(array, m+1, r);
merge(array, l, m, r);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
mergeSort(arr, 0, n-1);
cout << "Array after Sorting: ";
display(arr, n);
}
OUTPUT:-
PROGRAM-3
Aim:- Write a C++ Program to find all the Shortest Path using Floyd
Warshall Algorithm
#include <iostream>
#include <climits>
#include <iomanip>
using namespace std;
#define N 4
#define M INT_MAX
void printPath(int path[][N], int v, int u)
{
if (path[v][u] == v)
return;
printPath(path, v, path[v][u]);
cout << path[v][u] << " ";
}
void printSolution(int cost[N][N], int path[N][N])
{
for (int v = 0; v < N; v++)
{
for (int u = 0; u < N; u++)
{
if (u != v && path[v][u] != -1)
{
cout << "Shortest Path from " << v << " -> " << u << " is ("
<< v << " ";
printPath(path, v, u);
cout << u << ")" << endl;
}
}
}
}
void floydWarshall(int adjMatrix[][N])
{
int cost[N][N], path[N][N];
for (int v = 0; v < N; v++)
{
for (int u = 0; u < N; u++)
{
cost[v][u] = adjMatrix[v][u];
if (v == u)
path[v][u] = 0;
else if (cost[v][u] != INT_MAX)
path[v][u] = v;
else
path[v][u] = -1;
}
}
for (int k = 0; k < N; k++)
{
for (int v = 0; v < N; v++)
{
for (int u = 0; u < N; u++)
{
if (cost[v][k] != INT_MAX && cost[k][u] != INT_MAX
&& cost[v][k] + cost[k][u] < cost[v][u])
{
cost[v][u] = cost[v][k] + cost[k][u];
path[v][u] = path[k][u];
}
}
if (cost[v][v] < 0)
{
cout << "Negative Weight Cycle Found!!";
return;
}
}
}
printSolution(cost, path);
}
int main()
{
int adjMatrix[N][N] =
{
{ 0, M, -2, M },
{ 4, 0, 3, M },
{ M, M, 0, 2 },
{ M, -1, M, 0 }
};
floydWarshall(adjMatrix);
return 0;
}
OUTPUT:-
PROGRAM-4
Aim:- Write a C++ Program to solve the Knapsack Problem using
Greedy Approach
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef struct {
int v;
int w;
float d;
} Item;
void input(Item items[],int sizeOfItems) {
cout << "Enter total "<< sizeOfItems <<" item's values and weight" <<
endl;
for(int i = 0; i < sizeOfItems; i++) {
cout << "Enter "<< i+1 << " V ";
cin >> items[i].v;
cout << "Enter "<< i+1 << " W";
cin >> items[i].w;
}
}
void display(Item items[], int sizeOfItems) {
int i;
cout << "values: ";
for(i = 0; i < sizeOfItems; i++) {
cout << items[i].v << "\t";
}
cout << endl << "weight: ";
for (i = 0; i < sizeOfItems; i++) {
cout << items[i].w << "\t";
}
cout << endl;
}
bool compare(Item i1, Item i2) {
return (i1.d > i2.d);
}
float knapsack(Item items[], int sizeOfItems, int W) {
int i, j, pos;
Item mx, temp;
float totalValue = 0, totalWeight = 0;
for (i = 0; i < sizeOfItems; i++) {
items[i].d = items[i].v / items[i].w;
}
sort(items, items+sizeOfItems, compare);
for(i=0; i<sizeOfItems; i++) {
if(totalWeight + items[i].w<= W) {
totalValue += items[i].v ;
totalWeight += items[i].w;
} else {
int wt = W-totalWeight;
totalValue += (wt * items[i].d);
totalWeight += wt;
break;
}}
cout << "Total weight in bag " << totalWeight<<endl;
return totalValue; }
int main() {
int W;
Item items[4];
input(items, 4);
cout << "Entered data \n";
display(items,4);
cout<< "Enter Knapsack weight \n";
cin >> W;
float mxVal = knapsack(items, 4, W);
cout << "Max value for "<< W <<" weight is "<< mxVal;
}
OUTPUT:-
PROGRAM-5
Aim:- Write a C++ Program for Shortest Path using Dijkstra’s
Algorithm
#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},{10,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];
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);
}
}
OUTPUT:-
PROGRAM-6
Aim:- Write a C++ Program to find Minimum Spanning Tree using
Prim’s Algorithm
#include<iostream>
using namespace std;
const int V=6;
int min_Key(int key[], bool visited[])
{
int min = 999, min_index;
for (int v = 0; v < V; v++) {
if (visited[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}
int print_MST(int parent[], int cost[V][V])
{
int minCost=0;
cout<<"Edge \tWeight\n";
for (int i = 1; i< V; i++) {
cout<<parent[i]<<" - "<<i<<" \t"<<cost[i][parent[i]]<<" \n";
minCost+=cost[i][parent[i]];
}
cout<<"Total cost is:"<<minCost;
}
void find_MST(int cost[V][V])
{
int parent[V], key[V];
bool visited[V];
for (int i = 0; i< V; i++) {
key[i] = 999;
visited[i] = false;
parent[i]=-1;
}
key[0] = 0;
parent[0] = -1;
for (int x = 0; x < V - 1; x++)
{
int u = min_Key(key, visited);
visited[u] = true;
for (int v = 0; v < V; v++)
{
if (cost[u][v]!=0 && visited[v] == false && cost[u][v] < key[v])
{
parent[v] = u;
key[v] = cost[u][v];
}
}
}
print_MST(parent, cost);
}
int main()
{
int cost[V][V];
cout<<"Enter the vertices for a graph with 6 vetices";
for (int i=0;i<V;i++)
{
for(int j=0;j<V;j++)
{
cin>>cost[i][j];
}
}
find_MST(cost);
return 0;
}
OUTPUT:-
PROGRAM-7
Aim:- Write a C++ Program for Sum of Subsets Problems using Back
Tracking
#include <iostream>
using namespace std;
class Subset_Sum
{
public:
void subsetsum_Backtracking(int Set[], int pos, int sum, int tmpsum, int size,
bool &found)
{
if (sum == tmpsum)
found = true;
for (int i = pos; i < size; i++)
{
if (tmpsum + Set[i] <= sum)
{
tmpsum += Set[i];
subsetsum_Backtracking(Set, i + 1, sum, tmpsum, size, found);
tmpsum -= Set[i];
}
}
}
};
int main()
{
int i, n, sum;
Subset_Sum S;
cout << "Enter the number of elements in the set:";
cin >> n;
int a[n];
cout << "Enter the values" << endl;
for (i = 0; i < n; i++)
cin >> a[i];
cout << "Enter the value of sum:" << endl;
cin >> sum;
bool f = false;
S.subsetsum_Backtracking(a, 0, sum, 0, n, f);
if (f)
cout << "Subset with the given sum found";
else
cout << "No required subset found" << endl;
return 0;
}
OUTPUT:-
PROGRAM-8
Aim:- Write a C++ Program to solve Travelling Sales Problem using
the Dynamic Programming
#include<iostream>
using namespace std;
int ary[10][10],completed[10],n,cost=0;
void takeInput() {
int i,j;
cout<<"Enter the number of villages: ";
cin>>n;
cout<<"\nEnter the Cost Matrix\n";
for(i=0;i < n;i++) {
cout<<"\nEnter Elements of Row: "<<i+1<<"\n";
for( j=0;j < n;j++)
cin>>ary[i][j];
completed[i]=0; } cout<<"\
n\nThe cost list is:";
for( i=0;i < n;i++) { cout<<"\
n";
for(j=0;j < n;j++) cout<<"\
t"<<ary[i][j]; } } int
least(int c) {
int i,nc=999;
int min=999,kmin;
for(i=0;i < n;i++) {
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();
cout<<"\n\nThe Path is:\n";
mincost(0);
cout<<"\n\nMinimum cost is "<<cost;
return 0;
}
OUTPUT:-
PROGRAM-9
Aim:- Write a C++ Program to find solution of N Queen Problem
using Back Tracking
#include<iostream>
using namespace std;
int grid[10][10];
void print(int n) {
for (int i = 0;i <= n-1; i++) {
for (int j = 0;j <= n-1; j++) {
cout <<grid[i][j]<< " ";
}
cout<<endl;
}
cout<<endl;
cout<<endl;
}
bool isSafe(int col, int row, int n) {
for (int i = 0; i < row; i++) {
if (grid[i][col]) {
return false;
} }
for (int i = row,j = col;i >= 0 && j >= 0; i--,j--) {
if (grid[i][j]) {
return false;
} }
for (int i = row, j = col; i >= 0 && j < n; j++, i--) {
if (grid[i][j]) {
return false;
} }
return true;
}
bool solve (int n, int row) {
if (n == row) {
print(n);
return true;
}
bool res = false;
for (int i = 0;i <=n-1;i++) {
if (isSafe(i, row, n)) {
grid[row][i] = 1;
res = solve(n, row+1) || res;
grid[row][i] = 0;
}
}
return res;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cout<<"Enter the number of queen:"<<endl;
cin >> n;
for (int i = 0;i < n;i++) {
for (int j = 0;j < n;j++) {
grid[i][j] = 0;
} }
bool res = solve(n, 0);
if(res == false) {
cout << -1 << endl;
} else {
cout << endl;
}
return 0;
}
OUTPUT:-
PROGRAM-10
Aim:- Write a C++ Program to solve the Knapsack Problem using
Branch and Bound
#include <bits/stdc++.h>
using namespace std;
struct Item {
float weight;
int value; };
struct Node {
int level, profit, bound;
float weight; };
bool comparison(Item a, Item b) {
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
return r1 > r2; }
int bound(Node u, int n, int W, Item arr[]) {
if (u.weight >= W) {
return 0; }
int pro_bound = u.profit;
int j = u.level + 1;
int totweight = u.weight;
while ((j < n) && (totweight + arr[j].weight <= W)) {
totweight += arr[j].weight;
pro_bound += arr[j].value;
j++; }
if (j < n) {
pro_bound += (W - totweight) * arr[j].value /
arr[j].weight; }
return pro_bound; }
int main() {
int W;
cout << "Enter weight of Knapsack: ";
cin >> W;
Item arr[] = {{1, 50}, {4.14, 60}, {3.98, 120}, {6, 90}, {4, 80}};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n, comparison);
queue<Node> Q;
Node u, v;
u.level = -1;
u.profit = u.weight = 0;
Q.push(u);
int max_pro = 0;
while (!Q.empty()) {
u = Q.front();
Q.pop();
if (u.level == -1)
v.level = 0;
if (u.level == n - 1)
continue;
v.level = u.level + 1;
v.weight = u.weight + arr[v.level].weight;
v.profit = u.profit + arr[v.level].value;
if (v.weight <= W && v.profit > max_pro)
max_pro = v.profit;
v.bound = bound(v, n, W, arr);
if (v.bound > max_pro)
Q.push(v);
v.weight = u.weight;
v.profit = u.profit;
v.bound = bound(v, n, W, arr);
if (v.bound > max_pro)
Q.push(v);
}
cout << "Maximum possible profit possible = "<< max_pro;
return 0;
}
OUTPUT:-