You are on page 1of 62

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. 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. 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. Implement 0/1 Knapsack problem using Dynamic Programming.

2.

3.

4. 5.

From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm. 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. 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. 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. Find Minimum Cost Spanning Tree of a given undirected graph using Prims algorithm. Implement All-Pairs Shortest Paths Problem using Floyd's algorithm. Parallelize this algorithm, implement it using OpenMP and determine the speed-up achieved. Implement N Queen's problem using Back Tracking.

6.

7.

8.

9.

10. 11.

12.

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:

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: Repeatedly identify in a remaining digraph a source, which is a vertex with no incoming edges

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 Warshalls 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. Dijkstras 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
Dijkstras 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 Dijkstras 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 Pv for every vertex v in V:

Dept.of CSE, STJIT Ranibennur

[11]

Design and Analysis of Algorithms Lab

6. Kruskals Algorithm
Method: 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 Kruskals 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 graphs 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 its 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 graphs 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.Prims 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 Prims algorithm for the following graph to find MST.

Dept.of CSE, STJIT Ranibennur

[23]

Design and Analysis of Algorithms Lab

11. Floyds 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 1 Sort 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. #include<stdio.h> #include<conio.h> #include<time.h> void swap(int *x,int *y) { int temp; temp=*x; *x=*y; *y=temp; } int partition(int a[],int l,int r) { int i,j; int p; p=a[l]; i=l+1; j=r; while(i<=j) { delay(100); while(a[i]<=p) i++; while(a[j]>=p) j--; swap(&a[i],&a[j]); } swap(&a[i],&a[j]); swap(&a[l],&a[j]); return j; } void qsort(int a[],int l,int r) { int s; if(l<r) { s=partition(a,l,r); qsort(a,l,s-1); qsort(a,s+1,r); } }
Dept.of CSE, STJIT Ranibennur [26]

Design and Analysis of Algorithms Lab

void main() { 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(); } ********************OUTPUT*************************** Quick Sort Enter The Value of n 5 Elements ARE 17 95 15 48 26 Sorted Array is 15 17 26 48 95 Begin Time=50 End Time is=61 Total No. of clock ticks=11 Total Time Required=0.604396

Dept.of CSE, STJIT Ranibennur

[27]

Design and Analysis of Algorithms Lab

Program 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. #include<stdio.h> #include<stdlib.> #include<time.h> #include<omp.h> void merge(int a[],int low,int mid,int high) { int b[100],i,j,k; i=low; j=mid+1; k=low; while(i<=mid && j<=high) { if(a[i]<a[j]) { b[k]=a[i]; k++; i++; } else { b[k]=a[j]; k++; j++; } } while(i<=mid) { b[k]=a[i]; k++; i++; } while(j<=high) { b[k]=a[j]; k++; j++; } for(i=low;i<=high;i++) { a[i]=b[i]; } }
Dept.of CSE, STJIT Ranibennur [28]

Design and Analysis of Algorithms Lab

void mergesort(int a[],int low,int high) { int mid; if(low<high) { mid=(low+high)/2; #pragma omp parallel sections { #pragma omp section mergesort(a,low,mid); #pragma omp section mergesort(a,mid+1,high); } merge(a,low,mid,high); } } void main() { 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: 5 Enter the elements 3 12 5 90 10 The sorted array is 3 5 19 12 90 The 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. #include<stdio.h> #include<conio.h> int temp[10],k=0; void topo(int n,int indegree[10],int a[10][10]) { int i,j; for(i=1;i<=n;i++) { if(indegree[i]==0) { indegree[i]=-1; temp[++k]=i; for(j=1;j<=n;j++) { if(a[i][j]==1 && indegree[j]!=-1) indegree[j]--; } i=0; } } } void main() { int i,j,n,indegree[10],a[10][10]; clrscr(); printf("Enter the number of vertices: "); scanf("%d",&n); for(i=1;i<=n;i++) indegree[i]=0; printf("Enter the adjacency matrix\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { scanf("%d",&a[i][j]); if(a[i][j]==1) indegree[j]++; } topo(n,indegree,a); if(k!=n) printf("\nTopological ordering is not possible\n"); else { printf("The topological ordering is \n"); for(i=1;i<=k;i++) printf("%d\t",temp[i]); } getch(); }
Dept.of CSE, STJIT Ranibennur [31]

Design and Analysis of Algorithms Lab

*******************OUTPUT*************************** Enter the number of vertices: 5 Enter the adjacency matrix: 0 0 1 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 The topological ordering is: 1 2 3 5 4

Dept.of CSE, STJIT Ranibennur

[32]

Design and Analysis of Algorithms Lab

Program 3(b) Compute the transitive closure of a given directed graph using Warshalls algorithm. #include<stdio.h> #include<conio.h> void warshall(int c[10][10],int n); void main() { 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 0 0 0 0 1 0 0 0 0 1 0 1 0 The Transitive Closure of given graph is 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1

Dept.of CSE, STJIT Ranibennur

[34]

Design and Analysis of Algorithms Lab

Program 4 Implement 0 / 1 Knapsack problem using dynamic programming. #include<stdio.h> #include<conio.h> int max(int a,int b) { if(a>b) return a; else return b; } void main() { 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++) { if(i==0||j==0) { v[i][j]=0; } else if(j-wt[i]>=0) { v[i][j]=max(v[i-1][j],v[i-1][j-wt[i]]+ve[i]); } else { v[i][j]=v[i-1][j]; } printf("%4d",v[i][j]); } printf("\n"); }
Dept.of CSE, STJIT Ranibennur [35]

Design and Analysis of Algorithms Lab

w=capacity; printf("The item in the knapsack\n"); for(i=n;i>0;i--) { if(v[i][w]==v[i-1][w]) continue; else { w=w-wt[i]; printf("%3d",wt[i]); } } printf("\n Total Profit=%d",v[n][capacity]); getch(); } *******************OUTPUT*************************** Enter the No. of items: 2 -------------------Weights Values-------------------2 10 3 20 Enter the Capacity of Knapsack:3 0 0 0 0 0 0 10 10 0 0 10 20 The item in the knapsack: 3 Total Profit: 20

Dept.of CSE, STJIT Ranibennur

[36]

Design and Analysis of Algorithms Lab

Program 5 From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstras algorithm. #include<stdio.h> #include<conio.h> void dijkstras(int cost[10][10], int dist[10], int n, int v) { int i,u,w,count,flag[10],min; for(i=1;i<=n;i++) { flag[i]=0; dist[i]=cost[v][i]; } flag[v]=1; dist[v]=1; count=2; while(count<n) { for(i=1,min=999;i<=n;i++) { if(dist[i]<min && !flag[i]) { min=dist[i]; v=i; } } flag[v]=i; count++; for(w=1;w<=n;w++) { if(dist[v]+cost[v][w]<dist[w] && !flag[w]) dist[w]=dist[v]+cost[v][w]; } } } void main() { 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++) for(j=1;j<=n;j++)
Dept.of CSE, STJIT Ranibennur [37]

Design and Analysis of Algorithms Lab

{ scanf("%d",&cost[i][j]); if(cost[i][j]==0) cost[i][j]=999; } printf("Enter the sourse vertex\n"); scanf("%d",&sourse); dijkstras(cost,dist,n,sourse); for(i=1;i<=n;i++) if(sourse!=i) printf("%d-->%d:: %d\n",sourse,i,dist[i]); getch(); } *******************OUTPUT*************************** Enter the number of vertices= 4 Enter the graph is matrix form 0 2 0 0 0 0 3 5 0 0 0 0 4 0 3 0 Enter the sourse vertex = 4 4-->1:: 4 4-->2:: 6 4-->3:: 3

Dept.of CSE, STJIT Ranibennur

[38]

Design and Analysis of Algorithms Lab

Program 6 Find minimum cost spanning tree of a given undirected graph using Kruskals algorithm. #include<stdio.h> #include<conio.h> int parent[10]; void main() { 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++) for(j=1;j<=n;j++) { scanf("%d",&cost[i][j]); if(cost[i][j]==0) cost[i][j]=999; } ne=1; while(ne<n) { for(min=999,i=1;i<=n;i++) for(j=1;j<=n;j++) if(cost[i][j]<min) { min=cost[i][j]; a=u=i; b=v=j; } while(parent[u]) u=parent[u]; while(parent[v]) v=parent[v]; if(v!=u) { printf("%d Edge (%d,%d)=%d\n",ne++,a,b,min); mincost+=min; parent[v]=u; } cost[a][b]=cost[b][a]=999; } printf("\n The minimum cost of spanning tree is %d\n",mincost); getch(); }
Dept.of CSE, STJIT Ranibennur [39]

Design and Analysis of Algorithms Lab

*******************OUTPUT*************************** Enter the number of verteces:4 Enter the cost matrix 0 1 2 4 1 0 0 5 2 0 0 3 4 5 3 0 1 Edge (1,2)=1 2 Edge (1,3)=2 3 Edge (3,4)=3 The minimum cost of spanning tree is 6

Dept.of CSE, STJIT Ranibennur

[40]

Design and Analysis of Algorithms Lab

Program 7(a) Print all the nodes reachable from a given starting node in a digraph using breadth first search method. #include<stdio.h> #include<conio.h> int i,j,n,f=0,r=-1,cost[10][10],q[10],q1[10]; void bsf(int u) { int v; for(v=1;v<=n;v++) { if(cost[u][v]==1&&q1[v]==0) q[++r]=v; } if(f<=r) { q1[q[f]]=1; bsf(q[f++]); } } void main() { int source; clrscr(); printf("Enter the no. of vertices: "); scanf("%d",&n); printf("\nEnter the Cost 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++) { q[i]=0; q1[i]=0; } printf("Enter The Source Vertex\n"); scanf("%d",&source); bsf(source); printf("The Vertices from %d:\n",source); for(i=1;i<=n;i++) { if(q1[i]==1) printf("%d is Reachable\n",i); } getch(); }
Dept.of CSE, STJIT Ranibennur [41]

Design and Analysis of Algorithms Lab

*******************OUTPUT*************************** Enter the no. of vertices: 3 Enter the Cost Matrix 0 1 1 1 0 1 1 1 0 Enter The Source Vertex:1 The Vertices from 1 1 is Reachable 2 is Reachable 3 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. #include<stdio.h> #include<conio.h> void dfs(int n,int u,int cost[10][10],int s[10]) { int v; s[u]=1; for(v=1;v<=n;v++) { if(cost[u][v]==1 && !s[v]) dfs(n,v,cost,s); } } void main() { 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); else printf("%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:3 Enter the Cost Matrix 0 1 1 0 0 0 1 1 0 Enter The Source Vertex:1 The Vertices from 1 1 is Reachable 2 is Reachable 3 is not Reachable 2) Enter the no. of vertices:4 Enter the Cost Matrix 0 1 1 1 0 0 0 1 0 0 0 1 0 0 0 0 Enter The Source Vertex:1 The Vertices from 1 1 is Reachable 2 is Reachable 3 is Reachable 4 is Reachable

Dept.of CSE, STJIT Ranibennur

[44]

Design and Analysis of Algorithms Lab

Program 8 Find 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 10 int s[MAX],x[MAX]; int d; void sumofsub(int p,int k,int r) { int i; x[k]=1; if((p+s[k])==d) { for(i=1;i<=k;i++) if(x[i]==1) printf("%d",s[i]); printf("\n"); } else if (p+s[k]+s[k+1]<=d) sumofsub(p+s[k],k+1,r-s[k]); if((p+r-s[k]>=d) && (p+s[k+1]<=d)) { x[k]=0; sumofsub(p,k+1,r-s[k]); } } 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)
Dept.of CSE, STJIT Ranibennur [45]

Design and Analysis of Algorithms Lab

printf("\nNo subset possible"); else sumofsub(0,1,sum); getch(); }

********************OUTPUT*************************** 1) Enter the max number 5 Enter the set in increasing order: 1 2 5 6 8 Enter the max subset value: 9 1 1 2 8 6

2) Enter the max number 5 Enter the set in increasing order: 34569 Enter the max subset value: 2 No subset possible

Dept.of CSE, STJIT Ranibennur

[46]

Design and Analysis of Algorithms Lab

Progarm 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. #include <stdio.h> #include<stdlib.h> #include<conio.h> int i,j, e,n,v1,v2,wt, G[10][10], list[10], d[30], p[30][20],r=0; int fact(int num) { int i,f=1; if (num!=0) for(i=1;i<=num;i++) f=f*i; return f; } int min_dist(int dist[]) { int min_index=0,minimum=dist[0]; for(i=0;i<fact(n-1);i++) if(dist[i]<minimum) { minimum= dist[i]; min_index=i; } return min_index; } void perm(int list[], int k, int m) { int i, temp; if(k==m) { for(i=0;i<=m;i++) { p[r][i+1]=list[i]; } r++; } else for(i=k;i<=m;i++) { Temp=list[k];list[k]=list[i];list[i]=temp;
Dept.of CSE, STJIT Ranibennur [47]

Design and Analysis of Algorithms Lab

perm(list, k+1,m); temp=list[k];list[k]=list[i];list[i]=temp; } } void sol() { int i,j; perm(list,0,n-2); for(i=0;i<fact(n-1);i++) { p[i][0]=0; p[i][n]=0; } for(i=0;i<fact(n-1);i++) { d[i]=0; for(j=0;j<n;j++) d[i]=d[i]+G[p[i][j]][p[i][j+1]]; } } void print_data() { int i,j,pos; printf("possible paths & costs\n"); for(i=0;i<fact(n-1);i++) { for(j=0;j<n+1;j++) printf("%d\t",p[i][j] ) ; printf("%d\n",d[i]); } printf("\nshortest path"); pos=min_dist(d); printf("\ncost %d\n", d[pos]); for (j=0;j<=n;j++) printf("\n%d ",p[pos][j]); } void main() { clrscr(); printf("Enter number of nodes"); scanf("%d",&n); printf("no. of edges");
Dept.of CSE, STJIT Ranibennur [48]

Design and Analysis of Algorithms Lab

scanf("%d",&e); for(i=0;i<n;i++) for (j=0;j<n;j++) G[i][j]=0; for(i=0;i<e;i++) { printf("v1..v2..wt"); scanf("%d%d%d",&v1,&v2,&wt); G[v2][v1]=G[v1][v2]=wt; } for(i=0;i<n-1;i++)//initializing the list for permutation list[i]=i+1; sol(); print_data(); getch(); }

********************OUTPUT*************************** Enter number of nodes: 3 no. of edges :3 v1..v2..wt : 1 2 v1..v2..wt : 1 3 v1..v2..wt : 2 3 5 4 3

possible paths & costs: 0 0 1 2 2 1 0 0 5 5

shortest path cost 5 0 1 2 0

Dept.of CSE, STJIT Ranibennur

[49]

Design and Analysis of Algorithms Lab

Program 10 Find 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++) for(j=1;j<=n;j++) { scanf("%d",&cost[i][j]); if(cost[i][j]==0) cost[i][j]=999; } visited[1]=1; for(i=2;i<=n;i++) visited[i]=0; ne=1; while(ne<n) { for(min=999,i=1;i<=n;i++) for(j=1;j<=n;j++) if(cost[i][j]<min) if(visited[i]==0) continue; else { min=cost[i][j]; a=u=i; b=v=j; } if(visited[u]==1&&visited[v]==0) { printf("%d Edge(%d%d)=%d\n",ne++,a,b,min); mincost+=min; visited[v]=1; } cost[a][b]=cost[b][a]=999; } printf("\n The Minimum Cost of Spanning Tree is %d\n",mincost); getch(); }
Dept.of CSE, STJIT Ranibennur [50]

Design and Analysis of Algorithms Lab

********************OUTPUT*************************** Enter the no. of vertices: 3 Enter the Cost Matrix 0 2 1 2 0 3 1 3 0 1 Edge(1,3)=1 2 Edge(1,2)=2 The Minimum Cost of Spanning Tree is 3

Dept.of CSE, STJIT Ranibennur

[51]

Design and Analysis of Algorithms Lab

Program 11 Implement All-Pairs Shortest Paths Problem using Floyd's algorithm. Parallelize this algorithm, implement it using OpenMP and determine the speed-up achieved. #include<stdio.h> #include<omp.h> #define INFINITY 999 int min(int i,int j) { if(i<j) return i; else return j; } void floyd(int n,int p[10][10]) { 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; }
Dept.of CSE, STJIT Ranibennur [52]

Design and Analysis of Algorithms Lab

********************OUTPUT*************************** Enter the no of nodes: 5 Enter the adjancy matrix 0 15 8 10 15 0 4 999 8 4 0 999 10 999 999 0 999 999 12 7 The distance matrix is 0 12 8 10 12 0 4 22 8 4 0 18 10 22 18 0 17 16 12 7

999 999 12 7 0

17 16 12 7 0

The time taken is: 0.001107683

Dept.of CSE, STJIT Ranibennur

[53]

Design and Analysis of Algorithms Lab

Program 12 Implement N Queens problem using back tracking. #include<stdio.h> #include<conio.h> char s[30][30],count; void display(int m[30],int n) { int i,j; printf("\n______%d_____\n",++count); for(i=0;i<n;i++) for(j=0;j<n;j++) s[i][j]='X'; for(i=0;i<n;i++) s[i][m[i]]='Q'; for(i=0;i<n;i++) { for(j=0;j<n;j++) printf("%2c",s[i][j]); printf("\n\n"); } printf("\n\n\n"); getch(); } int place(int m[30],int k) { int i; for(i=0;i<k;i++) { if(m[k]==m[i]||(abs(m[i]-m[k])==abs(i-k))) return 0; } return 1; } void main() { int n,k=0,i,m[30]; clrscr(); printf("Enter the number of queens\n"); scanf("%d",&n); if(n==2||n==3) { printf("no solutions\n"); getch();
Dept.of CSE, STJIT Ranibennur [54]

Design and Analysis of Algorithms Lab

exit(0); } n--; for(m[0]=0;k>=0;m[k]++) { while(m[k]<=n && !place(m,k)) m[k]++; if(m[k]<=n) { if(k==n) { display(m,n+1); } else k++,m[k]=-1; } else k--; } } ********************OUTPUT*************************** Enter the number of queens 4 ______1_____ X Q X X X X X Q Q X X X X X Q X ______2_____ X X Q Q X X X X X X Q X

X X Q X

Dept.of CSE, STJIT Ranibennur

[55]

Design and Analysis of Algorithms Lab

Viva Questions
1) What is the time complexity of linear search? 2) What is the time complexity of binary search? 3) What is the major requirement for binary search? The given list should be sorted. 4) What is binary search? It is an efficient method of finding out a required item from a given list, provided the list is in order.The process is: 1.First the middle item of the sorted list is found. 2.Compare the item with this element. 3.If they are equal search is complete. 4.If the middle element is greater than the item being searched, this process is repeated in the upper half of the list. 5.If the middle element is lesser than the item being searched, this process is repeated in the lower half of the list. 5) What is heap? A heap can be defined as a binary tree with keys assigned to its nodes per node) provided the following two conditions are met: 1 The trees shape requirement The binary tree is essentially complete ( or simply ( one key (n) (log2n)

complete), that is, all its levels are full except possibly the last level, where only some rightmost leaves may be missing. 2. The parental dominance requirement The key at each node is greater than or equal to the keys at its children. 6) What is Merge Sort? Merge sort is an O (n log n) comparison-based sorting algorithm. Where the given array is divided into two equal parts. The left part of the array as well as the right part of the array is sorted recursively. Later, both the left part and right part are merged into a single sorted array. 7) On which paradigm Merge sort is based? Merge-sort is based on the divide-and-conquer paradigm. Dept.of CSE, STJIT Ranibennur [56]

Design and Analysis of Algorithms Lab 8) What is the time complexity of merge sort? 9) What is the space requirement of merge sort? Space requirement: (n) (not in-place). 10)When do you say an algorithm is stable and in place? Stable if it retains the relative ordering. In place if it does not use extra memory. 11 ) Name the design strategy used in Selection Sort. 12) Define Brute force strategy. Brute force is a straight forward approach to solving a problem, usually directly based on the problems statement and definitions of the concepts involved. 13) What is the time complexity of Selection Sort algorithm? 14) Why is the name Selection Sort? Algorithm selects the smallest number in the array and places it in its final position the sorted array. 15) When is Selection Sort algorithm useful?
2

n log n.

Brute force

(n2)

comparisons. Selection Sort algorithm requires (ncan be very useful if writes are the most expensive operation. 16) What are the drawbacks of Selection Sort? Inefficient on large lists. It requires same number of iterations no matter how well-organized the array is. It uses internal sorting, means it would require the entire array to be in main memory. 17) Can knapsack problem be solved in any other technique? It can be solved using many other techniques such as BruteForce, Greedy technique, Branch and bound etc..

18) Mention few applications of dynamic programming. Can be applied to find factorial, fibonacci numbers in which the required value may depend on previously computed values. To find the longest common substrings of the strings "ABAB", "BABA" and "ABBA" are the strings "AB" and "BA" of length 2. Other common substrings are "A", "B" and the empty string . etc.. Dept.of CSE, STJIT Ranibennur [57]

Design and Analysis of Algorithms Lab 19) Compare Dynamic programming and Divide and conquer. Dynamic programming differs from the "Divide and Conquer" (D-and-C) method in the fact that the problems solved by D-and-C can have many non-overlapping subproblems i.e, new subproblems may be generated when the method is applied. Both use recursion. 20) What is the other name for Dijkstras Algorithm? Single Source Shortest Path Algorithm. 21) What is the constraint on Dijkstras Algorithm? This algorithm is applicable to graphs with non-negative weights only. 22) What is a Weighted Graph? A weighted graph is a graph with numbers assigned to its edges. These numbers are called weights or costs. 23) What is a Connected Graph? A graph is said to be connected if for every pair of its vertices u and v there is a path from u to v. 24) Differentiate b/w Traveling Salesman Problem(TSP) and Dijkstras Algorithm. In TSP, given n cities with known distances b/w each pair , find the shortest tour that passes through all the cities exactly once before returning to the starting city. In Dijkstras Algorithm, find the shortest path from source vertex to all other remaining vertices 25) Differentiate b/w Prims Algorithm and Dijkstras Algorithm? Prims algorithm is to find minimum cost spanning tree. Dijkstras algorithm is to find the shortest path from source vertex to all other remaining vertices. 26) What are the applications of Dijkstras Algorithm? It finds its application even in our day to day life while travelling. They are helpful in routing applications. 27) What is Divide and Conquer Technique? (I) Divide the instance of a problem into two or more smaller instances (II) Solve the smaller instances recursively (III) Obtain solution to original instances by combining these solutions 28) What is the another name for Quicksort? Dept.of CSE, STJIT Ranibennur Partition Exchange Sort [58]

Design and Analysis of Algorithms Lab 29) What are the advantages and disadvantages of Quick sort? Advantage: Fastest among all sorting algorithms Suitable when the input size is very large. Disadvantage: Heavily based on recursive sorting technique It takes O (n* log n) time and O (log n) additional space due to recursion. 30) When do you say that a Quick sort having best case complexity? When the pivot exactly divides the array into equal half 31) when do you say that the pivot element is in its final position? When all the elements towards the left of pivot are <= pivot and all the elements towards the right of pivot are >= pivot. 32) What is CLK_TCK? macro defines the number of clock ticks per second which is available in the TIME.H header file. 33) What is BFS traversal? It proceeds in a concentric manner by visiting first all the vertices that are adjacent to a starting vertex, then all unvisited vertices two edges apart from it and so on , until all the vertices are in the same connected component as the starting vertex are visited. If there still remains unvisited vertices, the algorithm to be restarted at an arbitrary vertex of another connected component of a graph. 34) What is DFS traversal? Consider an arbitrary vertex v and mark it as visited on each iteration, proceed to an unvisited vertex w adjacent to v. we can explore this new vertex depending upon its adjacent information. This process continues until dead end is encountered.(no adjacent unvisited vertex is available). At the dead end the algorithm backs up by one edge and continues the process of visiting unvisited vertices. This process continues until we reach the starting vertex. 35) What are Tree edge, Back edge & Cross edge ? Tree edge: whenever a new unvisited vertex is reached for the first time, it is attached as a child to the vertex from which it is being visited. Such an edge is called a tree edge. Back edge: An edge leading to a previously visited vertex other than its immediate predecessor. Such an edge is called a back edge Cross edge If an edge leading to a previously visited vertex other than its immediate predecessor (i.e. its parent in the tree). Is encountered, the edge is noted as a cross edge.

Dept.of CSE, STJIT Ranibennur

[59]

Design and Analysis of Algorithms Lab 36) What are the various applications of BFS & DFS tree traversal technique? Application of BFS Checking connectivity and checking acyclicity of a graph. Check whether there is only one root in the BFS forest or not. If there is only one root in the BFS forest, then it is connected graph disconnected graph. For checking cycle presence, we can take advantage of the graph's representation in the form of a BFS forest, if the latter vertex does not have cross edge, then the graph is acyclic. Application of DFS To check whether given graph is connected or not. To check whether the graph is cyclic or not. To find the spanning tree. Topological sorting. otherwise

37) Which data structures are used in BFS & DFS tree traversal technique? We use Stack data structure to traverse the graph in DFS traversal. We use queue data structure to traverse the graph in DFS traversal. 38) What are the efficiencies of BFS & DFS algorithms for Adjacency matrix and adjacency list representation? Adjacency matrices: (V2) Adjacency linked lists: (V+E) 41) Define squashed order? Any subsets involving aj can be listed only after all the subsets involving a1,,aj1(j=1,2,,n-1) 42) Explain time and space trade off strategy. It is a strategy in which time efficiency can be achieved at the cost of extra memory usage. 43) Which technique does the Horspool algorithm uses? Input enhancement technique 44) Explain Input enhancement technique. It is a technique in which the problems input is preprocessed in whole or in part and the additional information stored is obtained to solve the problem. 45) What is a shift table? It is a table that stores the shift information i.e it stores the distance of each rightmost character in the first m-1 characters of the pattern from the last character of the pattern and stores the length of the pattern as the shift size if the character is not present in the pattern.

Dept.of CSE, STJIT Ranibennur

[60]

Design and Analysis of Algorithms Lab 46) Which is better Brute Force or Horspool algorithm for string matching? Horspool is better as it reduces the number of comparisons. 47) Differentiate between Brute-Force technique and Horspool algorithm for string matching. a) In brute-force, comparison starts from left where as in Horspool comparison starts from right. b) In brute-force technique, if there is a character mismatch then we shift the pattern to the right by 1 position. In Horspool, if there is a mismatch then the shift size is obtained from the shift table and the pattern is shifted accordingly. 48) Differentiate between Horspool and Boyer -Moore algorithms. Horspool algorithm uses only Shift table to obtain the shift information. Boyer - Moore algorithm uses 2 tables. -Bad symbol shift table (same as the shift table used by Horspool).The shift information of this table is known as d1

-Good suffix shift table The shift information from this table is known as d2. Shifting is done by taking max(d1,d2). 49) What is Dynamic Programming? It is a technique for solving problems with overlapping sub problems. 50) What does Dynamic Programming have in common with Divide-and-Conquer? Both solve the problems by dividing the problem into sub problems. Using the solutions of sub problems, the solutions for larger instance of the problem can be obtained. 51) What is a spanning tree ? A spanning tree of a weighted connected graph is its connected acyclic(no cycles) subgraph (i.e. a tree)that contains all the vertices of a graph.

52) What is a minimum spanning tree ? Minimum spanning tree of a connected graph is its spanning tree of smallest weight. 53) State greedy technique for solving problem. A greedy approach constructs a problem through a sequence of steps each expanding a partially constructed solution obtained so far, untill the complete solution is reached. On each step the choice must be made as Dept.of CSE, STJIT Ranibennur [61]

Design and Analysis of Algorithms Lab Feasible: i.e. it has to satisfy the problems constraints. Locally optimal: i.e. it has to be the best local choice among all feasible choices available on that step. Irrevocable: i.e. once made, it cannot be changed on subsequent steps of the algorithm. 54) What is the purose of Floyds algoreithm? - To find the all pair shortest path. 55) What is the time efficiency of floyds algorithm? - It is same as warshalls algorithm that is (n3). 56) For what purpose we use Warshalls algorithm? Warshalls algorithm for computing the transitive closure of a directed graph 57) Warshalls algorithm depends on which property? Transitive property 58) What is the time complexity of Warshalls algorithm?
3

Dept.of CSE, STJIT Ranibennur

[62]

You might also like