Design and Analysis of Algorithms Lab 1. Sort a given set of elements using the Quicksort method and det1ermine the time required 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. The elements can be read from a file or can be generated using the random number generator. 2. Using OpenMP, implement a parallelized Merge Sort algorithm to sort a given set of elements and determine the time required 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. The elements can be read from a file or can be generated using the random number generator. 3. a. Obtain the Topological ordering of vertices in a given digraph. b. Compute the transitive closure of a given directed graph using Warshall's algorithm. 4. Implement 0/1 Knapsack problem using Dynamic Programming. 5. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm. 6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm. 7. a. Print all the nodes reachable from a given starting node in a digraph using BFS method. b. Check whether a given graph is connected or not using DFS method. 8. Find a subset of a given set S = {sl, s2,.....,sn} of n positive integers whose sum is equal to a given positive integer d. For example, if S= {1, 2, 5, 6, 8} and d = 9 there are two solutions {1,2,6}and{1,8}.A suitable message is to be displayed if the given problem instance doesn't have a solution. Dept.of CSE, STJIT Ranibennur [1]
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Design and Analysis of Algorithms Lab
1. Sort a given set of elements using the Quicksort method and det1ermine the time required 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. The elements can be read from a file or can be generated using the random number generator.
2. Using OpenMP, implement a parallelized Merge Sort algorithm to sort a given set of elements and determine the time required 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. The elements can be read from a file or can be generated using the random number generator.
3. a. Obtain the Topological ordering of vertices in a given digraph. b. Compute the transitive closure of a given directed graph using Warshall's algorithm.
4. Implement 0/1 Knapsack problem using Dynamic Programming.
5. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm.
6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm.
7. a. Print all the nodes reachable from a given starting node in a digraph using BFS method. b. Check whether a given graph is connected or not using DFS method.
8. Find a subset of a given set S = {sl, s2,.....,sn} of n positive integers whose sum is equal to a given positive integer d. For example, if S= {1, 2, 5, 6, 8} and d = 9 there are two solutions {1,2,6}and{1,8}.A suitable message is to be displayed if the given problem instance doesn't have a solution.
9. Implement any scheme to find the optimal solution for the Traveling Salesperson problem and then solve the same problem instance using any approximation algorithm and determine the error in the approximation.
10. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.
11. Implement All-Pairs Shortest Paths Problem using Floyd's algorithm. Parallelize this algorithm, implement it using OpenMP and determine the speed-up achieved.
12. Implement N Queen's problem using Back Tracking.
Note: In the examination each student picks one question from the lot of all 12 questions.
Dept.of CSE, STJIT Ranibennur [1]
Design and Analysis of Algorithms Lab
1. Quick Sort(Also known as “partition-exchange sort”)
Definition:
Quick sort is a well –known sorting algorithm, based on divide & conquer approach.
The steps are:
1. Pick an element called pivot from the list
2. Reorder the list so that all elements which are less than the pivot come before the pivot and
all
elements greater than pivot come after it. After this partitioning, the pivot is in its final
position. This is called the partition.
3. Recursively sort the sub-list of lesser elements and sub-list of greater elements.
Features:
Developed by C.A.R. Hoare
Efficient algorithm
NOT stable sort
Significantly faster in practice, than other algorithms]
Dept.of CSE, STJIT Ranibennur [2]
Design and Analysis of Algorithms Lab
2. Merge Sort
Definition:
Merge sort is a sort algorithm that splits the items to be sorted into two groups,
recursively sorts each group, and merges them into a final sorted sequence.
Features:
Is a comparison based algorithm
Is a stable algorithm
Is a perfect example of divide & conquer algorithm design strategy
It was invented by John Von Neumann
Example:
Apply merge sort for the following list of elements: 6, 3, 7, 8, 2, 4, 5, 1
Solution:
Dept.of CSE, STJIT Ranibennur [3]
Design and Analysis of Algorithms Lab
3a.Topological Sorting
Description:
Topological sorting is a sorting method to list the vertices of the graph in such an order
that for every edge in the graph, the vertex where the edge starts is listed before the
vertex where the edge ends.
NOTE:
There is no solution for topological sorting if there is a cycle in the digraph .
[MUST be a DAG]
Topological sorting problem can be solved by using
1. DFS method
2. Source removal method
Source removal method:
Purely based on decrease & conquer
Repeatedly identify in a remaining digraph a source, which is a vertex with no
incoming edges
Delete it along with all the edges outgoing from it.
Example:
Apply Source removal – based algorithm to solve the topological sorting problem for the
given graph:
Dept.of CSE, STJIT Ranibennur [4]
Design and Analysis of Algorithms Lab
Dept.of CSE, STJIT Ranibennur [5]
Design and Analysis of Algorithms Lab
3.b Transitive Closure Warshall’s Algorithm
Example:
Dept.of CSE, STJIT Ranibennur [6]
Design and Analysis of Algorithms Lab
Dept.of CSE, STJIT Ranibennur [7]
Design and Analysis of Algorithms Lab
4. Knapsack Problem by DP
Given n items of
integer weights: w1, w2 … wn
values: v1, v2 … vn
A knapsack of integer capacity W, find most valuable subset of the items that fit into the
knapsack. Consider instance defined by first i items and capacity j (j W).
Let V[i,j] be optimal value of such instance.
Initial conditions: V[0,j] = 0 and V[i,0] = 0
Dept.of CSE, STJIT Ranibennur [8]
Design and Analysis of Algorithms Lab
Dept.of CSE, STJIT Ranibennur [9]
Design and Analysis of Algorithms Lab
5. Dijkstra’s Algorithm
(to find Single Source Shortest Paths)
Definitions:
Shortest Path Problem: Given a connected directed graph G with non-negative
weights on the edges and a root vertex r, find for each vertex x, a directed path P
(x) from r to x so that the sum of the weights on the edges in the path P (x) is as
small as possible.
Algorithm
• By Dutch computer scientist Edsger Dijkstra in 1959.
• Solves the single-source shortest path problem for a graph with nonnegative edge weights.
• This algorithm is often used in routing.
E.g.: Dijkstra's algorithm is usually the working principle behind link-state
routing protocols
The method
Dijkstra’s algorithm solves the single source shortest path problem in 2 stages.
Stage 1: A greedy algorithm computes the shortest distance from source to all other nodes
in the graph and saves in a data structure.
Stage 2 : Uses the data structure for finding a shortest path from source to any vertex v.
• At each step, and for each vertex x, keep track of a “distance” D(x) and a directed
path P(x) from root to vertex x of length D(x).
• Scan first from the root and take initial paths P( r, x ) = ( r, x ) with
D(x) = w( rx ) when rx is an edge,
D(x) = _ when rx is not an edge.
For each temporary vertex y distinct from x, set
D(y) = min{ D(y), D(x) + w(xy) }
Dept.of CSE, STJIT Ranibennur [10]
Design and Analysis of Algorithms Lab
Example:Apply Dijkstra’s algorithm to find Single source shortest paths with vertex a as the source.
Solution:Length Dv of shortest path from source (s) to other vertices v and Penultimate vertex Pvfor every vertex v in V:
Dept.of CSE, STJIT Ranibennur [11]
Design and Analysis of Algorithms Lab
6. Kruskal’s AlgorithmMethod: STEP 1: Sort the edges by increasing weight
STEP 2: Start with a forest having |V| number of trees. STEP 3: Number of trees are reduced by ONE at every inclusion of an edge
At each stage: Among the edges which are not yet included, select the one with minimum
weight AND which does not form a cycle.
The edge will reduce the number of trees by one by combining two trees of
the forest
Algorithm stops when |V| -1 edges are included in the MST i.e : when the number of trees in the forest is reduced to ONE.
Example:Apply Kruskal’s algorithm for the following graph to find MST.
Solution:
Dept.of CSE, STJIT Ranibennur [12]
Design and Analysis of Algorithms Lab
Dept.of CSE, STJIT Ranibennur [13]
Design and Analysis of Algorithms Lab
7.a Depth-first search (DFS)
Description: DFS starts visiting vertices of a graph at an arbitrary vertex by marking it as visited.
It visits graph’s vertices by always moving away from last visited vertex to an
unvisited one, backtracks if no adjacent unvisited vertex is available.
It is a recursive algorithm, it uses a stack. A vertex is pushed onto the stack when it’s
reached for the first time. A vertex is popped off the stack when it becomes a dead
end, i.e., when there is no adjacent unvisited vertex
“Redraws” graph in tree-like fashion (with tree edges and back edges for
undirected graph)
Dept.of CSE, STJIT Ranibennur [14]
Design and Analysis of Algorithms Lab
Dept.of CSE, STJIT Ranibennur [15]
Design and Analysis of Algorithms Lab
7 b. Breadth-first search (BFS)
Description:
BFS starts visiting vertices of a graph at an arbitrary vertex by marking it as visited.
It visits graph’s vertices by across to all the neighbors of the last visited vertex
Instead of a stack, BFS uses a queue.
Similar to level-by-level tree traversal
“Redraws” graph in tree-like fashion (with tree edges and cross edges for
undirected graph).
Dept.of CSE, STJIT Ranibennur [16]
Design and Analysis of Algorithms Lab
Dept.of CSE, STJIT Ranibennur [17]
Design and Analysis of Algorithms Lab
8.Sum of subsets
Problem: Given n positive integers w1, ... wn and a positive integer S. Find all subsets
of w1, ... wn that sum to S.
Example:
n=3, S=6, and w1=2, w2=4, w3=6
Solutions:
{2,4} and {6}
• We will assume a binary state space tree.
• The nodes at depth 1 are for including (yes, no) item 1, the nodes at depth 2 are for
item 2, etc.
• The left branch includes wi, and the right branch excludes w.
• The nodes contain the sum of the weights included so far
Sum of subset Problem: State SpaceTree for 3 items
Dept.of CSE, STJIT Ranibennur [18]
Design and Analysis of Algorithms Lab
9. Traveling Salesman Problem (TSP)
The Traveling Salesman Problem (TSP) is a problem in combinatorial optimization studied in
operations research and theoretical computer science. Given a list of cities and their pair wise
distances, the task is to find a shortest possible tour that visits each city exactly once.
Example 6.2.1:
A salesman has to visit five cities A.B, C, D and E. The distances (in hundred kilometers)
between the five cities are shown in Table 6.1.
Table 6.1
Solution:Consider the effective matrix. This is shown in Table 6.2.
Table 6.2
In this matrix first, we will take first row which is referred a city. We select that column
(assignment) for which it contains minimum distance. For this example, incase of first row,
column B (assignment) has the minimum value. In the similar way, we select all the rows and
find the minimum value for the respective columns.
These are given in Table 6.3.
Dept.of CSE, STJIT Ranibennur [19]
Design and Analysis of Algorithms Lab
In this table, we observed that assignment D occur only once with city B. That is city B is
unique for city D and hence we assign city B to D. This is shown in Table 6.4.
Table 6.4
However, for other job assignment occur more than once. Hence they are not unique. So how
other job will be assigned further we discuss below. Next delete row B and column D. Again
select minimum cost value for the remaining cities which is shown below Table 6.5.
Since assignment B occur with city A and D. Hence first we take the difference between the
value of B and next minimum value (here tie is happens). Here 102 maximum difference is 2
for A and hence we assign B to city A. This is shown in Table 6.6.
Table 6.6
Dept.of CSE, STJIT Ranibennur [20]
Design and Analysis of Algorithms Lab
Next delete row A and column B. Again select minimum cost value for the remaining cities
which is shown below Table 6.7.
Since assignment A occur with city C, D and E. Hence we take the difference between the
value of A and next minimum value, here the maximum difference is 3 for Job E. And hence
we assign A to city E. This is shown in Table 6.8.
Table 6.8.
Next delete row E and column A. Again select minimum cost value for the remaining cities
which is shown below Table 6.9.
Here, we cannot assign C to city C. Therefore we only assign E to city C. Then obviously, we
have no other choice rather to assign C for City D. Finally, we can assign all the cities along
with distance which is shown in Table 6.10.
This solution is happened to be same as that of Hungarian method. Hence we can say that the
minimum value is still 26 in both the methods. So this solution is optimal. However our
method seems to be very simple, easy and takes very few steps in solving the method.
Dept.of CSE, STJIT Ranibennur [21]
Design and Analysis of Algorithms Lab
10.Prim’s Algorithm
(To find minimum spanning tree)
Minimum Spanning Tree (MST). Definition:
MST of a weighted, connected graph G is defined as: A spanning tree of G with
minimum total weight.
MST Applications:
• Network design.
Telephone, electrical, hydraulic, TV cable, computer, road
• Approximation algorithms for NP-hard problems.
Traveling salesperson problem, Steiner tree
• Cluster analysis.
• Reducing data storage in sequencing amino acids in a protein
• Learning salient features for real-time face verification
• Auto config protocol for Ethernet bridging to avoid cycles in a network, etc.
Method:
STEP 1: Start with a tree, T0, consisting of one vertex
STEP 2: “Grow” tree one vertex/edge at a time
Construct a series of expanding sub-trees T1, T2, … Tn-1.
At each stage construct Ti + 1 from Ti by adding the minimum weight edge
connecting a vertex in tree (Ti) to one vertex not yet in tree, choose from “fringe”
edges (this is the “greedy” step!) Algorithm stops when all vertices are included.
Dept.of CSE, STJIT Ranibennur [22]
Design and Analysis of Algorithms Lab
Example:Apply Prim’s algorithm for the following graph to find MST.
Dept.of CSE, STJIT Ranibennur [23]
Design and Analysis of Algorithms Lab
11. Floyd’s Algorithm
Dept.of CSE, STJIT Ranibennur [24]
Design and Analysis of Algorithms Lab
Example:
Dept.of CSE, STJIT Ranibennur [25]
Design and Analysis of Algorithms Lab
Program 1Sort a given set of elements using the Quicksort method and determine the time required 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.The elements can be read from a file or can be generated using the random number generator.
int a[20],i,j,n;clock_t begin,end;clrscr();printf("\n Quick Sort");printf("\n\n");printf("Enter The Value of n\n");scanf("%d",&n);for(i=0;i<n;i++)
{ scanf("The array elements are %d",a[i]=rand()%100);
}printf("Elements ARE: ");for(i=0;i<n;i++){
printf("\t%d",a[i]=rand()%100);}begin=clock();qsort(a,0,n-1);end=clock();printf("\nSorted Array is");for(i=0;i<n;i++)printf("\t%d",a[i]);printf("\n\n");printf("Begin Time=%d\n",begin);printf("End Time is=%d\n",end);printf("Total No. of clock ticks=%d\n",(end-begin));printf("Total Time Required=%f",((end-begin)/(CLK_TCK)));getch();
Quick SortEnter The Value of n 5Elements ARE17 95 15 48 26Sorted Array is15 17 26 48 95Begin Time=50End Time is=61Total No. of clock ticks=11Total Time Required=0.604396
Dept.of CSE, STJIT Ranibennur [27]
Design and Analysis of Algorithms Lab
Program 2Using OpenMP, implement a parallelized Merge Sort algorithm to sort a given set of elements and determine the time required 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. The elements can be read from a file or can be generated using the random number generator.
int a[100],n,i;double starttime,endtime:printf("Enter the number of elements:\n");scanf("%d",&n);printf("Enter the array elements:\n");
for(i=0;i<n;i++) { a[i]=rand()%100; } printf("The elements before sorting are:\n"); for(i=0;i<n;i++) { printf("%d\t",a[i]); } Starttime=omp_get_wtime(); mergesort(a,0,n-1); endtime=omp_get_wtime(); printf("\nThe sorted elements are:\n"); for(i=0;i<n;i++) { printf("%d\t",a[i]); } printf("\nThe time taken is %lf\n",(double)(endtime-starttime));
}
Dept.of CSE, STJIT Ranibennur [29]
Design and Analysis of Algorithms Lab
********************OUTPUT***************************Enter the number of elements:5Enter the elements3 12 5 90 10The sorted array is3 5 19 12 90The time required for sorting is 0.102453
Dept.of CSE, STJIT Ranibennur [30]
Design and Analysis of Algorithms Lab
Program 3(a)Obtain the topological ordering of vertices in a given digraph.
int n,cost[10][10],source,i,j;clrscr();printf("Enter the number of vertices\n");scanf("%d",&n);printf("Enter matrix\n");for(i=1;i<=n;i++){ for(j=1;j<=n;j++)
{scanf("%d",&cost[i][j]);
}}warshall(cost,n);printf("The Transitive Closure of given graph is \n");for(i=1;i<=n;i++){ for(j=1;j<=n;j++)
{printf("%d\t",cost[i][j]);
}printf("\n");}getch();
}
void warshall(int c[10][10],int n){
int i,j,k;for(k=1;k<=n;k++){ for(i=1;i<=n;i++)
{ for(j=1;j<=n;j++){
c[i][j]=(c[i][j]||c[i][k]&&c[k][j]);}
} }}
Dept.of CSE, STJIT Ranibennur [33]
Design and Analysis of Algorithms Lab
*******************OUTPUT***************************Enter the number .of vertices 4
Enter matrix:0 1 0 00 0 0 10 0 0 01 0 1 0The Transitive Closure of given graph is
1 1 1 1 1 1 1 10 0 0 01 1 1 1
Dept.of CSE, STJIT Ranibennur [34]
Design and Analysis of Algorithms Lab
Program 4Implement 0 / 1 Knapsack problem using dynamic programming.
int n,i,j,capacity;int wt[20],ve[20];int v[20][20],w;clrscr();printf("Enter the No. of items\n:");scanf("%d",&n);printf("-------------------\n\nWeights Values\n\n--------------------\n");for(i=1;i<=n;i++){
scanf("%d",&wt[i]);scanf("%d",&ve[i]);
}printf("Enter the Capacity of Knapsack\n");scanf("%d",&capacity);for(i=0;i<=n;i++){ for(j=0;j<=capacity;j++)
int n,cost[10][10],sourse,i,j,dist[10];clrscr();printf("Enter the number of vertices\n");scanf("%d",&n);printf("Enter the graph is matrix form \n");for(i=1;i<=n;i++)
int mincost=0,cost[10][10],n,i,j,ne,a,b,min,u,v;printf("Enter the number of verteces\n");scanf("%d",&n);printf("Enter the cost matrix\n");for(i=1;i<=n;i++)
Enter the no. of vertices: 3Enter the Cost Matrix 0 1 1 1 0 11 1 0Enter The Source Vertex:1The Vertices from 11 is Reachable2 is Reachable3 is Reachable
Dept.of CSE, STJIT Ranibennur [42]
Design and Analysis of Algorithms Lab
Program 7(b)Check weather a given graph is connected or not using DFS method.
int n,j,src,cost[10][10],s[10],i;clrscr();printf("Enter the no. of Vertices\n");scanf("%d",&n);printf("Enter the Cost of Matrix\n");for(i=1;i<=n;i++)for(j=1;j<=n;j++)scanf("%d",&cost[i][j]);for(i=1;i<=n;i++)s[i]=0;printf("Enter The Source Vertex\n");scanf("%d",&src);dfs(n,src,cost,s);printf("The Vertices from %d\n",src);for(i=1;i<=n;i++){
if(s[i]==1)printf("%d is Reachable\n",i);
elseprintf("%d is not Rreachable\n",i);
}getch();
}
Dept.of CSE, STJIT Ranibennur [43]
Design and Analysis of Algorithms Lab
*******************OUTPUT***************************1)Enter the no. of vertices:3Enter the Cost Matrix 0 1 1 0 0 01 1 0Enter The Source Vertex:1The Vertices from 11 is Reachable2 is Reachable3 is not Reachable
2)Enter the no. of vertices:4Enter the Cost Matrix 0 1 1 1 0 0 0 10 0 0 10 0 0 0Enter The Source Vertex:1The Vertices from 11 is Reachable2 is Reachable3 is Reachable4 is Reachable
Dept.of CSE, STJIT Ranibennur [44]
Design and Analysis of Algorithms Lab
Program 8Find a subset of a given set S={s1, s2,…., sn} of n positive integers whose sum is equal to a given positive integer d. for example, if S={ 1,2,5,6,8} and d=9 there are two solutions { 1,2,6} and {1,8}. A suitable message is to be displayed if the given problem instance does not have a solution.
#include<stdio.h>#include<conio.h>#define MAX 10int s[MAX],x[MAX];int d;
void main(){ int i,n,sum=0; clrscr(); printf("\nEnter max number : "); scanf("%d",&n); printf("\nEnter the set in increasing order : \n"); for(i=1;i<=n;i++) scanf("%d",&s[i]); printf("\nEnter the max subset value : "); scanf("%d",&d); for(i=1;i<=n;i++) sum=sum+s[i]; if(sum<d || s[1]>d)
Progarm 9Implement any scheme to find the optimal solution for the Traveling Salesperson problem and then solve the same problem instance using any approximation algorithm and determine the error in the approximation.
Program 10Find minimum cost spanning tree of a given undirected graph using prims algorithm
#include<stdio.h>#include<conio.h>void main(){
int mincost=0,cost[10][10],n,i,j,visited[10],ne,a,b,min,u,v;clrscr();printf("Enter the no.of vertices\n");scanf("%d",&n);printf("Enter the cost matrix\n");for(i=1;i<=n;i++)
Enter the no. of vertices: 3Enter the Cost Matrix 0 2 12 0 31 3 0
1 Edge(1,3)=12 Edge(1,2)=2The Minimum Cost of Spanning Tree is 3
Dept.of CSE, STJIT Ranibennur [51]
Design and Analysis of Algorithms Lab
Program 11Implement All-Pairs Shortest Paths Problem using Floyd's algorithm. Parallelize this algorithm, implement it using OpenMP and determine the speed-up achieved.
int i,j,k;#pragma omp parallel for private(i,j,k) shared(p)for(k=1;k<=n;k++)
for(i=1;i<=n;i++)for(j=1;j<=n;j++)
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);}
int main(){
int i,j,n,a[10][10],d[10][10],source;double starttime,end time;printf("Enter the no.of nodes: ");scanf("%d",&n);printf("\nEnter the adjacency matrix\n");for(i=1;i<=n;i++)
for(j=1;j<=n;j++)scanf("%d",&a[i][j]);
starttime=omp_get_wtime();floyd(n,a);endtime=omp_get_wtime();printf("\n\nThe distance matrix is \n");for(i=1;i<=n;i++){ for(j=1;j<=n;j++)
printf("%d\t",a[i][j]);printf("\n");
}printf("\n\nThe time taken is %l0.9f\n",(double)(starttime-endtime));return 0;