0% found this document useful (0 votes)
55 views23 pages

Ada File Tina

The document describes an experiment to implement the knapsack problem using the greedy approach. The program sorts items by density and selects items in descending order of density until the knapsack is full. It stores 6 items with ID, weight, value and calculates density as value/weight. The items are sorted by density and the fractional knapsack function selects items until total weight exceeds the knapsack capacity, outputting details of each selected item.

Uploaded by

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

Ada File Tina

The document describes an experiment to implement the knapsack problem using the greedy approach. The program sorts items by density and selects items in descending order of density until the knapsack is full. It stores 6 items with ID, weight, value and calculates density as value/weight. The items are sorted by density and the fractional knapsack function selects items until total weight exceeds the knapsack capacity, outputting details of each selected item.

Uploaded by

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

Analysis and Design of Algorithm

(LAB FILE)

BACHELOR OF TECHNOLOGY
(Computer Science and Engineering)

SEMESTER-VI

(2016-2020)
Department of Computer Science & Engineering

AMITY SCHOOL OF ENGINEERING AND TECHNOLOGY


AMITY UNIVERSITY UTTAR PRADESH
NOIDA, (U.P.), INDIA

SUBMITTED TO- SUBMITTED BY-

Ms. Shanu Sharma Tina M1ttal

A2305216452

6CSE – 7X
LIST OF PROGRAMS
Sr. Date of Date of Page Max. Sign. of
No. Name of Program Allotment Submission No. Marks Faculty

Implement Recursive Binary search and


determine the time taken to search an
element. Repeat the experiment for different
values of n, the number of elements in the list
to be searched and plot a graph of the time
1. taken versus n.

Sort a given set of elements using Quick sort


method and determine the time taken to sort
the elements. Repeat the experiment for
different values of n, the number of
elements in the list to be sorted and plot a
2. graph of the time taken versus n.

Implement knapsack problem using greedy


3. approach.

Implement 0/1 Knapsack Problem using


4. Dynamic Programming method.

From a given starting node in a digraph, print


all the nodes reachable by using BFS/DFS
5. method.

Find Minimum Cost Spanning Tree of a


given undirected graph using
6. Prim’s/Kruskal’s algorithm.

From a given vertex in a weighted connected


graph, find shortest paths to other vertices
7. using Dijkstra's algorithm.

Consider the problem of N queen on an


(NxN) chessboard. Two queens are said to
attack each other if they are on the same row,
column, or diagonal. Implements
backtracking algorithm to solve the problem
i.e. place N non-attacking queens on the
8. board.

1|Page
Tina Mittal(A2305216452)
Implement Knapsack Problem based on
9. Backtracking algorithm.

Implement Traveling Salesman problem


10. based on Branch and Bound technique.
11. Open- Given two sequences, a subsequence
Ended is a sequence that appears in the same
Experi relative order, but not necessarily
-ment contiguous. For example,“abc”,
“abg”, “bdf”, “aeg”, „”acefg”, .. etc
are subsequences of “abcdefg”. So a
string of length n has 2^n different
possible subsequences. It is a classic
computer science problem, the basis
of file comparison programs and has
applications in bioinformatics.
Develop a program to implement the
solution of Longest Common Sub-
sequence problem.

2|Page
Tina Mittal(A2305216452)
EXPERIMENT-1

DATE:

AIM: Implement Recursive Binary search and determine the time taken to search an element.
Repeat the experiment for different values of n, the number of elements in the list to be searched
and plot a graph of the time taken versus n.

Program:
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <timer.h>
const int max = 200;
int rbsearch(int[], int, int, int);
Timer tim;
int main()
{
clrscr();
randomize();
tim.reset();
int arr[max];
arr[0]=random(100);
int i,j;
int loc,num;
cout<<"Array is:\n";
for (i=0; i<max; ++i)
{
arr[i+1]=random(100)+arr[i];
cout<<i+1<<": "<<arr[i]<<"\n";
}
cout<<"Enter element to search: ";
cin>>num;
tim.start();
loc=rbsearch(arr, 0, max-1, num);
if (loc!=-1)
cout<<"\tElement '"<<num<<"' found at position: "<<loc+1;
else
cout<<"\tElement not found";
tim.stop();

3|Page
Tina Mittal(A2305216452)
cout<<"\nThe time was: "<<tim.time();
getch();
tim.reset();
return 0;
}
int rbsearch(int arr[], int left, int right, int num)
{
if (right >= left)
{
int mid = left + (right - left)/2;
if (arr[mid] > num)
return rbsearch(arr, left, mid-1, num);
else if (arr[mid] == num)
return mid;
else
return rbsearch(arr, mid+1, right, num);
}
return -1;
}

n = [100,200,300,400,500,600,700,800,900]
t = [143,149,151,151,150,150,152,156,155]
import matplotlib.pyplot as plt
plt.plot(n,t)
plt.xlabel(‘No. of elements’)
plt.ylabel(‘time taken in usec’)
plt.show()

OUTPUT:

4|Page
Tina Mittal(A2305216452)
EXPERIMENT-2

DATE:

AIM: Sort a given set of elements using Quick sort method and determine the time taken to sort
the elements. Repeat the experiment for different values of n, the number of elements in the list
to be sorted and plot a graph of the time taken versus n.

Program:
#include<iostream.h>
#include<conio.h>
#include<timer.h>
#include<stdlib.h>
const long n=100;
Timer tim;
long partition (long[], long, long);
void quickSort(long[], long, long);
long main()
{
clrscr();
randomize();
tim.reset();
long arr[n];
long i;
for (i=0; i<n; ++i)
arr[i]=random(1000);
for (i=0; i<n; ++i)
cout<<arr[i]<<" ";
tim.start();
quickSort(arr, 0, n-1);
tim.stop();
cout<<"\n\nSorted array:\n";
for (i=0; i<n; ++i)
cout<<arr[i]<<" ";
cout<<"\n\nThe time was: "<<tim.time();
getch();
tim.reset();
return 0;
}
long partition (long arr[], long low, long high)

5|Page
Tina Mittal(A2305216452)
{
long pivot=arr[high];
long i=(low-1);
long t;
for (long j=low; j<high; j++)
{
if (arr[j] <= pivot)
{
i++;
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
t=arr[i+1];
arr[i+1]=arr[high];
arr[high]=t;
return (i+1);
}
void quickSort(long arr[], long low, long high)
{
if (low<high)
{
long pi=partition(arr, low, high);
quickSort(arr, low, pi-1);
quickSort(arr, pi+1, high);
}
}
import matplotlib.pyplot as plt
import numpy as np
def avg(x):
return sum(x)/len(x)
x_100 =[0.00035,0.000257,0.000331,0.000351,0.000264]
x_200 =[0.000705,0.000668,0.000626,0.00084,0.00065]
x_300 =[0.0013,0.000955,0.000958,0.001077,0.001029]
x_400 =[0.001383,0.001364,0.001434,0.001732,0.00145]
x_500 =[0.002115,0.002021,0.002144,0.002192,0.001659]
x_600 =[0.002251,0.002772,0.002182,0.002161,0.002754]
x_700 =[0.002327,0.003181,0.00345,0.003053,0.002657]
x_800 =[0.002919,0.00316,0.00263,0.003158,0.002839]
x_900 =[0.005521,0.004759,0.00452,0.003654,0.004441]

6|Page
Tina Mittal(A2305216452)
x_1000 =[0.005603,0.003887,0.005455,0.004944,0.004139]
y=[x_100,x_200,x_300,x_400,x_500,x_600,x_700,x_800,x_900,x_1000]
x=[]
for i in range(len(y)):
x.append(avg(y[i]))
y= np.arange(100,1001,100)
plt.plot(y,x, 'o--')
plt.xlabel("No. of Elements")
plt.ylabel("time(seconds)")
plt.show()

OUTPUT:

7|Page
Tina Mittal(A2305216452)
EXPERIMENT-3

DATE:

AIM: Implement Knapsack Problem using Greedy Approach.

Program:

#include <iostream.h>
#include <conio.h>
struct Item {
char id[5];
int weight;
int value;
float density;
};
const int max = 6;
void fractionalKnapsack(Item items[], int n, int W);
int main()
{
clrscr();
int i, j;
Item items[max] =
{
{"i1", 6, 6, 0},
{"i2", 10, 2, 0},
{"i3", 3, 1, 0},
{"i4", 5, 8, 0},
{"i5", 1, 3, 0},
{"i6", 3, 5, 0}
};
Item temp;
int n = max;
int W = 8;
for(i = 0; i < n; i++)
{items[i].density = float(items[i].value) / items[i].weight;}
for(i = 1; i < n; i++)
{
for(j = 0; j < n - i; j++)
{
if(items[j+1].density > items[j].density)

8|Page
Tina Mittal(A2305216452)
{
temp = items[j+1];
items[j+1] = items[j];
items[j] = temp;
}
}
}
fractionalKnapsack(items, n, W);
getch();
return 0;
}
void fractionalKnapsack(Item items[], int n, int W)
{
int i, wt;
float value;
float totalWeight = 0, totalBenefit = 0;
for(i = 0; i < n; i++)
{
if(items[i].weight + totalWeight <= W)
{
totalWeight += items[i].weight;
totalBenefit += items[i].value;
cout<<"\nSelected Item: "<<items[i].id<<
"\nWeight: "<<items[i].weight<<
"\nValue: "<<items[i].value<<
"\nTotal Weight: "<<totalWeight<<
"\nTotal Benefit: "<<totalBenefit<<endl;

}
else
{
wt = (W - totalWeight);
value = wt * (float(items[i].value) / items[i].weight);
totalWeight += wt;
totalBenefit += value;
cout<<"\nSelected Item: "<<items[i].id<<
"\nWeight: "<<items[i].weight<<
"\nValue: "<<items[i].value<<
"\nTotal Weight: "<<totalWeight<<
"\nTotal Benefit: "<<totalBenefit<<endl;
break;

9|Page
Tina Mittal(A2305216452)
}
}
cout<<endl;
cout<<"Total Weight: "<<totalWeight<<endl;
cout<<"Total Benefit: "<<totalBenefit<<endl;
}

OUTPUT:

10 | P a g e
Tina Mittal(A2305216452)
EXPERIMENT-4

DATE:

AIM: Implement 0/1 Knapsack Problem using Dynamic Programming method.

Program:

11 | P a g e
Tina Mittal(A2305216452)
EXPERIMENT-5

DATE:

AIM: From a given starting node in a digraph, print all the nodes reachable by using BFS/DFS
method.

Program:

#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],r=-1,f=0,i,j,n;
void bfs(int v);
int main(){
int v;
printf(“\nEnter no. of vertices:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
printf(“\nEnter Adjacency Matrix of the graph:”);
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
printf(“nEnter a[%d][%d]:”,i,j);
scanf(“%d”,&a[i][j]);
}
}
printf(“\nEnter the node of ur Choice:”);
scanf(“%d”,&v);
bfs(v);
printf(“\nAll the nodes reachable from node->%d is/are : nn”,v);
for(i=1;i<=n;i++){
if(visited[i])
printf(“%dt”,i);
}
getch();
return(0);
}
void bfs(int v){
for(i=1;i<=n;i++)
if(a[v][i] && !visited[i])
12 | P a g e
Tina Mittal(A2305216452)
q[++r]=i;
if(f<=r){
visited[q[f]]=1;
bfs(q[f++]);
}

OUTPUT:

13 | P a g e
Tina Mittal(A2305216452)
EXPERIMENT-6a

DATE:

AIM: Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.

Program:

EXPERIMENT-6b

DATE:

AIM: Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm.

Program:

EXPERIMENT-7

DATE:

AIM: From a given vertex in a weighted connected graph, find shortest paths to other vertices
using Dijkstra's algorithm.

Program:

14 | P a g e
Tina Mittal(A2305216452)
EXPERIMENT-8

DATE:

AIM: Consider the problem of N queen on an (NxN) chessboard. Two queens are said to attack
each other if they are on the same row, column, or diagonal. Implements backtracking algorithm
to solve the problem i.e. place N non-attacking queens on the board.

Program:

EXPERIMENT-9

DATE:

AIM: Implement Knapsack Problem based on Backtracking algorithm.

Program:

#include <stdio.h>
#include <conio.h>
#define max 10
int w[max],i,j,p[max];
int n,m;
float unit[max];
int y[max],x[max],fp=-1,fw;
void get()
{
printf("\n Enter total number of items: ");
scanf("%d",&n);
printf("\n Enter the Maximum capacity of the Sack: ");
scanf("%d",&m);
for(i=0;i<n;i++)
{
printf("\n Enter the weight of the item %d : ",i+1);
scanf("%d",&w[i]);
printf("\n Enter the profit of the item %d : ", i+1);
scanf("%d", &p[i]);
}
}
void show()
{
float s=0.0;
printf("\n\tItem\tWeight\tCost\tUnit Profit\tSelected ");
for(i=0;i<n;i++)

15 | P a g e
Tina Mittal(A2305216452)
printf("\n\t%d\t\t%d\t\t%d\t\t%f\t%d",i+1,w[i],p[i],unit[i],x[i]);
printf("\n\n The Sack now holds following items : ");
for(i=0;i<n;i++)
if(x[i]==1)
{
printf("%d\t",i+1);
s += (float) p[i] * (float) x[i];
}
printf("\n Maximum Profit: %f ",s);
}
void sort()
{
int t,t1;
float t2;
for(i=0;i<n;i++)
unit[i] = (float) p[i] / (float) w[i];
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(unit[i] < unit[j])
{
t2 = unit[i];
unit[i] = unit[j];
unit[j] = t2;
t = p[i];
p[i] = p[j];
p[j] = t;
t1 = w[i];
w[i] = w[j];
w[j] =t1;
}
}
}
}
float bound(float cp,float cw,int k)
{
float b = cp;
float c = cw;
for(i=k;i<=n;i++)
{

16 | P a g e
Tina Mittal(A2305216452)
c = c+w[i];
if( c < m)
b = b +p[i];
else
return (b+(1-(c-m)/ (float)w[i])*p[i]);
}
return b;
}
void knapsack(int k,float cp,float cw)
{
if(cw+w[k] <= m)
{
y[k] = 1;
if(k <= n)
knapsack(k+1,cp+p[k],cw+w[k]);
if(((cp+p[k]) > fp) && ( k == n))
{
fp = cp+p[k];
fw = cw+w[k];
for(j=0;j<=k;j++)
x[j] = y[j];
}
}
if(bound(cp,cw,k) >= fp)
{
y[k] = 0;
if( k <= n)
knapsack(k+1,cp,cw);
if((cp > fp) && (k == n))
{
fp = cp;
fw = cw;
for(j=0;j<=k;j++)
x[j] = y[j];
}
}
}
int main()
{
clrscr();
get();

17 | P a g e
Tina Mittal(A2305216452)
printf("\n The Sack is arranged in the order\n");
sort();
knapsack(0,0.0,0.0);
show();
getch();
}
OUTPUT:

18 | P a g e
Tina Mittal(A2305216452)
EXPERIMENT-10

DATE:

AIM: Implement Traveling Salesman problem based on Branch and Bound technique.

Program:

#include <bits/stdc++.h>
using namespace std;
const int N = 4;

int final_path[N+1];
bool visited[N];
int final_res = INT_MAX;
void copyToFinal(int curr_path[])
{
for (int i=0; i<N; i++)
final_path[i] = curr_path[i];
final_path[N] = curr_path[0];
}
int firstMin(int adj[N][N], int i)
{
int min = INT_MAX;
for (int k=0; k<N; k++)
if (adj[i][k]<min && i != k)
min = adj[i][k];
return min;
}
int secondMin(int adj[N][N], int i)
{
int first = INT_MAX, second = INT_MAX;
for (int j=0; j<N; j++)
{
if (i == j)
continue;
if (adj[i][j] <= first)
{
second = first;
first = adj[i][j];
}
else if (adj[i][j] <= second &&
adj[i][j] != first)
19 | P a g e
Tina Mittal(A2305216452)
second = adj[i][j];
}
return second;
}
void TSPRec(int adj[N][N], int curr_bound, int curr_weight,
int level, int curr_path[])
{
if (level==N)
{
if (adj[curr_path[level-1]][curr_path[0]] != 0)
{
int curr_res = curr_weight +
adj[curr_path[level-1]][curr_path[0]];
if (curr_res < final_res)
{
copyToFinal(curr_path);
final_res = curr_res;
}
}
return;
}
for (int i=0; i<N; i++)
{
if (adj[curr_path[level-1]][i] != 0 &&
visited[i] == false)
{
int temp = curr_bound;
curr_weight += adj[curr_path[level-1]][i];
if (level==1)
curr_bound -= ((firstMin(adj, curr_path[level-1]) +
firstMin(adj, i))/2);
else
curr_bound -= ((secondMin(adj, curr_path[level-1]) +
firstMin(adj, i))/2);
if (curr_bound + curr_weight < final_res)
{
curr_path[level] = i;
visited[i] = true;
TSPRec(adj, curr_bound, curr_weight, level+1,
curr_path);
}

20 | P a g e
Tina Mittal(A2305216452)
curr_weight -= adj[curr_path[level-1]][i];
curr_bound = temp;
memset(visited, false, sizeof(visited));
for (int j=0; j<=level-1; j++)
visited[curr_path[j]] = true;
}
}
}
void TSP(int adj[N][N])
{
int curr_path[N+1];
int curr_bound = 0;
memset(curr_path, -1, sizeof(curr_path));
memset(visited, 0, sizeof(curr_path));
for (int i=0; i<N; i++)
curr_bound += (firstMin(adj, i) +
secondMin(adj, i));
curr_bound = (curr_bound&1)? curr_bound/2 + 1 :
curr_bound/2;
visited[0] = true;
curr_path[0] = 0;
TSPRec(adj, curr_bound, 0, 1, curr_path);
}
int main()
{
int adj[N][N] =
{ {0, 18, 10, 15},
{18, 0, 35, 25},
{10, 35, 0, 30},
{15, 25, 30, 0}
};
TSP(adj);
printf("Minimum cost : %d\n", final_res);
printf("Path Taken : ");
for (int i=0; i<=N; i++)
printf("%d ", final_path[i]);
return 0;
}
OUTPUT:

21 | P a g e
Tina Mittal(A2305216452)
22 | P a g e
Tina Mittal(A2305216452)

You might also like