Escolar Documentos
Profissional Documentos
Cultura Documentos
http://sites.google.com/site/ncetians
List of Experiments: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. Recursive Binary & Linear Search. Heap Sort. a. Merge Sort b. DFS ( Connected or not ). Selection Sort. a. Topological Ordering b. Insertion Sort. 0 / 1 Knapsack problem. Dijkstras Algorithm. Quick Sort. Kruskals Algorithm. a. BFS b. Floyds Algorithm Subset problem. a. Horspool String matching Algorithm. b. Binomial Co Efficient. Prims Algorithm. a. DFS b. Warshalls Algorithm N Queens Algorithm
Page no. 1 6 10 14 19 23 28 31 35 40 42 48 53 56 61 65 68 71 77 80
http://sites.google.com/site/ncetians
1.
if(begin<=end) the go to Step 2 else go to Step mid = (begin+end)/2 if(key element = a[mid]) then successful search else go to step 4 /* search the upper half of the array */ If(k<a[mid]) then recursively call binary(begin, mid-1) /* search the lower half of the array */ if(k>a[mid]) then recursively call binary (mid+1,end)
LINEAR SERACH
Step 1: Step 2: Step 3: Step 4: Step 5: input an array with n number of elements input the key element if( key element = a[1] ) then successful search exit. else go to Step 5 Recursively call the same algorithm for the rest n-1 elements.
http://sites.google.com/site/ncetians
http://sites.google.com/site/ncetians
==========Input - Output=============
Enter size of the array n : 5 Enter elements of array in ascending order : 1 2 3 4 5 Enter the key element : 2 Successful search , key element is present
==========Input - Output=============
Enter size of the array n : 5 Enter elements of array in ascending order : 1 2 3 4 5 Enter the key element : 6 Unsuccessful search
http://sites.google.com/site/ncetians
http://sites.google.com/site/ncetians
==========Input - Output=============
Enter size of the array n : 5 Enter elements of array in ascending order : 1 2 3 4 5 Enter the key element : 2 Key 2 found in position 2
==========Input - Output=============
Enter size of the array n : 5 Enter elements of array in ascending order : 1 2 3 4 5 Enter the key element : 6 Key not found
http://sites.google.com/site/ncetians
2.
ALGORITHM
/* Constructs a heap from the elements of a given array */ /* Input : An array H[1..n] of orderable items /* Output : A heap H[1..n] Step 1: for i = n/2 downto 1 do Step 2 Step 2: k = i ; v = H[k] and heap = false Step 3: while not heap and 2 * k <= n do Step 4: j=2*k Step 5: if j < n // there are two children Step 6: if H[j] < H[j+1] j = j + 1 Step 7: if v >= H[j] heap = true Step 8: else go to Step 9 Step 9: H[k] = H[j] ; k = j Step 10: H[k] = v
http://sites.google.com/site/ncetians
PROGRAM
#include<stdio.h> #include<conio.h> #define max 100 void heapify () ; void heapsort () ; int maxdel (); int a[max] , b[max] ,n ;
void main () { int i ; int m ; clrscr () ; printf ( " \n Enter array size : " ) ; scanf ( "%d" , &n ) ; m=n; printf ( " \n Enter elements : \n " ) ; for ( i = 1 ; i <= n ; i++ ) scanf ( "%d" , &a[i] ) ; heapsort () ; printf ( " \n The sorted array is : \n " ) ; for ( i = 1 ; i <= m ; i++ ) printf ( "\n%d" , b[i] ) ; getch () ; } void heapsort () { int i ; heapify () ; for ( i = n ; i >= 1 ; i-- ) b[i] = maxdel () ; } void heapify () Department of CSE / ISE Algorithms 8 Analysis and Design of
http://sites.google.com/site/ncetians
int i , e , j ; // start from middle of a and move up to 1 for ( i = n/2 ; i >= 1 ; i-- ) { e = a[i] ; //save root of subtree j = 2 * i ; //left child and c+1 is right child
while ( j <= n ) { if ( j < n && a[j] < a[j+1] ) j++ ; //pick larger of children if ( e >= a[j] ) break; // is a max heap a[j/2] = a[j] ; j=j*2; //go to the next level } a[j/2] = e ; } } int maxdel () { int x , j , e , i ; if ( n == 0 ) return -1 ; x = a[1] ; //save the maximum element e = a[n] ; //get the last element n-- ; // Heap the structure again i=1; j = 2; while ( j <= n ) { if ( j < n && a[j] < a[j+1] ) j++ ; //Pick larger of two childrean if ( e >= a[j] ) break ; //subtree is heap a[i] = a[j] ; i=j; j=j*2; // go to the next level } a[i] = e ; return x ; } Department of CSE / ISE Algorithms 9 Analysis and Design of
http://sites.google.com/site/ncetians
=============Input - Output============
Enter array size : 5 Enter elements : 7 1 9 3 5 The sorted array is : 1 3 5 7 9
10
http://sites.google.com/site/ncetians
3.
a.
ALGORITHM
Mergesort ( A [ 0..n-1 ] )
// Sorts array A [ 0 .n-1} by recursive mergesort //Input: An array A [ 0..n-1 ] of orderable elements //Output: Array A [ 0.n-1 ] Sorted in nondecreasing order Step 1: If n > 1 then go thru the following steps Step 2: copy A [ 0[n/2] 1 ] to B [ 0[n/2] 1 ] to Step 3: copy A [ [n/2] n - 1 ] to B [ 0[n/2] 1 ] to Step 4: Mergesort(B [ 0[n/2] 1 ] ) Step 5: Mergesort(C [ 0[n/2] 1 ] ) Step 6: Merge ( B, C, A )
Merge ( B [ 0..p-1 ], C [ 0.q-1 ], A [ 0.p+q-1] ) //Merges two sorted arrays into one sorted array
//Input: Arrays B [ 0.p-1 ] and C [ 0.q-1 ] both sorted //Output: Sorted array A [ 0p+q-1 ] of the elements of B and C Step 1: i=0 Step 2: j=0 Step 3: k=0 Step 4: while i < p and j < q do { Step 5: if B[i] <= C[j] { Step 6: A[k] = B[i] Step 7: i=i+1 } /* end if */ Step 8: else { Step 9: A[k] = C[j] Step 10: j=j+1 Department of CSE / ISE 11 Analysis and Design of Algorithms
Check out more Downloads @ Step 11: Step 12: Step 13:
http://sites.google.com/site/ncetians
} /* end if */ k=k+1 /* end while */ if i = p then copy C [ j..q-1 ] to A [ k..p+q-1 ] else copy B [ i.p-1 ] to A [ kp+q-1 ]
PROGRAM
# include <stdio.h> # include <conio.h>
void Merge(int a[], int low, int mid, int high) { int i, j, k, b[20]; i=low; j=mid+1; k=low; while ( i<=mid && j<=high ) { if( a[i] <= a[j] ) b[k++] = a[i++] ; else b[k++] = a[j++] ; } while (i<=mid) b[k++] = a[i++] ; while (j<=high) b[k++] = a[j++] ; for(k=low; k<=high; k++) a[k] = b[k]; } void MergeSort(int a[], int low, int high) { int mid; if(low >= high) return; mid = (low+high)/2 ; MergeSort(a, low, mid); MergeSort(a, mid+1, high); Merge(a, low, mid, high); } Department of CSE / ISE Algorithms 12 Analysis and Design of
http://sites.google.com/site/ncetians
void main() { int n, a[20]; int k; clrscr(); printf("\n Enter How many Numbers : "); scanf("%d", &n); printf("\n Enter %d Numbers : \n ", n); for(k=1; k<=n; k++) scanf("%d", &a[k]);
MergeSort(a, 1, n); printf("\n Sorted Numbers are : \n "); for(k=1; k<=n; k++) printf("%5d", a[k]); getch(); }
13
http://sites.google.com/site/ncetians
================Input Output===============
Enter how many numbers : Enter 5 numbers : 99 67 85 12 97 Sorted numbers are : 12 67 85 97 99 5
14
http://sites.google.com/site/ncetians
3.
b.
ALGORITHM DFS ( G )
//Input: Graph G = < V , E > //Output: Graph G, whether it is connected or not Step 1:mark each vertex in V with 0 as a mark of being unvisited Step 2:count = 0 Step 3:for each vertex v in V do Step 4:if v is marked with 0 then DFS ( v ) //end for DFS ( v ) //visits recursively all the unvisited vertices connected to vertex v and //assigns them the numbers in that order they are encountered via global //variable count Step 5:count = count + 1 Step 6:mark v with count Step 7:for each vertex w in V adjacent to v do Step 8:if w is marked with 0 then DFS ( w ) //end for
15
http://sites.google.com/site/ncetians
PROGRAM
# include <stdio.h> # include <conio.h> # define INFINITY 999 # define TRUE 1 # define FALSE 0 int s[80], top=-1; int StackEmpty() { return( top==-1 ); } void Push(int x) { top=top+1; s[top]=x ; } int Pop() { int x = s[top] ; top=top-1; return(x); } Department of CSE / ISE Algorithms 16 Analysis and Design of
http://sites.google.com/site/ncetians
void InitGraph(int g[20][20], int n) { int i,j; for(i=1; i<=n; i++) for(j=1; j<=n; j++) g[i][j] = INFINITY; } void ReadGraph(int g[20][20]) { int i, j, wt; char ch; do {
} }
printf("\n Input Edge <v1, v2, Wt> : "); scanf("%d%d%d", &i, &j, &wt); g[i][j] = wt; printf(" One More Edge ? (y/n) : "); ch=getche(); while(ch=='y');
void PrintGraph(int g[20][20], int n) { int i,j; for(i=1; i<=n; i++) for(j=1; j<=n; j++) if( g[i][j] != INFINITY ) printf("\n %d <----> %d : %d", i, j, g[i][j]); } int Explore(int g[20][20], int n, int visited[]) { int j; int i = Pop(); for(j=n; j>=1; j--) if( g[i][j] != INFINITY && visited[j]==FALSE ) { Push(j); visited[j]=TRUE; } return(i); } Department of CSE / ISE Algorithms 17 Analysis and Design of
http://sites.google.com/site/ncetians
void DFS(int g[20][20], int n, int sv) { int i,v, visited[20], flag=FALSE; for(i=1; i<=n; i++) visited[i] = FALSE ; visited[sv]=TRUE; Push(sv); v = Explore(g,n,visited); printf("\n\n Nodes Reachable from Node %d", sv); while( StackEmpty()==FALSE ) { v = Explore(g, n, visited); printf("\n Node %d", v); flag=TRUE; }
if(flag==FALSE) printf("\n None"); } void main() { int n, g[20][20]; int sv; clrscr(); printf("\n Enter How many nodes : "); scanf("%d", &n); InitGraph(g,n); ReadGraph(g); printf("\n Eneter the Starting Vertex : "); scanf("%d", &sv); printf("\n The Given Directed Graph is \n"); PrintGraph(g,n); DFS(g, n, sv); getch(); }
18
http://sites.google.com/site/ncetians
============Input Output==========
Enter number of vertices : 4 Enter adjacent vertex and weight for You want to continue ( y/n ) ? y Enter adjacent vertex and weight for You want to continue ( y/n ) ? y Enter adjacent vertex and weight for You want to continue ( y/n ) ? y Enter adjacent vertex and weight for You want to continue ( y/n ) ? y Enter adjacent vertex and weight for You want to continue ( y/n ) ? y Enter adjacent vertex and weight for You want to continue ( y/n ) ? y Enter adjacent vertex and weight for You want to continue ( y/n ) ? n Adjacency List Output < 1 ,2 > < 2 ,1 > < 2 ,3 > < 2 ,4 > < 3 ,2 > <3,4> 1 1 1 1 1 1 19 : 1 2 : : : : : : : 1 2 2 3 3 4 4 : : : : : : : 2 3 4 2 4 2 3 1 1 1 1 1 1 1
http://sites.google.com/site/ncetians
============Input Output==========
Enter number of vertices : 4 Enter adjacent vertex and weight for You want to continue ( y/n ) ? y Enter adjacent vertex and weight for You want to continue ( y/n ) ? y Enter adjacent vertex and weight for You want to continue ( y/n ) ? y Enter adjacent vertex and weight for You want to continue ( y/n ) ? y Enter adjacent vertex and weight for You want to continue ( y/n ) ? n : : : : : 1 1 2 3 4 : : : : : 2 3 1 1 0 1 1 1 1 0
Adjacency List Output < 1 ,2 > < 1 ,3 > < 2 ,1 > < 3 ,1 > 1 1 1 1
: 1 2
Not Connected
20
http://sites.google.com/site/ncetians
4.
ALGORITHM
Selection sort ( A [ 0n-1 ] ) //The algorithm sorts a given array by selection sort
//Input: An array A [ 0n-1 ] of orderable elements //Output: Array A [ 0.n-1 ] sorted in ascending order Step 1: for i = 0 to n 2 do Step 2: min = i Step 3: for j =i + 1 to n 1 do Step 4: if a[j] < a[min] then go to Step 5 Step 5: min = j //end for Step 6: swap A[i] and A[min] //end for
21
http://sites.google.com/site/ncetians
PROGRAM
#include<stdio.h> #include<conio.h> int a[20] , n ;
void main () { void selectionsort() ; int i ; clrscr () ; printf ( " \n Enter size of the array : " ) ; scanf ( "%d" , &n ) ; printf ( " \n Enter the elements : \n " ) ; for ( i = 0 ; i < n ; i++ ) scanf ( "%d" , &a[i] ) ; selectionsort () ; printf ( " \n The sorted elements are : " ) ; for ( i = 0 ; i < n ; i++ ) printf ( "\n%d" , a[i] ) ; getch () ; Department of CSE / ISE Algorithms 22 Analysis and Design of
http://sites.google.com/site/ncetians
void selectionsort () { int i , j , min , temp ; for ( i = 0 ; i < n - 1 ; i++ ) { min = i ; for ( j = i + 1 ; j < n ; j++ ) { if ( a[j] < a[min] ) min = j ; } temp = a[i] ; a[i] = a[min] ; a[min] = temp ; } }
==============Input - Output=============
Enter size of the array : 5 Enter the elements : 7 1 9 3 5 The sorted elements are : 1 3 5 7 9
23
http://sites.google.com/site/ncetians
5.
a.
PROGRAM
# include <stdio.h> # include <conio.h> # define INFINITY 999 # define TRUE 1 # define FALSE 0 int s[80], top=-1; int StackEmpty() { return( top==-1 ); } Department of CSE / ISE Algorithms
24
Check out more Downloads @ void Push(int x) { top=top+1; s[top]=x ; } int Pop() { int x = s[top] ; top=top-1; return(x); }
http://sites.google.com/site/ncetians
void InitGraph(int g[20][20], int n) { int i,j; for(i=1; i<=n; i++) for(j=1; j<=n; j++) g[i][j] = INFINITY; }
void ReadGraph(int g[20][20]) { int i, j, wt; char ch; do { printf("\n Input Edge <v1, v2, Wt> : "); scanf("%d%d%d", &i, &j, &wt); // g[i][j] = g[j][i] = wt ; g[i][j] = wt; printf(" One More Edge ? (y/n) : "); ch=getche(); }while(ch=='y'); } void PrintGraph(int g[20][20], int n) { int i,j; for(i=1; i<=n; i++) for(j=1; j<=n; j++) if( g[i][j] != INFINITY ) Department of CSE / ISE 25 Algorithms
http://sites.google.com/site/ncetians
int InDeg(int g[20][20], int n, int v) { int deg=0, u; for(u=1; u<=n; u++) if( g[u][v] != INFINITY ) deg++; return(deg); } int Explore(int g[20][20], int n, int visited[], int degree[]) { int j; int i = Pop(); for(j=1; j<=n; j++) if( g[i][j] != INFINITY && visited[j]==FALSE ) degree[j] = degree[j] - 1;
for(j=1; j<=n; j++) if( degree[j]==0 && visited[j]==FALSE) { Push(j); visited[j]=TRUE; } return(i); } void TopoOrder(int g[20][20], int n) { int i,k,v, visited[20], degree[20], flag; for(i=1; i<=n; i++) { visited[i] = FALSE ; degree[i] = InDeg(g,n,i); } Department of CSE / ISE Algorithms 26 Analysis and Design of
http://sites.google.com/site/ncetians
for(i=1; i<=n; i++) if( degree[i] == 0 && visited[i]==FALSE ) { Push(i); visited[i]=TRUE; } printf("\n\n Nodes in Topological Order"); while( StackEmpty()==FALSE ) { v = Explore(g, n, visited, degree); printf("\n Node %d", v); } flag=TRUE; for(k=1; k<=n; k++) if (visited[k] == FALSE) flag=FALSE; if(flag==TRUE) printf("\n Topological Order Found"); else printf("\n No Topological Order Found"); }
void main() { int n, g[20][20]; clrscr(); printf("\n Enter How many nodes : "); scanf("%d", &n); InitGraph(g,n); ReadGraph(g); printf("\n The Given Directed Graph is \n"); PrintGraph(g,n); TopoOrder(g, n); getch(); } Department of CSE / ISE Algorithms 27 Analysis and Design of
http://sites.google.com/site/ncetians
============Input Output============
Enter 100 for diagonal elements and no edges Enter the no of vertices : 3 Enter the Adjacency matrix: 100 1 100 100 100 100 1 1 100 1 :
============Input Output============
Enter 100 for diagonal elements and no edges Enter the no of vertices : 2 Department of CSE / ISE Algorithms 28 :
http://sites.google.com/site/ncetians
5.
b.
ALGORITHM
Check out more Downloads @ Step 7: } //end while A[j+1] = v } //end for
http://sites.google.com/site/ncetians
PROGRAM
#include<stdio.h> #include<conio.h> int a[20] , n ;
void main () { void insertionsort() ; int i ; clrscr () ; printf ( " \n Enter size of the array : " ) ; scanf ( "%d" , &n ) ; Department of CSE / ISE Algorithms 30 Analysis and Design of
http://sites.google.com/site/ncetians
printf ( " \n Enter the elements : \n " ) ; for ( i = 0 ; i < n ; i++ ) scanf ( "%d" , &a[i] ) ; insertionsort () ; printf ( " \n The sorted elements are : " ) ; for ( i = 0 ; i < n ; i++ ) printf ( "\n%d" , a[i] ) ; getch () ; } void insertionsort () { int i , j , min ; for ( i = 0 ; i < n ; i++ ) { min = a[i] ; j=i-1; while ( j >= 0 && a[j] > min ) { a[j + 1] = a[j] ; j=j-1; } a[j + 1] = min ; } }
=============Input - Output=============
Enter size of the array : 5 Enter the elements : 9 2 8 5 1 The sorted elements are : 1 Department of CSE / ISE Algorithms 31 Analysis and Design of
http://sites.google.com/site/ncetians
6. Implement 0 / 1 Knapsack problem using dynamic programming. ALGORITHM Knapsack ( i, j ) //Input: A nonnegative integer i indicating the number of the first //items being considered and a nonnegative integer j indicating the
//Knapsacks capacity. Department of CSE / ISE Algorithms 32 Analysis and Design of
http://sites.google.com/site/ncetians
//Output: The value of an optimal feasible subset of the first I items. //Note: Uses as global variables input arrays Weights [ 1..n },
//Values [ 1 n ] and table V [ 0n, 0W ] whose entries are //initialized with 1s except for row 0 and column 0 initialized with //0s. Step 1: if V [i, j ] < 0 { Step 2: if j < Weights[i] then value = Knapsack ( i-1, j ) Step 3: else { Step 4: value = max ( Knapsack ( i-1, j ) Step 5: Values[I] + Knapsack ( i1, j-Weights[i] ) ) } //end else Step 6: V[i j] = value } //end if Step 7: return V [ i, j ]
PROGRAM
# include <stdio.h> # include <conio.h> int m; int n; float w[30]; float p[30]; float x[30]; float totprof ; Department of CSE / ISE Algorithms
33
http://sites.google.com/site/ncetians
float DKnapSack(int k, int m) { float res, res1, res2; if(k==n) res = (w[k] <= m) ? p[k] : 0 ; else if(w[k] > m) res = DKnapSack(k+1, m); else { res1 = p[k] + DKnapSack(k+1, m-w[k]); res2 = DKnapSack(k+1, m); res = (res1 > res2) ? res1 : res2 ; } return(res); } void main() { int k; float p1,p2, wt; clrscr(); printf("\n Enter the Knapsack Capacity : "); scanf("%d", &m); printf("\n Enter the number of Objects : "); scanf("%d", &n); for(k=1; k<=n; k++) { printf("\n Enter the Weight & Profit for Object %d : ", k); scanf("%f%f", &w[k], &p[k]); }
totprof = DKnapSack(1, m); wt=0; for(k=1; k<=n-1; k++) { p1=DKnapSack(k, m-wt); p2=DKnapSack(k+1, m-wt); if(p1==p2) x[k] = 0; else { x[k] = 1; wt=wt+w[k]; } Department of CSE / ISE 34 Analysis and Design of Algorithms
http://sites.google.com/site/ncetians
} p1=DKnapSack(n, m-wt); x[n] = (p1==0) ? 0 : 1 ; printf("\n Maximum Profit : %f", totprof); printf("\n Solution Vector : \n"); for(k=1; k<=n; k++) printf("%6.2f",x[k]); getch(); }
===========Input Output=========
Enter the number of objects Enter the weights : 1 2 2 Enter the profits : 18 16 6 Enter the Knapsack capacity: Department of CSE / ISE Algorithms 35 : 3
http://sites.google.com/site/ncetians
Enter the number of objects Enter the weights : 2 1 3 2 Enter the profits : 12 10 20 15 Enter the Knapsack capacity: Optimal solution = 37
7. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstras algorithm. ALGORITHM Dijkstra( G , s )
Department of CSE / ISE Algorithms 36 Analysis and Design of
http://sites.google.com/site/ncetians
//Input: A weighted connected graph G=< V , E > and its vertex v in V //Output: The length dv of a shortest path from s to v and its //penultimate vertex pv for every vertex v in V. Step 1:Initialize ( Q ) //initialize vertex priority in the priority queue. Step 2: for every vertex v in V do { Step 3: dv = infinity Step 4: pv = NULL Step 5: Insert(Q, v , dv )//initialize vertex priority in the priority queue } //end for Step 6: ds = 0 Step 7: Decrease ( Q , s , ds ) //update priority of s with ds Step 8: Vt = 0 Step 9: for I = 0 to | V | - 1 do { Step 10:u* = DeleteMin ( Q ) //delete the minimun priority element Step 11:vt = vt U { u* } Step 12:for every vertex u in V Vt that is adjacent to u* do { Step 13:if (du* + w ( u*, u ) < du ) { Step 14:du = du* + w ( u*, u ) Step 15:pu = u* Step 16:Decrease ( Q , u , du ) } // end if } // end for } // end for
PROGRAM
# include <stdio.h> # include <conio.h>
# define INFINITY 9999 # define TRUE 1 Department of CSE / ISE Algorithms 37 Analysis and Design of
http://sites.google.com/site/ncetians
void InitGraph(int g[20][20], int n) { int i,j; for(i=1; i<=n; i++) for(j=1; j<=n; j++) g[i][j] = INFINITY; } void ReadGraph(int g[20][20]) { int i, j, wt; char ch; do { printf("\n Input Directed Edge <v1, v2, Wt> : "); scanf("%d%d%d", &i, &j, &wt); g[i][j] = wt; //g[i][j] = g[j][i] = wt ; printf(" One More Edge ? (y/n) : "); ch=getche(); }while(ch=='y'); } void PrintGraph(int a[20][20], int n) { int i,j; for(i=1; i<=n; i++) { for(j=1; j<=n; j++) printf("%8d", a[i][j]); printf("\n\n"); } }
int MIN(int a, int b) { return( (a<b)?a:b ); } int MinNode(int dist[], int n, int selected[]) { Department of CSE / ISE 38 Analysis and Design of Algorithms
http://sites.google.com/site/ncetians
int k, min=INFINITY, index=0; for(k=1; k<=n; k++) if( dist[k]<min && selected[k]==FALSE) { min = dist[k]; index=k; } return(index); } void svspaths(int g[20][20], int n, int sv, int dist[]) { int selected[20], k,u,w; for(k=1; k<=n; k++) { selected[k] = FALSE; dist[k] = g[sv][k]; } selected[sv]=TRUE; dist[sv]=0; for(k=1; k<=n-1; k++) { u = MinNode(dist, n, selected); selected[u] = TRUE; for(w=1; w<=n; w++) if( selected[w]==FALSE ) dist[w] = MIN( dist[w], dist[u]+g[u][w] ); } } void main() { int n, g[20][20], sv, dist[20]; int k; clrscr(); printf("\n Enter How many nodes : "); scanf("%d", &n); InitGraph(g,n); ReadGraph(g);
printf("\n Enter the Starting Vertex : "); scanf("%d", &sv); svspaths(g, n, sv, dist); printf("\n\n The Given Graph in Matrix Format : \n\n"); PrintGraph(g,n); getch(); Department of CSE / ISE 39 Analysis and Design of Algorithms
http://sites.google.com/site/ncetians
printf("\n Single Vertex Shortest Paths : \n"); for(k=1; k<=n; k++) printf("\n From Node-%d to Node-%d : %d", sv, k, dist[k] ); getch(); }
===========Input Output=============
Enter the no of vertices : Enter the Adjacency matrix Department of CSE / ISE Algorithms 40 5 : Analysis and Design of
http://sites.google.com/site/ncetians
7 2 5 0 4 : 100 100 6 4 0 1 1 2 3
41
http://sites.google.com/site/ncetians
:
ALGORITHM
Quicksort ( A [lr] ) //Sorts a subarray by quicksort //Input: A subarray A[lr] of A[0.n-1], defined by its left and right //indices l and r
//Output: The subarray A[lr] sorted in increasing order Step 1: if l < r then { Step 2: s = partition( A[lr] ) //s is a split position Step 3: Quicksort ( A [ ls-1 ] ) Step 4: Quicksort ( A [ s+1r ] )
Partition ( A [ lr ] )
//Partitions a sub array by using its first element as a pivot //Input: A sub array A[l..r] of A[0n-1], defined by its left and right //indices l and r ( l < r ). //Output: A partition of A[lr], with the split position returned as this //functions value. Step 1: p = a[l] Step 2: i=l Step 3: j=r+1 Step 4: repeat Step 5: repeat i = i + 1 until A[i] >= p Step 6: repeat j = j 1 until A[j] <= p Step 7: swap ( A[i] , A[j] ) Step 8: until i >= j Step 9: swap ( A[i] , A[j] ) //undo last swap when i >= j Step 10: swap ( A[l], A[j] ) Step 11: return j
PROGRAM
Department of CSE / ISE Algorithms
:
42 Analysis and Design of
http://sites.google.com/site/ncetians
void Exch(int *p, int *q) { int temp = *p; *p = *q; *q = temp; } void QuickSort(int a[], int low, int high) { int i, j, key, k; if(low>=high) return; key=low; i=low+1; j=high; while(i<=j) { while ( a[i] <= a[key] ) i=i+1; while ( a[j] > a[key] ) j=j-1; if(i<j) Exch(&a[i], &a[j]); } Exch(&a[j], &a[key]); QuickSort(a, low, j-1); QuickSort(a, j+1, high); } void main() { int n, a[20]; int k; clrscr(); printf("\n Enter How many Numbers : "); scanf("%d", &n); printf("\n Enter %d Numbers : \n ", n); for(k=1; k<=n; k++) scanf("%d", &a[k]); QuickSort(a, 1, n); printf("\n Sorted Numbers are : \n "); for(k=1; k<=n; k++) printf("%5d", a[k]); getch(); }
43
http://sites.google.com/site/ncetians
===============Input Output=============
Enter array size : Enter the array : 4 2 1 9 8 : 5 6 7 8 9 10 3 5 7 10 6 10
44
http://sites.google.com/site/ncetians
9. Find Minimum Cost Spanning tree of a given undirected graph using Kruskals algorithm. ALGORITHM Kruskal ( G )
//Input: A weighted connected graph G = < V , E > //Output: Et, the set of edges composing a minimum spanning tree //of G. Step 1:Sort E in increasing order of the edge weights w(ei1) <=..<= w(ei|E| ) Step 2:Et = NULL ; ecounter = 0 //initialize the set of tree edges //and itz size Step 3:k = 0 //initialize the number of processed edges Step 4: While ecounter < | V | - 1 { Step 5:k = k + 1 Step 6:if Et U { eik } is acyclic then { Step 7:Et = Et U { eik } Step 8:ecounter = ecounter + 1 } // end if } // end while Step 9:return Et
45
http://sites.google.com/site/ncetians
PROGRAM
#include<conio.h> #include<stdio.h> struct tag { int v1 , v2 , wt ; }; typedef struct tag edge ; void readgraph(edge e[] , int n ) { int k ; for ( k = 1 ; k <= n ; k++ ) { printf ( " \n input edge < v1 , v2 , wt > : \n " ) ; scanf ( "%d%d%d" , &e[k].v1 , &e[k].v2 , &e[k].wt ) ; } } void printgraph(edge e[] , int n ) { int k ; for ( k = 1 ; k <= n ; k++ ) printf ( " \n %d <......> %d : e[k].v2 , e[k].wt ) ; } int find ( int p[] , int k ) { if ( p[k] == k ) return k ; else return ( find ( p , p[k] ) ) ; } void bsort ( edge e[] , int n ) { int i , j ; edge temp ; for ( i = 1 ; i <= n - 1 ; i++ ) for ( j = 1 ; j <= n - 1 ; j++ ) if ( e[j].wt > e[j+1].wt ) Department of CSE / ISE Algorithms 46 Analysis and Design of
%d \n" , e[k].v1 ,
http://sites.google.com/site/ncetians
{
temp = e[j] ; e[j] = e[j+1] ; e[j+1] = temp ; } } int min ( int x , int y ) { return ( ( x < y ) ? x : y ) ; } int max ( int x , int y ) { return ( ( x > y ) ? x : y ) ; } int kruskal ( edge e1[] , int n1 , edge e2[] , int n2 ) { int mincost = 0 , parent[30] ; int i , j , k , p1 , p2 , mn , mx ; int v1 , v2 , wt , n ; for ( k = 1 ; k <= n2 + 1 ; k++ ) parent[k] = k ; bsort ( e1 , n1 ) ; for ( i = 1 , j = 1 ; ( i <= n1 ) && ( j <= n2 ) ; i++ , j++ ) { v1 = e1[i].v1 ; v2 = e1[i].v2 ; wt = e1[i].wt ; p1 = find ( parent , v1 ) ; p2 = find ( parent , v2 ) ; if ( p1 == p2 ) j=j-1; else { e2[j] = e1[i] ; mn = min ( p1 , p2 ) ; mx = max ( p1 , p2 ) ; parent[mx] = mn ; mincost = mincost + wt ; } } return ( mincost ) ; } Department of CSE / ISE Algorithms 47 Analysis and Design of
http://sites.google.com/site/ncetians
void main () { edge e1[30] , e2[30] ; int n1 , n2 , n , cost ; clrscr () ; printf ( " \n Enter how many nodes : \n " ) ; scanf ( "%d" , &n ) ; n2 = n - 1 ; printf ( " \n Enter how many edges of the graph : \n " ) ; scanf ( "%d" , &n1 ) ; readgraph ( e1 , n1 ) ; cost = kruskal ( e1 , n1 , e2 , n2 ) ; printf( " \n minimum cost = %d \n " , cost ) ; printf ( " \n the spanning tree is : \n " ) ; printgraph ( e2 , n2 ) ; getch () ; }
48
http://sites.google.com/site/ncetians
=============Input - Output============
input edge < v1 , v2 , wt > : 1 6 10 input edge < v1 , v2 , wt > : 3 4 12 input edge < v1 , v2 , wt > : 2 7 14 input edge < v1 , v2 , wt > : 2 3 16 input edge < v1 , v2 , wt > : 4 7 18 input edge < v1 , v2 , wt > : 4 5 24 input edge < v1 , v2 , wt > : 5 7 24 input edge < v1 , v2 , wt > : 5 6 25 input edge < v1 , v2 , wt > : 1 2 28 minimum cost = 99 the spanning tree is : 1 <......> 6 : 3 <......> 4 : 2 <......> 7 : 2 <......> 3 : Department of CSE / ISE Algorithms 10 12 14 16 49 Analysis and Design of 6 25 10 7
12
28 14
16
3 18 5 22 4
24
http://sites.google.com/site/ncetians
10.
a.
Print all the nodes reachable from a given starting node in a digraph using Breadth First Search method. :
ALGORITHM BFS ( G )
//Input: Graph G = < V , E > //Output: Graph G, with its vertices marked with consecutive integers in //the order they have been visited by the BFS traversal. Step 1:mark each vertex in V with 0 as a mark of being unvisited Step 2:count = 0 Step 3:for each vertex v in V do Step 4:if v is marked with 0 then BFS ( v ) //end for BFS ( v ) //visits recursively all the unvisited vertices connected to vertex v and //assigns them the numbers in that order they are visited via global //variable count Step 5:count = count + 1 Step 6:mark v with count and initialize a queue with v Step 7:While the queue is not empty do { Step 8:for each vertex w in V adjacent to the fronts vertex v do { Step 9:if w is marked with 0 then { Step 10:count = count + 1 Step 11:add w to the queue } // end if //end for Step 12:remove vertex v from the front of the queue } // end while
50
http://sites.google.com/site/ncetians
PROGRAM
# include <stdio.h> # include <conio.h> # define INFINITY 999 # define TRUE 1 # define FALSE 0 int q[80], front=-1, rear=-1; int QueueEmpty() { return( front==-1 && rear==-1 ); } void QInsert(int x) { rear = rear + 1; q[rear] = x ; if( front==-1) front=front+1; } int QDelete() { int x = q[front] ; if( front == rear ) front = rear = -1; else front = front + 1; return(x); } void InitGraph(int g[20][20], int n) { int i,j; for(i=1; i<=n; i++) Department of CSE / ISE Algorithms 51 Analysis and Design of
http://sites.google.com/site/ncetians
void ReadGraph(int g[20][20]) { int i, j, wt; char ch; do { printf("\n Input Edge <v1, v2, Wt> : "); scanf("%d%d%d", &i, &j, &wt); g[i][j] = wt; printf(" One More Edge ? (y/n) : "); ch=getche(); }while(ch=='y'); } void PrintGraph(int g[20][20], int n) { int i,j; for(i=1; i<=n; i++) for(j=1; j<=n; j++) if( g[i][j] != INFINITY ) printf("\n %d <----> %d : %d", i, j, g[i][j]); } int Explore(int g[20][20], int n, int visited[]) { int j; int i = QDelete(); for(j=1; j<=n; j++) if( g[i][j] != INFINITY && visited[j]==FALSE ) { QInsert(j); visited[j]=TRUE; } return(i); } void BFS(int g[20][20], int n, int sv) { Department of CSE / ISE 52 Algorithms
http://sites.google.com/site/ncetians
int i,v, visited[20], flag=FALSE; for(i=1; i<=n; i++) visited[i] = FALSE ; visited[sv]=TRUE; QInsert(sv); v = Explore(g,n,visited);
printf("\n Nodes Reachable from Node %d", sv); while( QueueEmpty()==FALSE ) { v = Explore(g, n, visited); printf("\n Node %d", v); flag=TRUE; } if(flag==FALSE) printf("\n None"); } void main() { int n, g[20][20]; int sv; clrscr(); printf("\n Enter How many nodes : "); scanf("%d", &n); InitGraph(g,n); ReadGraph(g); printf("\n Eneter the Starting Vertex : "); scanf("%d", &sv); printf("\n The Given Directed Graph is \n"); PrintGraph(g,n); BFS(g, n, sv); getch(); }
53
http://sites.google.com/site/ncetians
===============Input Output=============
Enter number of vertices : 4 Enter adjacent vertex and weight for You want to continue (y/n) ? y Enter adjacent vertex and weight for You want to continue (y/n) ? y Enter adjacent vertex and weight for You want to continue (y/n) ? y Enter adjacent vertex and weight for You want to continue (y/n) ? y Enter adjacent vertex and weight for You want to continue (y/n) ? y Enter adjacent vertex and weight for You want to continue (y/n) ? n Adjacency List Output <1,2> 0 <2,3> 0 <2,4> 0 <4,1> 0 <4,3> 0 : 1 2
: : : : : :
1 2 2 3 4 4
: : : : : :
2 3 4 0 1 3
0 0 0 0 0 0
Enter Starting vertex : 1 Vertices reachabale from: 1 are : 2 3 Department of CSE / ISE Algorithms 54
http://sites.google.com/site/ncetians
10.
b.
ALGORITHM
Floyd ( W [ 1n , 1.n ] )
//Input: The weight matrix W of a graph. //Output: The distance matrix of the shortest paths lengths. Step 1: D = W // is not necessary if W can be overwritten Step 2: For k = 1 to n do { Step 3: For i = 1 to n do { Step 4: For j = 1 to n do { Step 5: D [i , j ] = min { D [ i , j ] , D [ i , k ] + D [ k , j ] } } //end for } //end for } //end for Step 6: return D
55
http://sites.google.com/site/ncetians
PROGRAM
# include <stdio.h> # include <conio.h>
# define INFINITY 999 # define MIN(x,y) (((x)<(y))?(x):(y)) void InitGraph(int g[20][20], int n) { int i,j; for(i=1; i<=n; i++) for(j=1; j<=n; j++) g[i][j] = INFINITY; } void ReadGraph(int g[20][20]) { int i, j, wt; char ch; do { printf("\n Input Directed Edge <v1, v2, Wt> : "); scanf("%d%d%d", &i, &j, &wt); // g[i][j] = wt; g[i][j] = g[j][i] = wt ; printf(" One More Edge ? (y/n) : "); ch=getche(); }while(ch=='y'); } Department of CSE / ISE Algorithms 56 Analysis and Design of
http://sites.google.com/site/ncetians
void PrintGraph(int a[20][20], int n) { int i,j; for(i=1; i<=n; i++) { for(j=1; j<=n; j++) printf("%5d", a[i][j]); printf("\n\n"); } } void AllPairs(int g[20][20], int n, int p[20][20]) { int i,j,k;
for(i=1; i<=n; i++) for(j=1; j<=n; j++) if( i==j) p[i][j] = 0; else p[i][j] = g[i][j] ; 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]) ; } void main() { int n, g[20][20], p[20][20]; clrscr(); printf("\n Enter How many nodes : "); scanf("%d", &n); InitGraph(g,n); ReadGraph(g); AllPairs(g, n, p); printf("\n\n Shortest Path Matrix : \n\n"); PrintGraph(p,n); getch(); } Department of CSE / ISE Algorithms
57
http://sites.google.com/site/ncetians
============Input Output=============
Enter the no of vertices : Enter the Adjacency matrix: 0 2 100 6 100 0 7 100 3 100 0 100 100 100 1 0 3 The final Adjacency matrix is 0 2 7 6 10 0 7 16 3 5 0 9 4 6 1 0 : 3 1 6 4 4 2 1 7 2
58
http://sites.google.com/site/ncetians
11.
Find a subset 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 solutins { 1, 2, 6 } and { 1, 8 }. A suitable is to be displayed if the given problem instance doesnt have a solution. :
ALGORITHM
Backtrack ( X [ 1.i ] )
//Input: X [1.i] specifies first I promising components of a solution. //Output: All the tuples representing the problems solutions Step 1:If X [1..i ] is a solution write X [1i ] Step 2: else { Step 3:for each element x E S i+1 consistent with X [1..i ] and the constraints do { Step 4:X[ i + 1 ] = x Step 5:Backtrack ( X [ 1.i + 1 ] ) }//end for }//end else
59
http://sites.google.com/site/ncetians
PROGRAM
#include<stdio.h> #include<conio.h> #define max 10
int s[max] , x[max] ; int d ; void sumofsub ( int , int , int ) ; void main () { int n , sum = 0 ; int i ; clrscr () ; printf ( " \n enter the size of the set : " ) ; scanf ( "%d" , &n ) ; printf ( " \n Enter the set in increasing order : \n " ) ; for ( i = 1 ; i <= n ; i++ ) scanf ( "%d", &s[i] ) ; printf ( " \n enter the value of d : \n " ) ; scanf ( "%d" , &d ) ; for ( i = 1 ; i <= n ; i++ ) sum = sum + s[i] ; if ( sum < d || s[1] > d ) printf ( " \n no subset possible : " ) ; Department of CSE / ISE Algorithms 60 Analysis and Design of
http://sites.google.com/site/ncetians
sumofsub ( 0 , 1 , sum ) ; getch () ; } void sumofsub ( int m , int k , int r ) { int i ; x[k] = 1 ; if ( ( m + s[k] ) == d ) { for ( i = 1 ; i <= k ; i++ ) if ( x[i] == 1 ) printf ( " \t %d " , s[i] ) ; printf ( " \n " ) ; } else if ( m + s[k] + s[k+1] <= d )
sumofsub ( m + s[k] , k + 1 , r - s[k] ) ; if ( ( m + r - s[k] >= d ) && ( m + s[k+1] <=d ) ) { x[k] = 0; sumofsub ( m , k + 1 , r - s[k] ) ; } }
61
http://sites.google.com/site/ncetians
============Input - Output=============
enter the size of the set : 5 Enter the set in increasing order : 1 2 5 6 8 enter the value of d : 9 1 1 2 8 6
============Input - Output=============
enter the size of the set : 6 Enter the set in increasing order : Department of CSE / ISE Algorithms 62 Analysis and Design of
http://sites.google.com/site/ncetians
12.
ALGORITHM
ShiftTable ( P [ 0.m-1 ] )
//Fills the shift table used by Horspools and Boyer Moore algorithms. //Input: Pattern P [ 0m-1 ] and an alphabet of possible characters. //Output: Table [ 0size 1 ] indexed by the alphabets characters and filled with shift sizes computed by formula. Step 1: for j = 0 to m 2 do Table [ P [ j ] ] = m 1 j Step 2: Table.
Horspool Algorithm
Step 1: Step 2: Step 3:
For a given pattern of length m and the alphabet used in both the pattern and text, construct the shift table as described above. Align the pattern against the beginning of the text. Repeat the following until either a matching sub string is 63 Analysis and Design of
http://sites.google.com/site/ncetians
found or the pattern reaches beyond the last character of the text. Starting with the last character in the pattern, compare the corresponding characters in the pattern, compare the corresponding characters in the pattern and text until either all m characters are matched ( then stop ) or a mismatching pair is encountered. In the latter case, retrieve the entry t ( c ) from the cs column of the shift table where c is the texts character currently aligned against the last character of the pattern and shift the pattern by t ( c ) characters to the right along the text.
PROGRAM
#include<stdio.h> #include<conio.h> #include<string.h> #define max 256 int horspool ( char * , char * ) ; int t[max] ; void shifttable ( char [] ) ; void main () { char source[max] ; char pattern[max] ; int found ; clrscr () ; printf ( " \n Enter source string : " ) ; gets ( source ) ; printf ( " \n Enter pattern string : " ) ; gets ( pattern ) ; Department of CSE / ISE 64 Analysis and Design of Algorithms
http://sites.google.com/site/ncetians
found = horspool ( source , pattern ) ; if ( found == -1 ) printf ( " \n Pattern not found " ) ; else printf ( " \n pattern found at : %d \n " , found + 1 ) ; getch () ; } void shifttable ( char p[] ) { int m , index , i , j ; m = strlen ( p ) ; for ( i = 0 ; i < max ; i++ ) t[i] = m ; // initialize with all ASCII characters for ( j = 0 ; j < m - 1 ; j++ ) { //decimal value of pattern character index = ( p[j] - '0' ) ; t[index] = m - 1 - j ; } }
int horspool ( char s[] , char p[] ) { int i , n , m ; int index ; int k = 0 ; n = strlen ( s ) ; m = strlen ( p ) ; shifttable ( p ) ; i=m-1; while ( i < n ) { while ( ( k < m ) && ( p[m - 1 - k] == s [i - k ] ) ) k++ ; if ( k == m ) return ( i - m + 1 ) ; else { //convert to decimal value index = ( s[i] - '0' ) ; i = i + t[index] ; // get the shift value } Department of CSE / ISE 65 Analysis and Design of Algorithms
http://sites.google.com/site/ncetians
=============Input - Output============
Enter source string : bangalore Enter pattern string : gal pattern found at : 4
=============Input - Output============
Enter source string : BANGALORE Enter pattern string : BIT Pattern not found Department of CSE / ISE Algorithms 66 Analysis and Design of
http://sites.google.com/site/ncetians
12.
b.
ALGORITHM Binomial ( n , k )
//Input: A pair of non negative integers n >= k >= 0 //Output: The value of C ( n , k ) Step 1: For I = 0 to n do { Step 2: For j = 0 to min ( i , k ) do { Step 3: if j = 0 or j = k then C [ i , j ] = 1 Step 4: C[i,j]=C[i1,j1]+C[i1,j] } //end for } //end for Step 5: return C [ n , k ] Department of CSE / ISE Algorithms 67 Analysis and Design of
http://sites.google.com/site/ncetians
PROGRAM
#include<stdio.h> #include<conio.h> int bc ( int , int ) ;
void main () { int n , k ; clrscr () ; printf ( " \n enter the values of n & k : " ) ; scanf ( "%d%d" , &n , &k ); if ( n < k ) printf ( " \n invalid input " ) ; else printf ( " \n %dC%d = %d \n " , n , k , bc ( n , k ) ) ; Department of CSE / ISE Algorithms 68 Analysis and Design of
http://sites.google.com/site/ncetians
int bc ( int n , int k ) { int c[10][10] , i , j ; for ( i = 0 ; i <= n ; i++ ) { c[i][0] = 1 ; c[i][i] = 1 ; } for ( i = 2 ; i <= n ; i++ ) for ( j = 1 ; j <= i - 1 ; j++ ) c[i][j] = c[i-1][j-1] + c[i-1][j] ; return c[n][k] ; }
===============Input - Output============
enter the values of n & k : 5 3 5C3 = 10
===============Input - Output============
enter the values of n & k : 4 6 Department of CSE / ISE Algorithms 69 Analysis and Design of
http://sites.google.com/site/ncetians
13.
Find Minimum Cost Spanning Tree of a given undirected graph using Prims algorithm. :
ALGORITHM Prim ( G )
//Input: A weighted connected graph G = < V , E > //Output: Et , the set of edges composing a minimum spanning tree of G Step 1:Vt= { v0 } //the set of tree vertices can be initialized with any vertex Step 2: Et = NULL Step 3: for i = 1 | V | - 1 do { Department of CSE / ISE Algorithms 70 Analysis and Design of
http://sites.google.com/site/ncetians
Step 4: find a minimum weight edge e*=(v*,u*) among all the edges (v, u ) Step 5: such that v is in Vt and u is in V Vt Step 6: Vt = Vt U { u * } Step 7: Et = Et U { e* } } //end for Step 8: return Et.
PROGRAM
# include <stdio.h> # include <conio.h> # define INFINITY 999 # define TRUE 1 # define FALSE 0 void InitGraph(int g[20][20], int n) { int i,j; Department of CSE / ISE Algorithms 71 Analysis and Design of
Check out more Downloads @ for(i=1; i<=n; i++) for(j=1; j<=n; j++) g[i][j] = INFINITY; }
http://sites.google.com/site/ncetians
void ReadGraph(int g[20][20]) { int i, j, wt; char ch; do { printf("\n Input Edge <v1, v2, Wt> : "); scanf("%d%d%d", &i, &j, &wt); g[i][j] = g[j][i] = wt; printf(" One More Edge ? (y/n) : "); ch=getche(); }while(ch=='y'); } void PrintGraph(int g[20][20], int n) { int i,j; for(i=1; i<=n; i++) for(j=i+1; j<=n; j++) if( g[i][j] != INFINITY ) printf("\n %d <----> %d : %d", i, j, g[i][j]); } int PrimAlg(int g[20][20], int n, int t[20][20]) { int u,v, min, mincost; int included[20]; int i,j,k;
included[1] = TRUE ; for(k=2; k<=n; k++) included[k] = FALSE ; mincost = 0; for(k=1; k<=n-1; k++) { min = INFINITY; u=1; v=1; for(i=1; i<=n; i++) if(included[i]==TRUE) for(j=1; j<=n; j++) if( g[i][j] < min ) { min = g[i][j]; Department of CSE / ISE 72 Analysis and Design of Algorithms
http://sites.google.com/site/ncetians
} t[u][v] = t[v][u] = g[u][v] ; mincost = mincost + g[u][v] ; included[v] = TRUE; printf("\n <%d, %d> = %d", u, v, t[u][v]); for(i=1; i<=n; i++) for(j=1; j<=n; j++) if( included[i] && included[j] ) g[i][j] = g[j][i] = INFINITY; } return(mincost); } void main() { int n, g[20][20], t[20][20]; int cost; clrscr(); printf("\n Enter How many nodes : "); scanf("%d", &n); InitGraph(g,n); InitGraph(t,n); ReadGraph(g); printf("\n The order of Insertion of edges :\n"); cost = PrimAlg(g,n,t); printf("\n\n Minimum cost = %d\n", cost); printf("\n The Spanning Tree is \n"); PrintGraph(t,n); getch(); }
===========Input Output==========
Enter the number of vertices Enter the Adjacency matrix: 0 10 1 10 0 6 1 6 0 1 <1,3> <3,2> 73 Analysis and Design of Department of CSE / ISE Algorithms : 3 (100 for no edges) 10 1 6 2
http://sites.google.com/site/ncetians
3
14.
a.
Print all the nodes reachable from a given starting node in a given digraph using Depth First Search method. :
ALGORITHM DFS ( G )
Department of CSE / ISE Algorithms
74
http://sites.google.com/site/ncetians
//Input: Graph G = < V , E > //Output: Graph G, & printing all its nodes. Step 1:mark each vertex in V with 0 as a mark of being unvisited Step 2:count = 0 Step 3:for each vertex v in V do Step 4:if v is marked with 0 then DFS ( v ) //end for DFS ( v ) //visits recursively all the unvisited vertices connected to vertex v and //assigns them the numbers in that order they are encountered via global //variable count Step 5:count = count + 1 Step 6:mark v with count Step 7:for each vertex w in V adjacent to v do Step 8:if w is marked with 0 then DFS ( w ) //end for
PROGRAM
# include <stdio.h> # include <conio.h> # define INFINITY 999 # define TRUE 1 # define FALSE 0 Department of CSE / ISE Algorithms 75 Analysis and Design of
Check out more Downloads @ int s[80], top=-1; int StackEmpty() { return( top==-1 ); } void Push(int x) { top=top+1; s[top]=x ; } int Pop() { int x = s[top] ; top=top-1; return(x); }
http://sites.google.com/site/ncetians
void InitGraph(int g[20][20], int n) { int i,j; for(i=1; i<=n; i++) for(j=1; j<=n; j++) g[i][j] = INFINITY; } void ReadGraph(int g[20][20]) { int i, j, wt; char ch; do { printf("\n Input Edge <v1, v2, Wt> : "); scanf("%d%d%d", &i, &j, &wt);
g[i][j] = wt; printf(" One More Edge ? (y/n) : "); ch=getche(); }while(ch=='y'); } void PrintGraph(int g[20][20], int n) Department of CSE / ISE 76 Algorithms Analysis and Design of
http://sites.google.com/site/ncetians
int i,j; for(i=1; i<=n; i++) for(j=1; j<=n; j++) if( g[i][j] != INFINITY ) printf("\n %d <----> %d : %d", i, j, g[i][j]); } int Explore(int g[20][20], int n, int visited[]) { int j; int i = Pop(); for(j=n; j>=1; j--) if( g[i][j] != INFINITY && visited[j]==FALSE ) { Push(j); visited[j]=TRUE; } return(i); } void DFS(int g[20][20], int n, int sv) { int i,v, visited[20], flag=FALSE; for(i=1; i<=n; i++) visited[i] = FALSE ; visited[sv]=TRUE; Push(sv); v = Explore(g,n,visited); printf("\n\n Nodes Reachable from Node %d", sv); while( StackEmpty()==FALSE ) { v = Explore(g, n, visited); printf("\n Node %d", v); flag=TRUE; }
77
http://sites.google.com/site/ncetians
clrscr(); printf("\n Enter How many nodes : "); scanf("%d", &n); InitGraph(g,n); ReadGraph(g); printf("\n Eneter the Starting Vertex : "); scanf("%d", &sv); printf("\n The Given Directed Graph is \n"); PrintGraph(g,n); DFS(g, n, sv); getch(); }
===============Input Output=============
78
http://sites.google.com/site/ncetians
: : : : : : 1 1 2 3 3 4 : : : : : : 2 4 3 1 4 2 0 0 0 0 0 0
Enter number of vertices : 4 Enter adjacent vertex and weight for You want to continue (y/n) ? y Enter adjacent vertex and weight for You want to continue (y/n) ? y Enter adjacent vertex and weight for You want to continue (y/n) ? y Enter adjacent vertex and weight for You want to continue (y/n) ? y Enter adjacent vertex and weight for You want to continue (y/n) ? y Enter adjacent vertex and weight for You want to continue (y/n) ? n Adjacency List Output <1,2> 0 <1,4> 0 <2,3> 0 <3,1> 0 <3,4> 0 <4,2> 0 Enter Starting vertex : Vertices reachable from: 2 3 4 :
3 1 1 are :
14.
b.
Compute the transitive closure of a given directed graph using Warshalls algorithm.
79 Analysis and Design of
http://sites.google.com/site/ncetians
ALGORITHM
Warshall ( A [1.n , 1n ] )
//Input: The adjacency matrix A of a digraph with n vertices. //Output: The transitive closure of the digraph Step 1: R(0) = A Step 2: for k = 1 to n do { Step 3: for i = 1 to n do { Step 4: for j = 1 to n do { Step 5: R(k) [ i , j ] = R(k-1) [ I , j ] or R(k-1) [ I , k ] and R(k-1) [ k , j ] } // end for } // end for } // end for Step 6: return R(n)
PROGRAM
Department of CSE / ISE Algorithms
:
80 Analysis and Design of
http://sites.google.com/site/ncetians
# include <stdio.h> # include <conio.h> # define TRUE 1 # define FALSE 0 void PrintGraph(int a[20][20], int n) { int i,j; for(i=1; i<=n; i++) { for(j=1; j<=n; j++) printf("%3d", a[i][j]); printf("\n"); } } void ReadGraph(int a[20][20], int n) { int i,j; for(i=1; i<=n; i++) for(j=1; j<=n; j++) scanf("%d", &a[i][j]); } int WarshallAlg(int g[20][20], int n, int p[20][20]) { int i,j,k; for(i=1; i<=n; i++) for(j=i+1; j<=n; j++) p[i][j] = p[j][i] = ( g[i][j] || g[j][i] ) ? 1 : 0 ; for(k=1; k<=n; k++) for(i=1; i<=n; i++) for(j=1; j<=n; j++) p[i][j] = p[i][j] || p[i][k] && p[k][j] ; for(i=1; i<=n; i++) for(j=i+1; j<=n; j++) if( p[i][j]==FALSE && p[j][i]==FALSE ) return(FALSE) ; return(TRUE); }
81
http://sites.google.com/site/ncetians
void main() { int n, g[20][20], p[20][20]; int res; clrscr(); printf("\n Enter How many nodes : "); scanf("%d", &n); printf("\n Enter the graph in matrix forrmat : \n"); ReadGraph(g,n); res = WarshallAlg(g, n, p); printf("\n Path Matrix : \n"); PrintGraph(p,n); if(res==TRUE) printf("\n Strongly/Weakly Connected Graph"); else printf("\n Disconnected Graph"); getch(); }
82
http://sites.google.com/site/ncetians
==============Input Output==========
Enter the number of vertices Enter the Adjacency matrix 0 0 0 1 1 0 0 0 0 0 0 1 0 1 0 0 : : : 1 2 4
83
http://sites.google.com/site/ncetians
15.
ALGORITHM
Backtrack ( X [ 1.i ] )
//Input: X [1.i] specifies first I promising components of a solution. //Output: All the tuples representing the problems solutions Step 1:If X [1..i ] is a solution write X [1i ] Step 2: else { Step 3:for each element x E S i+1 consistent with X [1..i ] and the constraints do { Step 4:X[ i + 1 ] = x Step 5:Backtrack ( X [ 1.i + 1 ] ) }//end for }//end else
84
http://sites.google.com/site/ncetians
PROGRAM
# include <stdio.h> # include <conio.h> # include <math.h> # define TRUE 1 # define FALSE 0
void Display(int board[20][20], int n) { int i,j; printf("\n The Solution is : \n\n"); for(i=1; i<=n; i++) { for(j=1; j<=n; j++) printf("%6d", board[i][j]); printf("\n\n"); } } int IsPossible(int q[], int i, int j) { int k, row, col; for(k=1; k<i; k++) { row=k; col=q[k]; if( row==i || col==j ) return(FALSE); if( abs(row-i) == abs(col-j) ) return(FALSE); } return(TRUE); } void NQueens(int board[20][20], int n) { int i,j, q[20]; for(i=1; i<=n; i++) for(j=1; j<=n; j++) board[i][j]=0; for(i=1; i<=n; i++) q[i]=0; for(i=1; i<=n; i++) { Department of CSE / ISE Algorithms 85 Analysis and Design of
http://sites.google.com/site/ncetians
for(j=q[i]+1, board[i][j-1]=0, q[i]=0; j<=n; j++) { if( IsPossible(q, i,j) == TRUE) { q[i] = j; board[i][j] = i; break; } } if( q[i]==0 ) i=i-2; } } void main() { int board[20][20], n; clrscr(); printf("\n Enter the Number of Queens(Power of 2) : "); scanf("%d", &n); NQueens(board, n); Display(board, n); getch(); }
86
http://sites.google.com/site/ncetians
==========Input Output=========
Enter the no. of Queens : 4 4
==========Input Output=========
Enter the no. of Queens : 8 8 X X X X X Q X X X X X X Q X X X X X Q X X X X X X X Q X X X X
87
http://sites.google.com/site/ncetians
88