Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 48

UNIVERSITY INSTITUTE OF ENGINEERING AND TECHNOLOGY,

PANJAB UNIVERSITY, CHANDIGARH

Design and Analysis of Algorithms Practical

SUBMITTED BY: SUBMITTED TO:


VANSHIKA SINGLA M/S Amanpreet
UE218107
IT (3rd year)
PRACTICAL 1

Details of platform , language and operating system.

 Operating system - Windows 11

Window Specifications –
Edition: Windows 11 Home Single Language
Version: 22H2
Os build: 22621.2134

Device Specifications –
Processor : 11th Gen Intel(R) Core(TM) i5-1135G7
System Type : 64-bit operating system, x64-based processor
RAM : 8.00 GB

 Language – C++

C++ is an object oriented programming language that is viewed by many as


the best language for creating large-scale applications. C++ is the superset of
the C language. A related programming language, Java, is based on C++ but
optimized for the distribution of program objects in a network such as the
internet.
Features of C++ :
1. Object-Oriented Programming
2. Machine Independent
3. Simple
4. High-Level Language
5. Compiler Based
6. Dynamic Memory Allocation
7. Memory Management
8. Multi-threading

 Platform – VS Code

Visual Studio Code is a lightweight yet powerful source code editor


developed by Microsoft. It offers a rich set of features, including smart code
completion, built-in Git integration, debugging support, and a vast library of
extensions. Its cross-platform availability makes it a go-to choice for
developers working on various operating systems. With its fast performance
and highly customizable interface, VS Code has garnered a large and active
community of users, making it one of the most popular code editors for a
wide range of programming languages and development tasks.
Features :
1. Lightweight
2. fast
3. Language Support
4. Integrated Development Environment (IDE) Features:
5. Integrated Terminal
PRACTICAL 2

Write a program to sort a given set of elements and determine the time required
to sort the elements. Repeat the exp for different values of n , the number of
elements in list to be sorted and plot a graph of the time v/s n element

1. Random number Generator:


Library used for generating random number:
<cstdlib>, <time.h>
Function invoked:
rand()
2. Time of Execution:
Library used for checking time of execution for each run:
<chrono>
Function invoked:
Chrono::high_resolution_clock::now();
3. Dynamic Array:
Library used for checking time of execution for each run:
<vector>
4. Plotting the outcome:
We used Excel to store the no. of inputs and time taken, and a graph is plot
based on this.

CODE :

BUBBLE SORT
#include<iostream>

#include<algorithm>

#include<time.h>

#include<chrono>

#include<cstdlib>

#include<vector>

using namespace std::chrono;

using namespace std;

int main()

int n;

cout<<"enter n: ";

cin>>n;

vector<int> a;

/*//average case

cout<<"Average Case: "<<endl;

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

a.push_back(rand());

} */

/*//Best case

cout<<"Best Case: "<<endl;

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

a.push_back(i);

}*/

/*//worst case

cout<<"Worst case: "<<endl;

for(int i=n;i>0;i--)

a.push_back(i);

}*/

auto start = std::chrono::high_resolution_clock::now();

for(int i=0;i<n-1;i++)

for(int j=0;j<n-1-i;j++)

if(a[j]>a[j+1])

int temp = a[j+1];

a[j+1] = a[j];

a[j] = temp;

auto end = std::chrono::high_resolution_clock::now();

auto time = end - start;


cout<<"elements sorted "<<endl;

cout<<"time taken= "<<(time/std::chrono::microseconds(1))<<" microseconds"<<endl;

OUTPUT:

n Best Case Average case Worst Case


10 0 0 0
100 0 100 215
500 0 1226 2501
1000 1122 5989 7965
1500 3001 5004 30009
2000 11845 22697 45987
5000 30560 85541 90444
PRACTICAL-3

Program of linear Search and Binary Search.

1. Random number Generator:


Library used for generating random number:
<cstdlib>, <time.h>
Function invoked:
rand()
2. Time of Execution:
Library used for checking time of execution for each run:
<chrono>
Function invoked:
Chrono::high_resolution_clock::now();
3. Dynamic Array:
Library used for checking time of execution for each run:
<vector>
4. Plotting the outcome:
We used Excel to store the no. of inputs and time taken, and a graph is plot
based on this.

CODE:

LINEAR SEARCH:
#include <iostream>
#include<algorithm>
#include<time.h>
#include<chrono>
#include<cstdlib>
#include<vector>
using namespace std;
bool search(vector <int> findElement, int size, int key)
{
for (int i = 0; i < size; i++)
{
if (findElement[i] == key)
{
return 1;
}
}
return 0;
}
int main()
{
auto start = std::chrono::high_resolution_clock::now();
int n;
cout<<"enter n: ";
cin>>n;
vector<int>a;
cout << "Enter the element to search for " << endl;
int key;
cin >> key;
// average case
// cout<<"Average Case: "<<endl;
// for(int i=0;i<n;i++)
// {
// a.push_back(rand());
// }
//Best case
// cout<<"Best Case: "<<endl;
// a.push_back(key);
// for(int i=1;i<n;i++)
// {
// a.push_back(rand());
// }

//worst case
cout<<"Worst case: "<<endl;
for(int i=0;i<n-1;i++)
{
a.push_back(rand());
}
a.push_back(key);
bool found = search( a, 10, key);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start;
std::cout << "Time taken: " << duration.count() << " seconds" << std::endl;
return 0;
}

OUTPUT:
n best case average case worst case

10 0 4.52752 3.72976

100 0 3.76214 4.87456

1000 0 3.61017 4.98547

2000 0 4.44232 6.32581

5000 0 3.39451 8.01875

8000 0 3.59798 8.25471


10000 0 4.63672 9.25471
BINARY SEARCH:

#include <iostream>
#include<algorithm>
#include<time.h>
#include<chrono>
#include<cstdlib>
#include<vector>
using namespace std;
int binSearch(vector<int>array, int size, int key)
{
int start = 0;
int end = size - 1;
int mid = start + (end - start) / 2;
while (start <= end)
{
if (array[mid] == key)
{
return mid;
}
if (key > array[mid])
{
start = mid + 1;
}
else
{
end = mid - 1;
}
mid = start + (end - start) / 2;
}
return -1;
}
int main()
{
auto start = std::chrono::high_resolution_clock::now();
int n;
cout<<"enter n: ";
cin>>n;
int key;
cout << "Enter the key you want to search" << endl;
cin >> key;

vector <int> a;
// cout<<"Average Case: "<<endl;
// for(int i=0;i<n;i++)
// {
// a.push_back(rand());
// }
//Best case
// cout<<"Best Case: "<<endl;
// a.push_back(key);
// for(int i=1;i<n;i++)
// {
// a.push_back(rand());
// }

//worst case
cout<<"Worst case: "<<endl;
for(int i=0;i<n-1;i++)
{
a.push_back(rand());
}
a.push_back(key);
int evenIndex = binSearch(a, 10, key);
cout << "index of " << key << " is " << evenIndex << endl;
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start;
// Print the time taken
std::cout << "Time taken: " << duration.count() << " seconds" << std::endl;
return 0;
}

OUTPUT:
n Best Case Average Case Worst Case

10 3.21542 5.42178 6.80771

100 3.58471 6.32561 8.56214

1000 3.65871 6.45872 15.54871

2000 4.08547 11.21459 18.52364

5000 3.96543 16.32514 23.14527

10000 8.25417 28.25614 41.25874


PRACTICAL-4

Program of Merge Sort, Heap Sort, Selection Sort, Radix Sort.

1. Random number Generator:


Library used for generating random number:
<cstdlib>, <time.h>
Function invoked:
rand()
2. Time of Execution:
Library used for checking time of execution for each run:
<chrono>
Function invoked:
Chrono::high_resolution_clock::now();
3. Dynamic Array:
Library used for checking time of execution for each run:
<vector>
4. Plotting the outcome:
We used Excel to store the no. of inputs and time taken, and a graph is plot
based on this.

CODE:

MERGE SORT:

#include <iostream>
#include<algorithm>
#include<time.h>
#include<chrono>
#include<cstdlib>
#include<vector>
using namespace std;
void merge(vector<int>arr, int s, int e)
{
int mid = (s + e) / 2;
int len1 = mid - s + 1;
int len2 = e - mid;
int *first = new int[len1];
int *second = new int[len2];
// copy values
int mainArrayIndex = s;
for (int i = 0; i < len1; i++)
{
first[i] = arr[mainArrayIndex++];
}
mainArrayIndex = mid + 1;
for (int i = 0; i < len2; i++)
{
second[i] = arr[mainArrayIndex++];
}
// merge 2 sorted arrays
int index1 = 0;
int index2 = 0;
mainArrayIndex = s;
while (index1 < len1 && index2 < len2)
{
if (first[index1] < second[index2])
{
arr[mainArrayIndex++] = first[index1++];
}
else
{
arr[mainArrayIndex++] = second[index2++];
}
}
while (index1 < len1)
{
arr[mainArrayIndex++] = first[index1++];
}
while (index2 < len2)
{
arr[mainArrayIndex++] = second[index2++];
}
delete[] first;
delete[] second;
}
void mergeSort(vector<int>arr, int s, int e)
{
// base case
if (s >= e)
{
return;
}
int mid = (s + e) / 2;
// left part sorting
mergeSort(arr, s, mid);
// right part sorting
mergeSort(arr, mid + 1, e);
// merge
merge(arr, s, e);
}

int main()
{
auto start = std::chrono::high_resolution_clock::now();
int n;
cout << "Enter the size of the array " << endl;
cin >> n;
vector <int>a;
cout << "Array before sorting is " << endl;
//average case
// cout<<"Average Case: "<<endl;
// for(int i=0;i<n;i++)
// {
// a.push_back(rand());
// }
//Best case
// cout<<"Best Case: "<<endl;
// for(int i=0;i<n;i++)
// {
// a.push_back(i);
// }
//worst case
cout<<"Worst case: "<<endl;
for(int i=n;i>0;i--)
{
a.push_back(i);
}
mergeSort(a, 0, n - 1);
cout << "Sorted array using merge sort is " << endl;
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start;
std::cout << "Time taken: " << duration.count() << " seconds" << std::endl;
return 0;
}

OUTPUT:

n Best Case Average Case Worst Case

10 1.02547 5.26478 1.18881

100 1.12547 5.32641 5.64527

1000 2.56981 6.54182 3.81414

2000 2.65743 6.98745 7.52146

5000 2.48576 10.52478 15.63241

10000 4.65286 15.63248 29.63254


HEAP SORT:

#include <iostream>
#include<algorithm>
#include<time.h>
#include<chrono>
#include<cstdlib>
#include<vector>
using namespace std;
void heapify(vector<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);
}
}
void heapSort(vector<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);
}
}
int main()
{
auto start = std::chrono::high_resolution_clock::now();
int n;
cout<<"enter n:";
cin>>n;
vector <int> arr;
// cout<<"Average Case: "<<endl;
// for(int i=0;i<n;i++)
// {
// arr.push_back(rand());
// }
//Best case
// cout<<"Best Case: "<<endl;
// for(int i=0;i<n;i++)
// {
// arr.push_back(i);
// }
//worst case
cout<<"Worst case: "<<endl;
for(int i=n;i>0;i--)
{
arr.push_back(i);
}
heapSort(arr, n);
cout<<”Sorted array using heap sort is”<<endl;
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration <double> duration = end - start;
std::cout << "Time taken: " << duration.count() << " seconds" << std::endl;
return 0;
}

OUTPUT:
n Best Case Average Case Worst case

10 1.02542 1.5687 1.9928

100 1.6584 2.5646 2.9847

1000 3.2547 3.7418 4.9666

5000 4.2564 5.6247 6.3258

10000 6.2154 11.2563 12.5698

SELECTION SORT:

#include <iostream>
#include<algorithm>
#include<time.h>
#include<chrono>
#include<cstdlib>
#include<vector>
using namespace std;
void selectionSort(vector<int>array, int size)
{
for (int i = 0; i < size; i++)
{
int min = i;
for (int j = i + 1; j < size; j++)
{
if (array[j] < array[min])
{
min = j;
}
}
swap(array[min], array[i]);
}
}

int main()
{
auto start = std::chrono::high_resolution_clock::now();
int n;
cout << "Enter the size of the array " << endl;
cin >> n;
vector <int> a;
cout << "Array before sorting is " << endl;
// Average Case
// cout<<"Average Case: "<<endl;
// for(int i=0;i<n;i++)
// {
// a.push_back(rand());
// }
//Best case
// cout<<"Best Case: "<<endl;
// for(int i=0;i<n;i++)
// {
// a.push_back(i);
// }
//worst case
cout<<"Worst case: "<<endl;
for(int i=n;i>0;i--)
{
a.push_back(i);
}
selectionSort(a, n);
cout << "Sorted array using selection sort is " << endl;

auto end = std::chrono::high_resolution_clock::now();


std::chrono::duration<double> duration = end - start;
std::cout << "Time taken: " << duration.count() << " seconds" << std::endl;
}

OUTPUT:
n Best Case Average Case Worst Case

10 1.02547 1.05248 1.06487

100 2.01547 2.35418 2.96587

1000 3.14587 4.65244 4.95303

5000 4.56328 5.23476 6.32547

10000 4.99996 9.92649 10.25483

RADIX SORT:

#include<iostream>
#include<algorithm>
#include<time.h>
#include<chrono>
#include<cstdlib>
#include<vector>
#include<list>
#include<cmath>
using namespace std;

void radixSort(vector<int>arr, int n, int max) {


int i, j, m, p = 1, index, temp, count = 0;
list<int> pocket;
for(i = 0; i< max; i++) {
m = pow(10, i+1);
p = pow(10, i);
for(j = 0; j<n; j++) {
temp = arr[j]%m;
index = temp/p;
pocket.push_back(arr[j]);
}
count = 0;
for(j = 0; j<10; j++) {

while(!pocket.empty()) {
arr[count] = *(pocket.begin());
pocket.erase(pocket.begin());
count++;
}
}
}
}
int main() {
int n, max;
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter the maximum digit of elements: ";
cin >> max;
vector<int>arr;
auto start = std::chrono::high_resolution_clock::now();
//cout<<"Average Case: "<<endl;
// for(int i=0;i<n;i++)
// {
// arr.push_back(rand());
// }
//Best case
// cout<<"Best Case: "<<endl;
// for(int i=0;i<n;i++)
// {
// arr.push_back(i);
// }
//worst case
cout<<"Worst case: "<<endl;
for(int i=n;i>0;i--)
{
arr.push_back(i);
}
//
cout << "Data before Sorting: "<<endl;
radixSort(arr, n, max);
cout << "Data after Sorting: "<<endl;
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start;
std::cout << "Time taken: " << duration.count() << " seconds" << std::endl;
}

OUTPUT:

n Best Case Average Case Worst Case

10 0 1.0254 0

100 2.3541 3.2548 3.9658

1000 3.6587 3.9999 4.1252

5000 4.0215 4.9969 5.6324

10000 4.8759 7.2569 9.6587


PRACTICAL-5

a)
AIM: Program to find optimal solution for Fractional Knapsack Problem.

Knapsack Problem:
Knapsack is like a container or a bag. If we have given some items with weight and profit
then we have to put items in knapsack in such a way that total value produces maximum
profit.
In fractional Knapsack problem we can divide the problem. Fractional knapsack problem can
be solved by greedy approach. The basic idea is calculating profit/weight ratio of each item
and then sort it according to that. Take item having highest ratio and add it as much as can.

For example:
Consider arr[] = {{100,20},{60,10},{120,30}} and W=50
First of all calculate profit/weight ratio of each item.
100/20 = 5
60/10 = 6
120/30 = 4
Now sort them: {{60,10},{100,20},{120,30}}
Iteration:
For i=0 weight=10 <50 so add it in the knapsack. W becomes 40
For i=1 weight=20<40 so add it in the knapsack. W becomes 20
For i=2 weight=30>20 fraction of 30 will be added that is 20/30 = 2/3 fraction of item in the
knapsack.
Calculating profit: 60 + 100+ 2/3*120 = 240 which is the maximum profit.

Algorithm:
Begin
Take an array of structure item
Declare profit, weight, knapsack weight and density
Calculate density = profit/weight for each item
Sort the items of array in decreasing order
Add weight of items of array in knapsack until it is full (Total value <=W)
End

CODE:
#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;
float totalValue = 0, totalWeight = 0;
for (i = 0; i < sizeOfItems; i++) {
items[i].d = (float)items[i].v / items[i].w; //typecasting done (v is int and w is also int so
we get final value of d as int)
}
sort(items, items+sizeOfItems, compare);
cout << "values : ";
for(i = 0; i < sizeOfItems; i++) {
cout << items[i].v << "\t";
}
cout << endl << "weights: ";
for (i = 0; i < sizeOfItems; i++) {
cout << items[i].w << "\t";
}
cout << endl << "ratio : ";
for (i = 0; i < sizeOfItems; i++) {
cout << items[i].d << "\t";
}
cout << endl;

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,n;
cout<<"enter n: ";
cin>>n;
Item items[n];
input(items, n);
cout << "Entered data \n";
display(items,n);
cout<< "Enter Knapsack weight \n";
cin >> W;
float mxVal = knapsack(items, n, W);
cout << "Max value for "<< W <<" weight is "<< mxVal;
}

OUTPUT:
b)
AIM: Program to find Minimum Cost Spanning tree using prims algorithm.

Prim’s algorithm is the minimum spanning tree algorithm that takes graph as input and find
subset of edges of that graph which forms tree and includes every vertex, has the minimum
sum of weights among all the trees formed from graph.

Algorithm:
Select a starting vertex
Repeat steps 3 and 4 until there are fringe vertices
Select an edge ‘e’ connecting the tree vertex and fringe vertex that has minimum weight.
Add the selected edge and the vertex to the minimum spanning tree T
Exit

CODE:
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int spanningTree(int V, vector<vector<int>> adj[])
{
priority_queue<pair<int, int>,
vector<pair<int, int> >, greater<pair<int, int>>> pq;
vector<int> vis(V, 0);
pq.push({0, 0});
int sum = 0;
while (!pq.empty()) {
auto it = pq.top();
pq.pop();
int node = it.second;
int wt = it.first;
if (vis[node] == 1) continue;
vis[node] = 1;
sum += wt;
for (auto it : adj[node]) {
int adjNode = it[0];
int edW = it[1];
if (!vis[adjNode]) {
pq.push({edW, adjNode});
}}}
return sum;
} };
int main() {
int V = 5;
vector<vector<int>> edges = {{0, 1, 2}, {0, 2, 1}, {1, 2, 1}, {2, 3, 2}, {3, 4, 1}, {4, 2, 2}};
vector<vector<int>> adj[V];
for (auto it : edges) {
vector<int> tmp(2);
tmp[0] = it[1];
tmp[1] = it[2];
adj[it[0]].push_back(tmp);
tmp[0] = it[0];
tmp[1] = it[2];
adj[it[1]].push_back(tmp);
}
Solution obj;
int sum = obj.spanningTree(V, adj);
cout << "The sum of all the edge weights: " << sum << endl;
return 0;
}

OUTPUT:
PRACTICAL-6
a)
AIM: Program to find minimum cost Spanning tree using Kruskal Algorithm.
In Kruskal’s algorithm sort all edges of given graph in increasing order. Then keeps on adding
new edges and nodes in minimum spanning tree if newly added doesn’t form cycle. It picks
the minimum weighted edge at first and the maximum weighted edge at last.

STEPS:
Sort all the edges in non-decreasing order of their weight.
Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If the
cycle is not formed, include this edge. Else, discard it.
Repeat step#2 until there are (V-1) edges in the spanning tree.

CODE:
#include<iostream>
#include<algorithm>
using namespace std;
class Edge{
public:
int source;
int dest;
int weight;
};
bool comp(Edge e1,Edge e2){
return e1.weight<e2.weight;
}
int findparent(int v,int parent[]){
if(parent[v]==v){
return v;
}
findparent(parent[v],parent);
}
void kruskals(Edge input[],int n,int E){
sort(input,input+E,comp);
Edge output[n-1];
int parent[n];
for(int i=0;i<n;i++){
parent[i]=i;
}
int count=0;
int i=0;
while(count!=n-1){
Edge currentedge=input[i];
int sourceparent=findparent(currentedge.source,parent);
int destparent=findparent(currentedge.dest,parent);
if(sourceparent!=destparent){
output[count]=currentedge;
count++;
parent[sourceparent]=destparent;
}
i++;}
cout<<"Result is:"<<endl;
for(int i=0;i<n-1;i++){
if(output[i].source<output[i].dest){
cout<<output[i].source<<" "<<output[i].dest<<" "<<output[i].weight<<endl;
}
else{
cout<<output[i].dest<<" "<<output[i].source<<" "<<output[i].weight<<endl;
}}}
int main(){
int n,E;
cout<<"Enter number of vertices and edges:";
cin>>n>>E;
Edge input[E];
for(int i=0;i<E;i++){
cout<<"Enter "<<i+1<<" connection:";
cin>>input[i].source>>input[i].dest>>input[i].weight;
}
kruskals(input,n,E);
return 0;
}

OUTPUT:
b)
AIM: Program to implement Djikstra Algorithm
The idea is to generate a SPT (shortest path tree) with a given source as a root. Maintain
an Adjacency Matrix with two sets,
 one set contains vertices included in the shortest-path tree,
 other set includes vertices not yet included in the shortest-path tree.
At every step of the algorithm, find a vertex that is in the other set (set not yet included)
and has a minimum distance from the source.

CODE:
#include <iostream>
#include<limits.h>
using namespace std;
#define V 9
int minDistance(int dist[],bool sptset[]){
int min=INT_MAX,min_index;
for(int v=0;v<V;v++){
if(sptset[v]==false && dist[v]<=min){
min=dist[v],min_index=v;
}
}
return min_index;
}
void printSolution(int dist[]){
cout<<"Vertex Distance from source"<<endl;
for(int i=0;i<V;i++){
cout<<i<<" "<<dist[i]<<endl;
}}
void dijkstra(int graph[V][V],int src){
int dist[V];
bool sptset[V];
for(int i=0;i<V;i++){
dist[i]=INT_MAX,sptset[i]=false;
}
dist[src]=0;
for(int count=0;count<V-1;count++){
int u=minDistance(dist,sptset);
sptset[u]=true;
for(int v=0;v<V;v++){
if(!sptset[v] && graph[u][v] && dist[u]!=INT_MAX && dist[u]+graph[u][v]<dist[v])
dist[v]=dist[u]+graph[u][v];
}
}
printSolution(dist);
}
int main() {
int graph[V][V]= {{0,4,0,0,0,0,8,0},{4,0,8,0,0,0,0,11,0},{0,8,0,7,0,4,0,0,2},{0,0,7,0,9,14,0,0,0},
{0,0,0,9,0,10,0,0,0},{0,0,4,14,10,0,2,0,0},{0,0,0,0,0,2,0,1,6},{8,11,0,0,0,0,1,0,7},
{0,0,2,0,0,0,6,7,0}
};
dijkstra(graph,0);
return 0;
}

OUTPUT:
PRACTICAL-7
a)
AIM: Write a program to implement 0/1 Knapsack Problem.

CODE:
#include <iostream>
using namespace std;
int max(int x, int y) {
return (x > y) ? x : y;
}
int knapSack(int W, int w[], int v[], int n) {
int i, wt;
int K[n + 1][W + 1];
for (i = 0; i <= n; i++) {
for (wt = 0; wt <= W; wt++) {
if (i == 0 || wt == 0)
K[i][wt] = 0;
else if (w[i - 1] <= wt)
K[i][wt] = max(v[i - 1] + K[i - 1][wt - w[i - 1]], K[i - 1][wt]);
else
K[i][wt] = K[i - 1][wt];
}
}
return K[n][W];
}
int main() {
cout << "Enter the number of items in a Knapsack:";
int n, W;
cin >> n;
int v[n], w[n];
for (int i = 0; i < n; i++) {
cout << "Enter value and weight for item " << i << ":";
cin >> v[i];
cin >> w[i];
}
cout << "Enter the capacity of knapsack: ";
cin >> W;
cout << knapSack(W, w, v, n);
return 0;
}
OUTPUT:

b)
AIM: Write a program to solve All pairs shortest path problem using Floyd-Warshall
Algorithm.
CODE:
#include <iostream>
#include <cstdlib>
#define max 10
#define infi 999
using namespace std;
int p[max][max];
void allpairshort(int a[max][max], int n)
{
int k, i, j;
for (k = 0; k < n; k++)
{
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (a[i][k] + a[k][j] < a[i][j])
{
a[i][j] = a[i][k] + a[k][j];
p[i][j] = k;
}
}
}
}
}

void shortest(int i, int j)


{
int k = p[i][j];
if (k > 0)
{
shortest(i, k);
cout<<" "<<k<<" ";
shortest(k, j);
}
}

void findpath(int a[max][max], int i, int j, int n)


{
cout<<"Path from " << i <<" to "<< j << ":";
if (a[i][j] < infi)
{
cout<<" "<<i<<" ";
shortest(i, j);
cout<<" "<<j<<" ";
}
}
int main()
{
int i, j;
int a[][10] = {{0, 10, infi, 30, 100},
{infi, 0 , 50, infi, infi},
{infi, infi , 0, infi, 10},
{infi, infi , 20, 0, 60},
{infi, infi , infi, infi, 0},
};

allpairshort(a, 5);
findpath(a, 0, 4, 5);
return 0;
}

OUTPUT:
PRACTICAL-8
a)
AIM: Write a program to solve 8-queen problem using backtracking approach
CODE:
#include <bits/stdc++.h>
using namespace std;
int countt=0;
void print(int board[][4]){
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
cout<<board[i][j]<<" ";
}
cout<<endl;
}
cout<<"-----------------\n";
}
bool isValid(int board[][4],int row,int col){

for(int i=col;i>=0;i--){
if(board[row][i])
return false;
}
int i=row,j=col;
while(i>=0&&j>=0){
if(board[i][j])
return false;
i--;
j--;
}
i=row;
j=col;

while(i<4&&j>=0){
if(board[i][j])
return false;
i++;
j--;
}
return true;
}

void ninjaQueens(int board[][4],int currentColumn){


if(currentColumn>=4)
return;

for(int i=0;i<4;i++){
if(isValid(board,i,currentColumn)){
board[i][currentColumn]=1;
if(currentColumn==3){
print(board);
countt++;
}

ninjaQueens(board,currentColumn+1);

board[i][currentColumn]=0;
}

}
}
int main() {

int board[4][4]={{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0}};
ninjaQueens(board,0);

cout<<countt<<endl;
return 0;
}

OUTPUT:

b)
AIM: Write a program to solve Sum of Subsets problem using backtracking approach.
CODE:
#include <iostream>
#include <vector>
using namespace std;
bool isSubsetSum(vector<int>& set, int n, int targetSum, vector<int>& subset) {
if (targetSum == 0) {
for (int i = 0; i < subset.size(); i++) {
cout << subset[i] << " ";
}
cout << endl;
return true;
}
if (n == 0 || targetSum < 0) {
return false;
}
if (isSubsetSum(set, n - 1, targetSum, subset)) {
return true;
}
subset.push_back(set[n - 1]);
if (isSubsetSum(set, n - 1, targetSum - set[n - 1], subset)) {
return true;
}
subset.pop_back();

return false;
}

int main() {
vector<int> set = {3, 34, 4, 12, 5, 2};
int targetSum;
cout<<"Enter the targetSum: ";
cin>>targetSum;

vector<int> subset;

if (isSubsetSum(set, set.size(), targetSum, subset)) {


cout << "Subset with the given sum exists." << endl;
} else {
cout << "No subset with the given sum exists." << endl;
}

return 0;
}

OUTPUT:

You might also like