Sie sind auf Seite 1von 87

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
b. Floyd’s Algorithm 53
11. Subset problem. 56
12. a. Horspool String matching Algorithm. 61
b. Binomial Co – Efficient. 65
13. Prim’s Algorithm. 68
14. a. DFS 71
b. Warshall’s Algorithm 77
15. N – Queen’s Algorithm 80

Department of CSE / ISE 1 Analysis and Design of


Algorithms
1. Perform recursive Binary and Linear search.

ALGORITHM :

BINARY SEARCH

Step 1: if(begin<=end) the go to Step 2 else go to Step


Step 2: mid = (begin+end)/2
Step 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 elements


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

Department of CSE / ISE 2 Analysis and Design of


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


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

Department of CSE / ISE 4 Analysis and Design of


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


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

Department of CSE / ISE 6 Analysis and Design of


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

Department of CSE / ISE 7 Analysis and Design of


Algorithms
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 ()
{
int i , e , j ;
// start from middle of a and move up to 1

Department of CSE / ISE 8 Analysis and Design of


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


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


Algorithms
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 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 [ 0…p+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
} /* end if */
Step 11: k=k+1
/* end while */
Department of CSE / ISE 11 Analysis and Design of
Algorithms
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);
}

void main()
{
int n, a[20];
int k;
Department of CSE / ISE 12 Analysis and Design of
Algorithms
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 13 Analysis and Design of


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

Enter how many numbers : 5

Enter 5 numbers :
99
67
85
12
97

Sorted numbers are :

12
67
85
97
99

Department of CSE / ISE 14 Analysis and Design of


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

Department of CSE / ISE 15 Analysis and Design of


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

void InitGraph(int g[20][20], int n)


{
int i,j;
for(i=1; i<=n; i++)

Department of CSE / ISE 16 Analysis and Design of


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

void DFS(int g[20][20], int n, int sv)


{
int i,v, visited[20], flag=FALSE;

for(i=1; i<=n; i++)


Department of CSE / ISE 17 Analysis and Design of
Algorithms
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 18 Analysis and Design of


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

Enter number of vertices : 4


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

Adjacency List Output :

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

Connected

Department of CSE / ISE 19 Analysis and Design of


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

Enter number of vertices : 4


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

Adjacency List Output :

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

Not Connected 3 4

Department of CSE / ISE 20 Analysis and Design of


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

Department of CSE / ISE 21 Analysis and Design of


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

void selectionsort ()
Department of CSE / ISE 22 Analysis and Design of
Algorithms
{
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

Department of CSE / ISE 23 Analysis and Design of


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

void Push(int x)
{
top=top+1;
s[top]=x ;
}
Department of CSE / ISE 24 Analysis and Design of
Algorithms
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 )
printf("\n %d <----> %d : %d", i, j, g[i][j]);
}

int InDeg(int g[20][20], int n, int v)


{
Department of CSE / ISE 25 Analysis and Design of
Algorithms
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);
}

for(i=1; i<=n; i++)


if( degree[i] == 0 && visited[i]==FALSE )
{
Push(i);
visited[i]=TRUE;
}
Department of CSE / ISE 26 Analysis and Design of
Algorithms
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 27 Analysis and Design of


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

Enter 100 for diagonal elements and no edges :


Enter the no of vertices : 3
Enter the Adjacency matrix:
1
100 100 1
1 100 1
100 100 100

The topological ordering is : 2 3


2 1 3

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

Enter 100 for diagonal elements and no edges :


Enter the no of vertices : 2 1
Enter the Adjacency matrix:

100 1
1 100

The topological ordering is : 2

Department of CSE / ISE 28 Analysis and Design of


Algorithms
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 order
Step 1: for i = 1 to n – 1 do {
Step 2: v = A[i]
Step 3: j=i–1
Step 4: while j >= 0 and A[j] > v do {
Step 5: A[j+1] = a[j]
Step 6: j=j–1
} //end while
Step 7: A[j+1] = v
} //end for

Department of CSE / ISE 29 Analysis and Design of


Algorithms
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 ) ;
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] ) ;

Department of CSE / ISE 30 Analysis and Design of


Algorithms
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
2
5
8
9

Department of CSE / ISE 31 Analysis and Design of


Algorithms
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.
//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 {
Department of CSE / ISE 32 Analysis and Design of
Algorithms
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 ;

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
{
Department of CSE / ISE 33 Analysis and Design of
Algorithms
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]; }
}
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]);

Department of CSE / ISE 34 Analysis and Design of


Algorithms
getch();
}

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

Enter the number of objects : 3


Enter the weights :
1 2 2
Enter the profits :
18 16 6
Enter the Knapsack capacity: 4

Optimal solution = 34

Enter the number of objects : 4


Enter the weights :
2 1 3 2
Enter the profits :
12 10 20 15
Enter the Knapsack capacity: 5

Department of CSE / ISE 35 Analysis and Design of


Algorithms
Optimal solution = 37

7. From a given vertex in a weighted connected graph, find


shortest paths to other vertices using Dijkstra’s
algorithm.

ALGORITHM :

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 = infinity
Step 4: pv = NULL
Step 5: Insert(Q, v , dv )//initialize vertex priority in the priority queue
} //end for
Department of CSE / ISE 36 Analysis and Design of
Algorithms
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
# 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;

}
Department of CSE / ISE 37 Analysis and Design of
Algorithms
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[])


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

Department of CSE / ISE 38 Analysis and Design of


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

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

Department of CSE / ISE 39 Analysis and Design of


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

Enter the no of vertices : 5


Enter the Adjacency matrix :

0 3 100 7 100
3 0 4 2 100 2 3
100 4 0 5 6
7 2 5 0 4
100 100 6 4 0
1 4 5
Enter starting vertex : 1

2 : 3
3 : 7
4 : 5
Department of CSE / ISE 40 Analysis and Design of
Algorithms
5 : 9

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

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 order
Step 1: if l < r then {
Step 2: s = partition( A[l…r] ) //s is a split position
Step 3: Quicksort ( A [ l…s-1 ] )
Department of CSE / ISE 41 Analysis and Design of
Algorithms
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=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 :

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


Department of CSE / ISE 42 Analysis and Design of
Algorithms
{
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();
}

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


Algorithms
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.
Department of CSE / ISE 44 Analysis and Design of
Algorithms
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

PROGRAM :

#include<conio.h>
#include<stdio.h>
struct tag
{
int v1 , v2 , wt ;
};
typedef struct tag edge ;

void readgraph(edge e[] , int n )


Department of CSE / ISE 45 Analysis and Design of
Algorithms
{
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 ;
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 )
{

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 )
Department of CSE / ISE 46 Analysis and Design of
Algorithms
{
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 ) ;
}

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 ) ;
Department of CSE / ISE 47 Analysis and Design of
Algorithms
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 () ;
}

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

input edge < v1 , v2 , wt > :


1 6 10 28
1 2
input edge < v1 , v2 , wt > : 10 14
3 4 12 16

input edge < v1 , v2 , wt > : 7 3


6
Department of CSE / ISE 48 Analysis and Design of
Algorithms
2 7 14 12
24 18
input edge < v1 , v2 , wt > : 25
2 3 16 5 4
22
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 : 10

3 <......> 4 : 12

2 <......> 7 : 14

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 :

Department of CSE / ISE 49 Analysis and Design of


Algorithms
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 front’s 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

PROGRAM :

# include <stdio.h>
# include <conio.h>
# define INFINITY 999
# define TRUE 1
# define FALSE 0

Department of CSE / ISE 50 Analysis and Design of


Algorithms
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++)
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> : ");
Department of CSE / ISE 51 Analysis and Design of
Algorithms
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)


{
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);
Department of CSE / ISE 52 Analysis and Design of
Algorithms
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();
}

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

Department of CSE / ISE 53 Analysis and Design of


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

Enter adjacent vertex and weight for : 2 : 3 0


You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 2 : 4 0


You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 3 : 0 0


You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 4 : 1 0


You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 4 : 3 0


You want to continue (y/n) ? n

Adjacency List Output :


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

Enter Starting vertex : 1 4 3


Vertices reachabale from: 1 are :

2
3
4

10. b. Implement All Pair Shortest paths problem using


Floyd’s algorithm.

Department of CSE / ISE 54 Analysis and Design of


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

PROGRAM :

Department of CSE / ISE 55 Analysis and Design of


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

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++)


Department of CSE / ISE 56 Analysis and Design of
Algorithms
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 57 Analysis and Design of


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

Enter the no of vertices : 4


Enter the Adjacency matrix:

0 100 3 100 2
2 0 100 100
1 2
100 7 0 1 7
6 100 100 0
3
The final Adjacency matrix is : 6

0 10 3 4 3 4
2 0 5 6 1
7 7 0 1
6 16 9 0

Department of CSE / ISE 58 Analysis and Design of


Algorithms
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 solutions
Step 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 59 Analysis and Design of


Algorithms
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 : " ) ;
else
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 )

Department of CSE / ISE 60 Analysis and Design of


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


Algorithms
============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 2 6
1 8

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

enter the size of the set : 6

Enter the set in increasing order :


5
10
12
13
15
18

enter the value of d :


30

5 10 15
5 12 13
12 18

Department of CSE / ISE 62 Analysis and Design of


Algorithms
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 – j
Step 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.
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.

Department of CSE / ISE 63 Analysis and Design of


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

Department of CSE / ISE 64 Analysis and Design of


Algorithms
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
}
}
return -1 ;
}

Department of CSE / ISE 65 Analysis and Design of


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


Algorithms
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 ] = 1
Step 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 67 Analysis and Design of


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

Department of CSE / ISE 68 Analysis and Design of


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

enter the values of n & k :


5
3

5C3 = 10

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

enter the values of n & k :


4
6

invalid input

Department of CSE / ISE 69 Analysis and Design of


Algorithms
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 {
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.

Department of CSE / ISE 70 Analysis and Design of


Algorithms
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;
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]);
Department of CSE / ISE 71 Analysis and Design of
Algorithms
}

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];
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);
Department of CSE / ISE 72 Analysis and Design of
Algorithms
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 : 3


Enter the Adjacency matrix: (100 for no edges)
10
0 10 1 1 2
10 0 6
1 6 0
1 6
<1,3> <3,2>

Total weight = 7 3

Department of CSE / ISE 73 Analysis and Design of


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

ALGORITHM :

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

Department of CSE / ISE 74 Analysis and Design of


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

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;
Department of CSE / ISE 75 Analysis and Design of
Algorithms
}

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

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;
Department of CSE / ISE 76 Analysis and Design of
Algorithms
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 77 Analysis and Design of


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

Enter number of vertices : 4


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

Enter adjacent vertex and weight for : 1 : 4 0


You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 2 : 3 0


You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 3 : 1 0


You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 3 : 4 0


You want to continue (y/n) ? y

Enter adjacent vertex and weight for : 4 : 2 0


You want to continue (y/n) ? n

Adjacency List Output :


<1,2> 0
1 2
<1,4> 0
<2,3> 0
<3,1> 0
<3,4> 0
<4,2> 0
3 4
Enter Starting vertex : 1
Vertices reachable from: 1 are :

Department of CSE / ISE 78 Analysis and Design of


Algorithms
2
3
4

14. b. Compute the transitive closure of a given directed


graph using Warshall’s algorithm.

ALGORITHM :

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

//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)

Department of CSE / ISE 79 Analysis and Design of


Algorithms
PROGRAM :

# 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])


{

Department of CSE / ISE 80 Analysis and Design of


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

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


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

Enter the number of vertices : 4

Enter the Adjacency matrix :


1 2
0 1 0 0
0 0 0 1
0 0 0 0
1 0 1 0

The Transitive Closure is :


3 4
1 1 1 1
1 1 1 1
0 0 0 0
1 1 1 1

Department of CSE / ISE 82 Analysis and Design of


Algorithms
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 solutions
Step 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 83 Analysis and Design of


Algorithms
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];

Department of CSE / ISE 84 Analysis and Design of


Algorithms
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++)


{

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


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

Enter the no. of Queens : 4

The solution to queens problem is : 4

X Q X X
X X X Q
Q X X X
X X Q X

X X Q X
Q X X X
X X X Q
X 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 X
X X X X Q X X X
X X X X X X X Q
Department of CSE / ISE 86 Analysis and Design of
Algorithms
X X X X X Q X X
X X Q X X X X X
X X X X X X Q X
X Q X X X X X X
X X X Q X X X X

Q X X X X X X X
X X X X X Q X X
X X X X X X X Q
X X Q X X X X X
X X X X X X Q X
X X X Q X X X X
X Q X X X X X X
X X X X Q X X X

Department of CSE / ISE 87 Analysis and Design of


Algorithms

Das könnte Ihnen auch gefallen