ada lab manual

114
Check out more Downloads @ http://sites.google.com/site/ncetians ALGORITHMS LAB MANUAL List of Experiments: Page no. 1. Recursive Binary & Linear Search. 1 2. Heap Sort. 6 3. a. Merge Sort 10 b. DFS ( Connected or not ). 14 4. Selection Sort. 19 5. a. Topological Ordering 23 b. Insertion Sort. 28 6. 0 / 1 Knapsack problem. 31 7. Dijkstra’s Algorithm. 35 8. Quick Sort. 40 9. Kruskal’s Algorithm. 42 10. a. BFS 48 Department of CSE / ISE Analysis and Design of Algorithms 1

Upload: maithreyi-g-rao

Post on 28-Nov-2014

96 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

ALGORITHMS LAB MANUAL

List of Experiments: Page no.

1. Recursive Binary & Linear Search. 12. Heap Sort. 63. a. Merge Sort 10

b. DFS ( Connected or not ). 144. Selection Sort. 195. a. Topological Ordering 23

b. Insertion Sort. 286. 0 / 1 Knapsack problem. 317. Dijkstra’s Algorithm. 358. Quick Sort. 409. Kruskal’s Algorithm. 4210. a. BFS 48

b. Floyd’s Algorithm 5311. Subset problem. 5612. a. Horspool String matching Algorithm. 61

b. Binomial Co – Efficient. 6513. Prim’s Algorithm. 68

14. a. DFS 71b. Warshall’s Algorithm 77

15. N – Queen’s Algorithm 80

Department of CSE / ISE Analysis and Design of Algorithms1

Page 2: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

1. Perform recursive Binary and Linear search.

ALGORITHM :

BINARY SEARCH

Step 1: if(begin<=end) the go to Step 2 else go to StepStep 2: mid = (begin+end)/2Step 3: if(key element = a[mid]) then successful search else go to step 4

/* search the upper half of the array */Step 4: If(k<a[mid]) then recursively call binary(begin, mid-1)

/* search the lower half of the array */Step 5: if(k>a[mid]) then recursively call binary (mid+1,end)

LINEAR SERACH

Step 1: input an array with n number of elementsStep 2: input the key elementStep 3: if( key element = a[1] ) then successful search exit.Step 4: else go to Step 5Step 5: Recursively call the same algorithm for the rest n-1 elements.

Department of CSE / ISE Analysis and Design of Algorithms2

Page 3: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

PROGRAM FOR BINARY SEARCH :

#include<stdio.h>#include<conio.h>int a[20] , n , k ; /* variable declaration */int bsearch ( int begin , int end ) ; /* Function declaration */

void main (){

int i , flag = 0 ;clrscr () ;printf ( " \n Enter size of the array n : " ) ;scanf ( "%d" , &n ) ;printf ( " \n Enter elements of array in ascending order : " ) ;for ( i = 0 ; i < n ; i++ )

scanf ( "%d" , &a[i] ) ;printf ( "\n Enter the key element : " ) ;scanf ( "%d" , &k ) ;flag = bsearch ( 0, n - 1 ) ;if ( flag == 1 )

printf ( " \n Successful search , key element is present " ) ;else

printf ( " \n Unsuccessful search " ) ;getch () ;}

int bsearch ( int begin , int end ){

int mid ;if ( begin <= end ){

mid = ( begin + end ) / 2 ;if ( k == a[mid] )

return 1 ;if ( k < a[mid] )

return bsearch ( begin , mid - 1 ) ;if ( k > a[mid] )

return bsearch ( mid + 1, end ) ;}return 0 ;

}

Department of CSE / ISE Analysis and Design of Algorithms3

Page 4: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

==========Input - Output=============

Enter size of the array n : 5

Enter elements of array in ascending order : 12345

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 : 12345

Enter the key element : 6

Unsuccessful search

Department of CSE / ISE Analysis and Design of Algorithms4

Page 5: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

PROGRAM FOR LINEAR SEARCH :

# include <stdio.h># include <conio.h>

int RLSearch(int a[], int low, int high, int key){ if( low>high )

return(-1); if(key==a[low])

return(low); else

return( RLSearch(a, low+1, high, key) );}

void main(){ int n, a[20], key; int pos; 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]); printf("\n Enter the Key to be Searched : "); scanf("%d", &key);

pos = RLSearch(a, 1, n, key);

if( pos == -1 ) printf("\n Key Not Found"); else printf("\n Key %d Found in position %d", key, pos);

getch();}

Department of CSE / ISE Analysis and Design of Algorithms5

Page 6: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

==========Input - Output=============

Enter size of the array n : 5

Enter elements of array in ascending order : 12345

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 : 12345

Enter the key element : 6

Key not found

Department of CSE / ISE Analysis and Design of Algorithms6

Page 7: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

2. Sort a given set of elements using the Heap Sort method.

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 2Step 2: k = i ; v = H[k] and heap = falseStep 3: while not heap and 2 * k <= n doStep 4: j = 2 * kStep 5: if j < n // there are two childrenStep 6: if H[j] < H[j+1] j = j + 1Step 7: if v >= H[j] heap = trueStep 8: else go to Step 9Step 9: H[k] = H[j] ; k = jStep 10: H[k] = v

Department of CSE / ISE Analysis and Design of Algorithms7

Page 8: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

PROGRAM :

#include<stdio.h>#include<conio.h>#define max 100void 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 Analysis and Design of Algorithms8

Page 9: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

{int i , e , j ;// start from middle of a and move up to 1for ( i = n/2 ; i >= 1 ; i-- ){

e = a[i] ; //save root of subtreej = 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 elemente = a[n] ; //get the last element n-- ;// Heap the structure againi = 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 Analysis and Design of Algorithms9

Page 10: ADA Lab Manual

Check out more Downloads @ 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

Department of CSE / ISE Analysis and Design of Algorithms10

Page 11: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

3. a. Sort a given set of elements using Merge Sort method.

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 orderStep 1: If n > 1 then go thru the following stepsStep 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 [ 0…p+q-1 ] of the elements of B and CStep 1: i = 0Step 2: j = 0Step 3: k = 0Step 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 Analysis and Design of Algorithms11

Page 12: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

} /* end if */Step 11: k = k + 1

/* end while */Step 12: if i = p then copy C [ j..q-1 ] to A [ k..p+q-1 ]Step 13: else copy B [ i….p-1 ] to A [ k…p+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 Analysis and Design of Algorithms12

Page 13: ADA Lab Manual

Check out more Downloads @ 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();}

Department of CSE / ISE Analysis and Design of Algorithms13

Page 14: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

================Input – Output===============

Enter how many numbers : 5

Enter 5 numbers :9967851297

Sorted numbers are :

1267859799

Department of CSE / ISE Analysis and Design of Algorithms14

Page 15: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

3. b. Check whether a given graph is connected or not using DFS method.

ALGORITHM :

DFS ( G )

//Input: Graph G = < V , E >//Output: Graph G, whether it is connected or notStep 1:mark each vertex in V with 0 as a mark of being “unvisited”Step 2:count = 0Step 3:for each vertex v in V doStep 4:if v is marked with 0 then DFS ( v )

//end forDFS ( 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 countStep 5:count = count + 1Step 6:mark v with countStep 7:for each vertex w in V adjacent to v doStep 8:if w is marked with 0 then DFS ( w )

//end for

Department of CSE / ISE Analysis and Design of Algorithms15

Page 16: ADA Lab Manual

Check out more Downloads @ 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 Analysis and Design of Algorithms16

Page 17: ADA Lab Manual

Check out more Downloads @ 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 Analysis and Design of Algorithms17

Page 18: ADA Lab Manual

Check out more Downloads @ 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();}

Department of CSE / ISE Analysis and Design of Algorithms18

Page 19: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

============Input – Output==========

Enter number of vertices : 4Enter adjacent vertex and weight for : 1 : 2 1You want to continue ( y/n )? yEnter adjacent vertex and weight for : 2 : 3 1You want to continue ( y/n )? yEnter adjacent vertex and weight for : 2 : 4 1You want to continue ( y/n )? yEnter adjacent vertex and weight for : 3 : 2 1You want to continue ( y/n )? yEnter adjacent vertex and weight for : 3 : 4 1You want to continue ( y/n )? yEnter adjacent vertex and weight for : 4 : 2 1You want to continue ( y/n )? yEnter adjacent vertex and weight for : 4 : 3 1You want to continue ( y/n )? n

Adjacency List Output :

< 1 ,2 > 1< 2 ,1 > 1< 2 ,3 > 1< 2 ,4 > 1< 3 ,2 > 1< 3 , 4 > 1

Department of CSE / ISE Analysis and Design of Algorithms19

1

4 3

2

Page 20: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

< 4 ,2 > 1< 4 ,3 > 1

Connected

============Input – Output==========

Enter number of vertices : 4Enter adjacent vertex and weight for : 1 : 2 1You want to continue ( y/n )? yEnter adjacent vertex and weight for : 1 : 3 1You want to continue ( y/n )? yEnter adjacent vertex and weight for : 2 : 1 1You want to continue ( y/n )? yEnter adjacent vertex and weight for : 3 : 1 1You want to continue ( y/n )? yEnter adjacent vertex and weight for : 4 : 0 0You want to continue ( y/n )? n

Adjacency List Output :

< 1 ,2 > 1< 1 ,3 > 1< 2 ,1 > 1< 3 ,1 > 1

Not Connected

Department of CSE / ISE Analysis and Design of Algorithms20

1 2

3 4

Page 21: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

4. Sort a given set of elements using Selection sort .

ALGORITHM :

Selection sort ( A [ 0…n-1 ] )

//The algorithm sorts a given array by selection sort//Input: An array A [ 0…n-1 ] of orderable elements//Output: Array A [ 0….n-1 ] sorted in ascending orderStep 1: for i = 0 to n – 2 doStep 2: min = i Step 3: for j =i + 1 to n – 1 doStep 4: if a[j] < a[min] then go to Step 5Step 5: min = j

//end forStep 6: swap A[i] and A[min]

//end for

Department of CSE / ISE Analysis and Design of Algorithms21

Page 22: ADA Lab Manual

Check out more Downloads @ 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 Analysis and Design of Algorithms22

Page 23: ADA Lab Manual

Check out more Downloads @ 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 : 71935

The sorted elements are :13579

Department of CSE / ISE Analysis and Design of Algorithms23

Page 24: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

5. a. Obtain the Topological ordering of vertices in a given digraph.

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 Analysis and Design of Algorithms24

Page 25: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

void Push(int x){ top=top+1; s[top]=x ;}

int Pop(){ int x = s[top] ; top=top-1; return(x);}

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 Analysis and Design of Algorithms25

Page 26: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

printf("\n %d <----> %d : %d", i, j, g[i][j]);}

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 Analysis and Design of Algorithms26

Page 27: ADA Lab Manual

Check out more Downloads @ 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 Analysis and Design of Algorithms27

Page 28: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

============Input – Output============

Enter 100 for diagonal elements and no edges :Enter the no of vertices : 3Enter the Adjacency matrix:

100 100 11 100 1100 100 100

The topological ordering is :2 1 3

============Input – Output============

Enter 100 for diagonal elements and no edges :Enter the no of vertices : 2

Department of CSE / ISE Analysis and Design of Algorithms28

1

2 3

1

Page 29: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

Enter the Adjacency matrix:

100 11 100

The topological ordering is :

No topological ordering possible

5. b. Sort a given set of elements using Insertion sort method.

ALGORITHM :

Insertionsort ( A [ 0…n-1 ] )

//Input: An array A [ 0….n-1 ] of orderable elements//Output: Array A [ 0…..n-1 ] sorted in increasing orderStep 1: for i = 1 to n – 1 do {Step 2: v = A[i]Step 3: j = i – 1Step 4: while j >= 0 and A[j] > v do {Step 5: A[j+1] = a[j]Step 6: j = j – 1

Department of CSE / ISE Analysis and Design of Algorithms29

2

Page 30: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

} //end whileStep 7: A[j+1] = v

} //end for

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 Analysis and Design of Algorithms30

Page 31: ADA Lab Manual

Check out more Downloads @ 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 : 92851

The sorted elements are :1

Department of CSE / ISE Analysis and Design of Algorithms31

Page 32: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

2589

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 //Knapsack’s capacity.

Department of CSE / ISE Analysis and Design of Algorithms32

Page 33: ADA Lab Manual

Check out more Downloads @ 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 [ 0…n, 0…W ] whose entries are //initialized with –1’s except for row 0 and column 0 initialized with //0’s.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 elseStep 6: V[i j] = value

} //end ifStep 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 Analysis and Design of Algorithms33

Page 34: ADA Lab Manual

Check out more Downloads @ 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 Analysis and Design of Algorithms34

Page 35: ADA Lab Manual

Check out more Downloads @ 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 : 3Enter the weights :1 2 2Enter the profits :18 16 6Enter the Knapsack capacity: 4

Department of CSE / ISE Analysis and Design of Algorithms35

Page 36: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

Optimal solution = 34

Enter the number of objects : 4Enter the weights :2 1 3 2Enter the profits :12 10 20 15Enter the Knapsack capacity: 5

Optimal solution = 37

7. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra’salgorithm.

ALGORITHM :

Department of CSE / ISE Analysis and Design of Algorithms36

Page 37: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

Dijkstra( G , s )

//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 = infinityStep 4: pv = NULLStep 5: Insert(Q, v , dv )//initialize vertex priority in the priority queue

} //end forStep 6: ds = 0Step 7: Decrease ( Q , s , ds ) //update priority of s with dsStep 8: Vt = 0Step 9: for I = 0 to | V | - 1 do {Step 10:u* = DeleteMin ( Q ) //delete the minimun priority elementStep 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

Department of CSE / ISE Analysis and Design of Algorithms37

Page 38: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

# define TRUE 1# define FALSE 0

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 Analysis and Design of Algorithms38

Page 39: ADA Lab Manual

Check out more Downloads @ 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);

Department of CSE / ISE Analysis and Design of Algorithms39

Page 40: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

getch();

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=============

Department of CSE / ISE Analysis and Design of Algorithms40

Page 41: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

Enter the no of vertices : 5Enter the Adjacency matrix :

0 3 100 7 1003 0 4 2 100100 4 0 5 67 2 5 0 4100 100 6 4 0

Enter starting vertex : 1

2 : 33 : 74 : 55 : 9

8. Sort a given set of elements using Quick sort method.

Department of CSE / ISE Analysis and Design of Algorithms41

2 3

1 4 5

Page 42: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

ALGORITHM :

Quicksort ( A [l…r] )

//Sorts a subarray by quicksort//Input: A subarray A[l…r] of A[0….n-1], defined by its left and right //indices l and r//Output: The subarray A[l…r] sorted in increasing orderStep 1: if l < r then {Step 2: s = partition( A[l…r] ) //s is a split positionStep 3: Quicksort ( A [ l…s-1 ] )Step 4: Quicksort ( A [ s+1…r ] )

Partition ( A [ l……r ] )

//Partitions a sub array by using its first element as a pivot//Input: A sub array A[l..r] of A[0…n-1], defined by its left and right //indices l and r ( l < r ).//Output: A partition of A[l…r], with the split position returned as

this //function’s value.Step 1: p = a[l]Step 2: i = lStep 3: j = r + 1Step 4: repeatStep 5: repeat i = i + 1 until A[i] >= pStep 6: repeat j = j –1 until A[j] <= pStep 7: swap ( A[i] , A[j] )Step 8: until i >= jStep 9: swap ( A[i] , A[j] ) //undo last swap when i >= jStep 10: swap ( A[l], A[j] )Step 11: return j

Department of CSE / ISE Analysis and Design of Algorithms42

Page 43: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

PROGRAM :

# include <stdio.h># include <conio.h>

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();

}

Department of CSE / ISE Analysis and Design of Algorithms43

Page 44: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

===============Input – Output=============

Enter array size : 10

Enter the array :

4 2 1 9 8 3 5 7 10 6

The sorted array is :

1 2 3 4 5 6 7 8 9 10

Department of CSE / ISE Analysis and Design of Algorithms44

Page 45: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

9. Find Minimum Cost Spanning tree of a given undirected graph using Kruskal’s 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 sizeStep 3:k = 0 //initialize the number of processed edgesStep 4: While ecounter < | V | - 1 {Step 5:k = k + 1Step 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

Department of CSE / ISE Analysis and Design of Algorithms45

Page 46: ADA Lab Manual

Check out more Downloads @ 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 : %d \n" , e[k].v1 , e[k].v2 , e[k].wt ) ;

}

int find ( int p[] , int k ){

if ( p[k] == k )return k ;

elsereturn ( find ( p , p[k] ) ) ;

}

void bsort ( edge e[] , int n ){

int i , j ;edge temp ;for ( i = 1 ; i <= n - 1 ; i++ )

Department of CSE / ISE Analysis and Design of Algorithms46

Page 47: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

for ( j = 1 ; j <= n - 1 ; j++ )if ( e[j].wt > e[j+1].wt ){

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 Analysis and Design of Algorithms47

Page 48: ADA Lab Manual

Check out more Downloads @ 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 () ;

}

Department of CSE / ISE Analysis and Design of Algorithms48

Page 49: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

=============Input - Output============

input edge < v1 , v2 , wt > : 1 6 10 28

input edge < v1 , v2 , wt > : 10 14 3 4 12 16

input edge < v1 , v2 , wt > : 2 7 14 12

24 18input edge < v1 , v2 , wt > : 25 2 3 16

22input 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 : 10 3 <......> 4 : 12 2 <......> 7 : 14

Department of CSE / ISE Analysis and Design of Algorithms49

1

7 3

4

2

5

6

Page 50: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

2 <......> 3 : 16 4 <......> 5 : 22

5 <......> 6 : 25

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 = 0Step 3:for each vertex v in V doStep 4:if v is marked with 0 then BFS ( v )

//end forBFS ( 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 countStep 5:count = count + 1Step 6:mark v with count and initialize a queue with vStep 7:While the queue is not empty do {Step 8:for each vertex w in V adjacent to the front’s vertex v do {Step 9:if w is marked with 0 then {Step 10:count = count + 1Step 11:add w to the queue

} // end if//end for

Step 12:remove vertex v from the front of the queue} // end while

Department of CSE / ISE Analysis and Design of Algorithms50

Page 51: ADA Lab Manual

Check out more Downloads @ 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){

Department of CSE / ISE Analysis and Design of Algorithms51

Page 52: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

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 = QDelete(); for(j=1; j<=n; j++) if( g[i][j] != INFINITY && visited[j]==FALSE ) {

QInsert(j); visited[j]=TRUE;

} return(i);}

Department of CSE / ISE Analysis and Design of Algorithms52

Page 53: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

void BFS(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; 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();}

Department of CSE / ISE Analysis and Design of Algorithms53

Page 54: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

===============Input – Output=============

Enter number of vertices : 4Enter adjacent vertex and weight for : 1 : 2 0You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 2 : 3 0You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 2 : 4 0You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 3 : 0 0You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 4 : 1 0You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 4 : 3 0You want to continue (y/n) ? n

Adjacency List Output :< 1 , 2 > 0< 2 , 3 > 0< 2 , 4 > 0< 4 , 1 > 0< 4 , 3 > 0

Enter Starting vertex : 1Vertices reachabale from: 1 are :

Department of CSE / ISE Analysis and Design of Algorithms54

1 2

4 3

Page 55: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

234

10. b. Implement All Pair Shortest paths problem using Floyd’s algorithm.

ALGORITHM :

Floyd ( W [ 1…n , 1….n ] )

//Input: The weight matrix W of a graph.//Output: The distance matrix of the shortest path’s lengths.Step 1: D = W // is not necessary if W can be overwrittenStep 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

Department of CSE / ISE Analysis and Design of Algorithms55

Page 56: ADA Lab Manual

Check out more Downloads @ 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 Analysis and Design of Algorithms56

Page 57: ADA Lab Manual

Check out more Downloads @ 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);

Department of CSE / ISE Analysis and Design of Algorithms57

Page 58: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

getch();}

============Input – Output=============

Enter the no of vertices : 4Enter the Adjacency matrix:

0 100 3 100 22 0 100 100100 7 0 1 76 100 100 0

3The final Adjacency matrix is : 6

0 10 3 42 0 5 6 17 7 0 16 16 9 0

Department of CSE / ISE Analysis and Design of Algorithms58

1 2

3 4

Page 59: ADA Lab Manual

Check out more Downloads @ 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 doesn’t 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 problem’s solutionsStep 1:If X [1..i ] is a solution write X [1…i ]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

Department of CSE / ISE Analysis and Design of Algorithms59

Page 60: ADA Lab Manual

Check out more Downloads @ 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] ;Department of CSE / ISE Analysis and Design of Algorithms60

Page 61: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

if ( sum < d || s[1] > d )printf ( " \n no subset possible : " ) ;

elsesumofsub ( 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] ) ;

}}

Department of CSE / ISE Analysis and Design of Algorithms61

Page 62: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

============Input - Output=============

enter the size of the set : 5

Enter the set in increasing order : 12568

enter the value of d : 9

1 2 6 1 8

============Input - Output=============

enter the size of the set : 6

Department of CSE / ISE Analysis and Design of Algorithms62

Page 63: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

Enter the set in increasing order : 51012131518

enter the value of d : 30

5 10 15 5 12 13 12 18

12. a. Implement Horspool algorithm for String Matching.

ALGORITHM :

ShiftTable ( P [ 0….m-1 ] )

//Fills the shift table used by Horspool’s and Boyer – Moore algorithms.//Input: Pattern P [ 0…m-1 ] and an alphabet of possible characters.//Output: Table [ 0…size – 1 ] indexed by the alphabet’s characters and filled with shift sizes computed by formula.Step 1: for j = 0 to m –2 do Table [ P [ j ] ] = m – 1 – jStep 2: Table.

Horspool Algorithm :

Step 1: For a given pattern of length m and the alphabet used in both the pattern and text, construct the shift table as described above.

Step 2: Align the pattern against the beginning of the text.

Department of CSE / ISE Analysis and Design of Algorithms63

Page 64: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

Step 3: Repeat the following until either a matching sub string is 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 c’s column of the shift table where c is the text’s 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 256int 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 : " ) ;

Department of CSE / ISE Analysis and Design of Algorithms64

Page 65: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

gets ( pattern ) ;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 charactersfor ( j = 0 ; j < m - 1 ; j++ ){

//decimal value of pattern characterindex = ( 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 valueindex = ( s[i] - '0' ) ;i = i + t[index] ; // get the shift value

Department of CSE / ISE Analysis and Design of Algorithms65

Page 66: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

}}return -1 ;

}

=============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 Analysis and Design of Algorithms66

Page 67: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

12. b. Find the Binomial Co - efficient using Dynamic Programming.

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 ] = 1Step 4: C [ i , j ] = C [ i – 1 , j – 1 ] + C [ i – 1 , j ]

} //end for} //end for

Step 5: return C [ n , k ]Department of CSE / ISE Analysis and Design of Algorithms67

Page 68: ADA Lab Manual

Check out more Downloads @ 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

Department of CSE / ISE Analysis and Design of Algorithms68

Page 69: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

printf ( " \n %dC%d = %d \n " , n , k , bc ( n , k ) ) ;getch () ;

}

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 : 53

5C3 = 10

===============Input - Output============

enter the values of n & k : 4

Department of CSE / ISE Analysis and Design of Algorithms69

Page 70: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

6

invalid input

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 GStep 1:Vt= { v0 } //the set of tree vertices can be initialized with any vertexStep 2: Et = NULL

Department of CSE / ISE Analysis and Design of Algorithms70

Page 71: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

Step 3: for i = 1 | V | - 1 do {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 – VtStep 6: Vt = Vt U { u * }Step 7: Et = Et U { e* }

} //end forStep 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){

Department of CSE / ISE Analysis and Design of Algorithms71

Page 72: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

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; 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 ) {

Department of CSE / ISE Analysis and Design of Algorithms72

Page 73: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

min = g[i][j]; u = i; v = j;

}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 : 3Enter the Adjacency matrix: (100 for no edges)

100 10 110 0 61 6 0

1 6

Department of CSE / ISE Analysis and Design of Algorithms73

1 2

Page 74: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

< 1 , 3 > < 3 , 2 >

Total weight = 7

14. a. Print all the nodes reachable from a given starting node in a given digraph using Depth First Search method.

ALGORITHM :

Department of CSE / ISE Analysis and Design of Algorithms74

3

Page 75: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

DFS ( G )

//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 = 0Step 3:for each vertex v in V doStep 4:if v is marked with 0 then DFS ( v )

//end forDFS ( 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 countStep 5:count = count + 1Step 6:mark v with countStep 7:for each vertex w in V adjacent to v doStep 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

Department of CSE / ISE Analysis and Design of Algorithms75

Page 76: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

# 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);}

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');}

Department of CSE / ISE Analysis and Design of Algorithms76

Page 77: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

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);}

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()Department of CSE / ISE Analysis and Design of Algorithms77

Page 78: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

{ 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();}

===============Input – Output=============

Department of CSE / ISE Analysis and Design of Algorithms78

Page 79: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

Enter number of vertices : 4Enter adjacent vertex and weight for : 1 : 2 0You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 1 : 4 0You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 2 : 3 0You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 3 : 1 0You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 3 : 4 0You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 4 : 2 0You 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 : 1Vertices reachable from: 1 are :

234

14. b. Compute the transitive closure of a given directed graph using Warshall’s algorithm.

Department of CSE / ISE Analysis and Design of Algorithms79

1 2

3 4

Page 80: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

ALGORITHM :

Warshall ( A [1….n , 1…n ] )

//Input: The adjacency matrix A of a digraph with n vertices.//Output: The transitive closure of the digraphStep 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 Analysis and Design of Algorithms80

Page 81: ADA Lab Manual

Check out more Downloads @ 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);}

Department of CSE / ISE Analysis and Design of Algorithms81

Page 82: ADA Lab Manual

Check out more Downloads @ 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();}

Department of CSE / ISE Analysis and Design of Algorithms82

Page 83: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

==============Input – Output==========

Enter the number of vertices : 4

Enter the Adjacency matrix :

0 1 0 00 0 0 10 0 0 01 0 1 0

The Transitive Closure is :

1 1 1 11 1 1 10 0 0 01 1 1 1

Department of CSE / ISE Analysis and Design of Algorithms83

1

43

2

Page 84: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

15. Implement N Queen’s problem using Back Tracking.

ALGORITHM :

Backtrack ( X [ 1….i ] )

//Input: X [1….i] specifies first I promising components of a solution.//Output: All the tuples representing the problem’s solutionsStep 1:If X [1..i ] is a solution write X [1…i ]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

Department of CSE / ISE Analysis and Design of Algorithms84

Page 85: ADA Lab Manual

Check out more Downloads @ 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 Analysis and Design of Algorithms85

Page 86: ADA Lab Manual

Check out more Downloads @ 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();}

Department of CSE / ISE Analysis and Design of Algorithms86

Page 87: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

==========Input – Output=========

Enter the no. of Queens : 4

The solution to queens problem is : 4

X Q X XX X X QQ X X XX X Q X

X X Q XQ X X XX X X QX Q X X

==========Input – Output=========

Enter the no. of Queens : 8

The solution to queens problem is : 8

Q X X X X X X XX X X X Q X X XX X X X X X X QX X X X X Q X XX X Q X X X X XX X X X X X Q XX Q X X X X X XX X X Q X X X X

Q X X X X X X XX X X X X Q X XX X X X X X X QX X Q X X X X XX X X X X X Q XX X X Q X X X XX Q X X X X X XX X X X Q X X X

Department of CSE / ISE Analysis and Design of Algorithms87

Page 88: ADA Lab Manual

Check out more Downloads @ http://sites.google.com/site/ncetians

Department of CSE / ISE Analysis and Design of Algorithms88