Professional Documents
Culture Documents
DAA Practical
DAA Practical
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++
Platform – VS Code
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
CODE :
BUBBLE SORT
#include<iostream>
#include<algorithm>
#include<time.h>
#include<chrono>
#include<cstdlib>
#include<vector>
int main()
int n;
cout<<"enter n: ";
cin>>n;
vector<int> a;
/*//average case
for(int i=0;i<n;i++)
a.push_back(rand());
} */
/*//Best case
for(int i=0;i<n;i++)
{
a.push_back(i);
}*/
/*//worst case
for(int i=n;i>0;i--)
a.push_back(i);
}*/
for(int i=0;i<n-1;i++)
for(int j=0;j<n-1-i;j++)
if(a[j]>a[j+1])
a[j+1] = a[j];
a[j] = temp;
OUTPUT:
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
#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
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:
#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 (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
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;
OUTPUT:
n Best Case Average Case Worst Case
RADIX SORT:
#include<iostream>
#include<algorithm>
#include<time.h>
#include<chrono>
#include<cstdlib>
#include<vector>
#include<list>
#include<cmath>
using namespace std;
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:
10 0 1.0254 0
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;
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;
}
}
}
}
}
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;
}
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;
return 0;
}
OUTPUT: