You are on page 1of 41

SEMESTER 4

Algorithmic Lab
Sl.No. Algorithm and Program Page No.

1. Linear Search 1

2. Fibonacci Series – Iterative 5

3. Binary Search 8

4. Fibonacci Series – Recursive 12

5. Merge Sort 15

16 Quick Sort 20

17 Depth First Search 24

18 Breadth First Search 28

19 Prim’s Algorithm 31

20 Kruskal’s Algorithm 34
Linear search Algorithm

//Implements linear search

//Input: An array A[0…n-1]

//Output: An intex of array’s that is equal to S

Loc = -1

For i=1to n do

If(A[i]=S) then

Loc = i

Exit

End if

End for

Exit

Apriori Analysis

Program Time Frequency

LOC = -1 1 1

INTIALIZATIO 1 1
N STEP

For I = 1 to N do 2 N+1

If (A[I] = S) Then 2 N

LOC = I; 1 1

EXIT

Endif

Endfor

Exit

2
Time = 1x1 + 1x1+2x (N+1) + 2xN + 1x1

= 3 + 2N + 2 + 2N

= 4N +5

Tabulate Time v/s N (Input Size) for varying input size

N Total Time

5 25

10 45

15 65

20 85

25 105

/* Program to search an element by sequential search method and estimate the time
and space complexity */

#include<stdio.h>
void main()
{
int arr[100],i,n,found=0,t=0,key;

printf("\n program to search an element using linear search");


printf("\n enter the size of an array");
scanf("%d",&n);

3
printf("\n enter the array element");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
t=t+2;
printf("\n enter the key");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key==arr[i])
{
found=1;
break;
}
t=t+2;
}
t=t+4;
t+t+2;
t=t+1;
if(found==1)
printf("\n the search element was found");
else
printf("\n the search element was not found");
printf("\n time taken is %d",t);

OUTPUT

program to search an element using linear search

enter the size of an array 5

enter the array element 1

enter the key6

the element was not found

4
time taken is 17

program to search an element using linear search

enter the size of an array 5

enter the array element 1

enter the key 1

the search element was found

time taken is 7

Aposteriori analysis

N T

5 7

10 14

15 21

20 35

5
Fibonacci series using non recursion

Algorithm F(n)

//Computes the nth Fibonacci number iteratively by using its definition

//Input: A non negative integer n

//Output: The n th Fibonacci number

F[0]←0; F[1]←1

for i←2 to n do

F[i]←F[i-1]+F[i-2]

returnF[n]

Apriori Analysis

Program Time Frequency

F[0]←0 1 1

F[1]←1 1 1

for i←2 to n do 2 N+1

6
F[i]←F[i-1]+F[i-2] 5 N

returnF[n] 1 1

Time = 1 * 1 + 1* 1+2(N+1)+5*N+1*1

= 1+1+2N+2+5N+1

=7N+5

=O(N)

/* Program to generate Fibonacci series using non recursion and estimate the time
and space complexity*/

#include<stdio.h>
void fibo(int);
int t;
void main()
{ int n;
printf("\nEnter the number of elements");
scanf("%d",&n);
fibo(n);
printf("\nTime taken is %d",t);

7
printf("Space = %d bytes\n", sizeof(n)+sizeof(f1)+sizeof(f2)+sizeof(f3));

}
void fibo(int n)
{ int f1,f2,f3,i;
f1=0;
f2=1;
t=t+2;
printf("%d\n%d\n",f1,f2);
t++;
for (i=3;i<=n;i++)
{ t+=2;
f3=f1+f2;
printf("%d\n",f3);
f1=f2;
f2=f3;
t+=4;
}
}

OUTPUT

Enter the number of elements5


0
1
1
2

8
3
Time = 21
Enter the number of elements 8
0
1
1
2
3
5
8
13
Time = 39

Aposteriori Analysis

N Time

5 21

10 39

15 81

20 111

25 141

Binary search Algorithm

Algorithm Binary search(A[0....n-1],k)

//Implements non recursively binary search

//Input: An array A[0...n-1] sorted in ascending order and a search key k

9
● //Output: An index of array's element that is equal to k or -1 if there is no
such //element

l←0;r←n-1

while l<=r do

m←[(l+r)/2]

if k=A[m] return m

else if k<A[m] r←m-1

else l←m+1

return -1

Apriori Analysis

T(n) = T(n/2)+1, T(1)=1


= [T(n/4)+1]+1]
= [T(n/8)+1]+2
= T(n/23)+3
For k times,
= T(n/2k)+k
n/2k becomes 1, when n=2k, k=log n
= T(n/2 log n)+k
= T(1) + k
= T(0) +1 +k
= O(log n) as k=log n

/* Program to search an element by binary search and estimate the time and space
complexity*/
#include<stdio.h>

10
#include<conio.h>
int t=0;
int binarysearch(int a[100],int,int);
void main()
{ int a[100],i,n,pos,key;
printf("\n\nenter the sizeof array\n");
scanf("\n%d",&n);
printf("\n\nenter the elements of array\n");
for(i=0;i<n;i++)
scanf("\n%d",&a[i]);
printf("\n\n enter the element to be search\n");
scanf("\n%d",&key);
pos=binarysearch(a,n,key);
if(pos==-1)
printf("\nunsuccessful\n");
else
printf("\nsuccessful found in the pos %d\n",pos);
printf("\n time taken =%d",t);

printf("Space = %d bytes\n", sizeof(a)+sizeof(n)+sizeof(key)+sizeof(pos)+6);


}
int binarysearch(int a[100],int n, int key)
{ int l,m,r;
l=0;
r=n-1;
t=t+3;
while(l<=r)
{ m=(l+r)/2;
t=t+3;

11
if(key==a[m])
{ t++;
return m;
}
else if(key<a[m])
{
r=m-1;
t=t+3;
}
else
{
l=m+1;
t=t+3;
}
}
return -1;
}

OUTPUT

Enter the size of array 5


Enter the elements of array 1
2
3
4
5
Enter the element to search 1

12
Successful found in the position 0
Time taken 13 space=212 bytes
Enter the size of array 6
Enter the elements of array 1
2
4
5
6
7

Enter the element to search 8


Unsuccessful
Time taken = 21 space =212 bytes

N Total Time

5 2.3219

10 3.3219

15 3.9068

20 4.3219

25 4.6498

30 4.9068

35 5.1292

40 5.3219

13
Algorithm Fibonacci series using recursion F(n)

// Computes the nth Fibonacci number recursively by using its definition

//Input: A nonnegative integer n

//Output: The nth Fibonacci number

if n<=1

return n

else

return F(n-1)+F(n-2)

Apriori Analysis

T(n) = T(n-1)+T(n-2), T(1)=1,T(0)=1

= 2T(n-1)

= 2[2T(n-2)]

= 4[2T(n-3)]

= 23T(n-3)

For K steps

= 2kT(n-k)

14
When k=n

= 2nT(n-n)

= 2n T(0)

= 2n.1

= 2n = O(2n)

15
/* Program to generate Fibonacci series using recursion and estimate the time and
space complexity*/
int t;
#include<stdio.h>
int fibo(int);
void main()
{ int n,i;
printf("\nEnter the number of elements");
scanf("%d",&n);
printf("Fibonacci series\n");
for(i=1;i<=n;i++)
printf("\n%d",fibo(i));
printf("\ntime=%d,n=%d",t,n);
printf("Space = %d bytes\n", sizeof(n)+sizeof(s));
}
int fibo(int n)
{ int s;
t++;
if(n==0)
{ t++;
return(0); }
else
if(n==1)
{ t++;
return(1); }
else
{ s=fibo(n-1)+fibo(n-2);
t=t+4;

16
return(s);
}
t++;
}

OUTPUT

Enter the number of elements 6


Fibonacci series
1
1
2
3
5
8
Time =194

Aposteriori analysis

N T

5 30

10 413

15 4762

20 53094

17
Algorithm mergesort(A[0...n-1])
//sorts array A[0...n-1]by recursive mergrsort
//input:an array A[0...n-1] of orderable elements
//output:array A[0...n-1]sorted in nondecreasing order

if n>1
copyA[0...n/2-1]to b[0...n/2-1]
copy A[n/2...n-1]to C[0...n/2-1]
mergesort(B[0...n/2-1])
mergesort(C[0...n/2-1])
merge(B,C,A)

Algorithm merge(B[0...p-1],C[0...q-1],A[0...p+q-1])
//merges two sorted arrays into one one sorted array
//input:arrays B[0..p-1]andC[0..q-1] both sorted
//output:sorted array A[0..p+q-1] of the elements of B and C

i←0;j←0;k←0
while i<p andj<q do
if B[i]≤C[j]
A[k]←B[i];i=i+1
Else
A[k]←C[j];j=j+1
k←k+1
if i=p
copy C[j..q-1] to A[k...p+q-1]
else
copyB[i..p-1] to A[k..p+q-1]

Apriori Analysis

18
T(n) = T(n/2)+T(n/2)+n , T(1)=1

= 2T(n/2)+n

= 2[2T(n/4)+n/2)]+n

= 22T(n/22) + n +n = 22T(n/22) +2 n

= 23T(n/23) + 3n

= 2kT(n/2k) +k n

When k= log n, n/2k = 1 so T(n/2k )=1 , n=2k

T(n) = 2log nT(1) + log n .n = n + n log n = O(n log n)

/* Program to implement merge sort algorithm and estimate the time and space
complexity*/
#include<stdio.h>
#include<stdlib.h>
mergesort(int a[100] ,int ,int);
merge(int a[100],int ,int ,int);
int t;
void main()
{ int a[100],n,i;
printf("\nEnter the number of elements in array\n");
scanf("%d",&n);
/* randomize();
for (i=0;i<n;i++)
a[i] = rand() % 100 + 1; */
printf("\nEnter the element\n");
for(i=0;i<n;i++)
a[i]=n-i;
// scanf("%d",&a[i]);
printf("\nUnsorted elements\n");

19
for(i=0;i<n;i++)
printf("\n%d\t",a[i]);
mergesort(a,0,n-1);
printf("\nsorted list\n");
for(i=0;i<n;i++)
printf("\n%d\t",a[i]);
printf("\nTime taken is %d",t);
printf(“\nspace%dbyets”,sizeof(a)+sizeof(n)+6+200);
}
mergesort(int a[100],int x,int y)
{ int mid;
if(x<y)
{
t++;
mid=(x+y)/2;
t=t+3;
mergesort(a,x,mid);
t++;
mergesort(a,mid+1,y);
t++;
merge(a,x,mid,y);
t++;
}
return 0;
}
merge(int a[100],int x,int mid,int y)
{ int i,j,k,c[100];
i=x;

20
k=x;
j=mid+1;
t=t+4;
while((i<=mid)&&(j<=y))
{ t=t+3;
if(a[i]<a[j])
{ t++;
c[k]=a[i];
k++;
i++;
t=t+3;
}
else
{ t++;
c[k]=a[j];
k++;
j++;
t=t+3;
}
}
while(i<=mid)
{ t++;
c[k]=a[i];
k++;
i++;
t=t+3;
}
while(j<=y)

21
{ t++;
c[k]=a[j];
k++;
j++;
t=t+3;
}
for(i=x;i<k;i++)
a[i]=c[i];
}

OUTPUT

Enter the number of elements in array


6
Enter the element Unsorted elements
6
5
4
3
2
1
Sorted list
1
2
3
4
5
6

22
Time=140
Space=408 bytes
Aposteriori Analysis

N Total time

5 107

10 280

15 474

20 681

25 898

30 1124

23
Algorithm Quicksort(A[0....n-1],low,high)
//this algorithm performs sorting using quicksort technique.
//input:an array with unsorted elements A[0...n-1]
//output:the sorted array.
if(low<high)then
//split the array into two subarrays
m←partition A[low...high]
quicksort(A,low,m-1)
quicksort(A,m+1,high)

Algorithm partition A(low...high)


//this algorithm partition the array using the first element as pivot element//
//input:an array A with low as left most index and high as right most index.
//output:right most position(index)should return.
pivot←A[low]
i<low
j<high+1
while(i<=j)do
{
while(A[i]<=pivot)do
i←i+1
while(A[j]>=pivot)do
j←j-1
if(i<=j)then
swap(A[i],A[j])
}
swap A[j] and pivot
return j

Apriori Analysis
Worst Case
T(n) = T(n-1) + n = T(n-2) + (n-1) + n
=… = 1 + 2 + … + n = O(n2)

Average Case
T(n) = T(n/2)+T(n/2)+n , T(1)=1

= O(n log n) (Same as Merge Sort)

24
/*Program to generate n random number and sort using quick sort
algorithm(divide and conquer) and estimate the time and space complexity*/

int t;
#include<stdio.h>
#include<stdlib.h>
int partition(int a[100],int ,int);
void quicksort(int a[100],int ,int);
void main()
{ int a[100],n,m,i,j;
printf("Enter the element in the array\n");
scanf("%d",&n);
printf("\nEnter the element\n");
// for(m=0;m<n;m++)
// scanf("%d",&a[m]);
randomize();
for(m=0;m<n;m++)
a[m]=rand()%100+1;
printf("\nUnsorted array");
for(m=0;m<n;m++)
printf("\n%d",a[m]);
i=0;
j=n-1;
printf("Sorted array");
quicksort(a,i,j);
for(m=0;m<n;m++)
printf("\n%d",a[m]);
printf("\ntime=%d,n=%d",t,n);
printf(“\n Space=%dbytes”, sizeof(a)+sizeof(n)+sizeof(m) +6);
}
void quicksort(int a[100], int i,int j)
{ int q;
t++;
if (i<j)
{ t++;
q=partition(a,i,j);
quicksort(a,i,q);
quicksort(a,q+1,j);

}
}
int partition(int a[100],int p,int r)
{ int pivot,i,j,temp;

25
t++;
pivot=a[p];
t++;
i=p;
t++;
j=r+1;
t++;
while(1)
{ while(a[i]<pivot)
{t=t+2;
i++;
}
while(a[j]>pivot)
{ t=t+2;
j--;
}

if(i<j)
{ t++;
temp=a[i];
t++;
a[i]=a[j];
t++;
a[j]=temp;
t++;
}
else
return j;
t++;

}
}

Output
Enter the element in the array 10
Unsorted array
27
21
30
24
58
72
53
82
46
75

26
Sorted array
21
24
27
30
46
53
58
72
75
82
Time=235
Space =110

Aposteriori Analysis

N T

10 100

20 400

30 900

40 1600

55 3025

27
Depth -First Search

DFS(G)

//Implement a depth -first search traversal of a given a given graph

//Input: Graph G=(V,E)

Output: Graph G with its vertices marked with consecutive integers

//in the order they've been first encounted by the DFS traversal

mark each vertex in V with 0 as a mark of being “unvisited”

count←0

for each vertex v in V do

if v is marked with 0

dfs(v)

dfs(v)

//visits recursively all the unvisited vertices connected to vertex v by a path

//and numbers them in the order they are encountered

//via global variable count

count←count+1;mark v with count

for each vertex w in V adjacent to v do

if w is marked with 0

dfs(w)

Apriori Analysis
● Each vertex marked and explored exactly once
● DFS(j) need to examine all neighbours of j
● In adjacency matrix, scan row j: n entries
● Overall O(n2)

28
/*Program to implement the graph depth first search algorithm and estimate the
time and space complexity*/

int t;
#include<stdio.h>
void DFS(int);
int G[10][10],visited[10],n;
//n is no of vertices and graph is sorted in array G[10][10]

void main()
{
int i,j;
printf("\n enter number of vertices:");
scanf("%d",&n);

//read the adjecency matrix


printf("\n enter adjecency matrix of the graph:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("path is : ");

//visited is initialized to zero


for(i=0;i<n;i++)
visited[i]=0;

DFS(0);
printf("\ntime=%d,n=%d",t);
print(“\nspace=%dbytes”,sizeof(n)+30+2);

void DFS(int i)
{
int j;
t++;
printf("\t%d",i);
visited[i]=1;
t++;
for(j=0;j<n;j++)
{ t=t+2;
if(!visited[j]&&G[i][j]==1)
{ t=t+4;
DFS(j);

29
} }}

OUTPUT

Enter number of vertices:3

Enter adjacency matrix of the graph

0 1 1

1 0 1

1 1 0

Path is : 0 1 2

Time =32

Space =34 bytes

Aposteriori Analysis

N T

3 32

4 52

5 76

6 104

7 136

30
Breadth First Search
ALGORITHM BFS(G)
//Implements a breadth-first search traversal of a given graph
//Input: Graph G = _V, E_
//Output: Graph G with its vertices marked with consecutive integers
// in the order they are visited by the BFS traversal
mark each vertex in V with 0 as a mark of being “unvisited”
count ←0
for each vertex v in V do
if v is marked with 0
bfs(v)

bfs(v)
//visits all the unvisited vertices connected to vertex v
//by a path and numbers them in the order they are visited
//via global variable count
count ←count + 1; mark v with count and initialize a queue with v
while the queue is not empty do
for each vertex w in V adjacent to the front vertex do
if w is marked with 0

31
count ←count + 1; mark w with count
add w to the queue
remove the front vertex from the queue

Apriori Analysis

● Each vertex enters Q exactly once


● If graph is connected, loop to process Q iterated n times
● For each j extracted from Q, need to examine all neighbours of j
● In adjacency matrix, scan row j: n entries
● Hence, overall O(n2)

32
/*Program to implement the graph breadth first search algorithm and space
complexity*/

int t;

#include<stdio.h>

#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v)
{ t++;
for(i=1;i<=n;i++)
{ t+=2;
if(a[v][i]&&!visited[i])
{ t=t+4;
q[++r]=i;
t=t+3;
}
if(f<=r)
{ t++;
visited[q[f]]=1;
t+=3;
bfs(q[f++]);
}
}
}
void main()
{
int v,start;
t++;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{ q[i]=0;
visited[i]=0;

}
printf("\nEnter graph data in matrix form:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the starting vertex:");
scanf("%d",&v);

33
start=v;
t++;
bfs(v);
t++;
printf("\nThe node which are reachable:");
for(i=1;i<=n;i++)
{t=t+3;
if((visited[i]))
{t++;
printf("%d\n",i);
}
}
//else
//printf("\nbfs is not possible");
printf("time=%d,n=%d",t,n);
printf(“\n Space =%dbytes”,sizeof(v)+sizeof(start)+442);
getch();
}

OUTPUT

Enter the number of vertices: 4


Enter graph data in matrix from :
0110
1011
1101
0110
Enter the starting vertex:2
The node which are reachable :1
2
3
4
Time =96

Space = bytes

Aposteriori Analysis

N T

3 70

34
4 96

5 124

6 154

7 164

Prim’s algorithm for constructing a minimum spanning tree


ALGORITHM Prim(G)
//Input: A weighted connected graph G = _V, E_
//Output: ET , the set of edges composing a minimum spanning tree of G

35
VT ← {v0} // the set of tree vertices can be initialized with any vertex

ET ← Ø

for i ←1 to |V| − 1 do

find a minimum-weight edge e∗ = (v*, u*) among all the edges (v, u)
such that v is in VT and u is in V − VT
VT←VT ∪ {u*}

ET←ET ∪ {e*}
return ET

Apriori Analysis

The algorithm’s running time will be in Θ|V2| where V is the number of vertices

/*Program to find the minimum cost spanning tree using prim’s algorithm and
estimate time space complexity*/

int t=0;
#include<stdio.h>
#include<conio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{ clrscr();
printf("\nEnter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:" );
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{ scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
visited[1]=1;
t=t++;
printf("\n");
while(ne<n)
{ t=t+2;
for(i=1,min=999;i<=n;i++)
{ t=t+3;
for(j=1;j<=n;j++)

36
{ t=t+2;
if(cost[i][j]<min)
{ t=t+2;
if(visited[i]!=0)
{ t=t+2;
min=cost[i][j];
a=u=i;
b=v=j;
t=t+6;
}
}
}
}
if(visited[u]==0||visited[v]==0)
{t=t+4;
printf("\nEdge%d:(%d%d)cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
t=t+4;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimum cost=%d",mincost);
printf("\nTime=%d",t);
printf(“\n Space =%dbytes”, sizeof(n)+124);
getch();
}

Output

Enter the number of nodes : 3


Enter the adjacency matrix :
0 10 1
10 0 6
1 6 0
Edge 1 (13)cost :1
Edge2 (32)cost :6
Minimum cost = 7
Time=117
Space =126

37
Aposteriori Analysis

N T

3 117

4 245

5 448

6 757

7 1302

38
Kruskal's algorithm for constructing a minimum spanning tree
Algorithm Kruskal (G)
//Input : A weighed connected graph g=<V,E>
//Output: ET , the set of edges composing a minimum spanning tree of G

sort E in non decreasing order of the edge weights w(ei1)<=...<=w(e)


E ←Ø; ecounter ←0 //initialize the set of tree edges and its size

k←0 //initialize the number of processed edges


while ecounter <|V|-1 do
k←k+1
if ET{eik} is acyclic
ET←ETU {eik}; ecounter←ecounter +1
return ET
Apriori Analysis

The algorithm’s running time will be in Θ|E| log |E| where V is the number of vertices

/*Program to find the minimum cost spanning tree using kruskal algorithm and
estimate the time and space complexity*/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int mincost=0,cost[9][9],parent[9];
int min;
int find(int);
int uni(int,int);
int t;
void main()
{ clrscr();
printf("\n\tImplementation of Kruskal's algorith\n");
printf("\nEnter the number of vertices:");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix:");
for(i=1;i<=n;i++)
{ for(j=1;j<=n;j++)
{ scanf("%d",&cost[i][j]);

39
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("The edges of minimum cost spanning tree are\n");
t++;
while(ne<n)
{ t++;
for(i=1,min=999;i<=n;i++)
{ t=t+3;
for(j=1;j<=n;j++)
{ t=t+2;
if(cost[i][j]<min)
{ t=t+2;
min=cost[i][j];
a=u=i;
b=v=j;
t=t+6;
}
}
}
u=find(u);
t++;
v=find(v);
t++;
if(uni(u,v))
{ t++;
printf("%d edge(%d,%d)=%d\n",ne++,a,b,min);
mincost+=min;
t++;
}
cost[a][b]=cost[b][a]=999;
t=t+4;
}
printf("\n\t Minimum cost=%d\n",mincost);
printf("\nTime=%d",t);
printf(“\nspace=%d”,sizeof(n)+104);
getch();
}
int find(int i)
{ while(parent[i])
i=parent[i];
t=t+2;
return i;
}
int uni(int i,int j)

40
{ if(i!=j)
{ parent[j]=i;
t=t+3;
return 1;
}
return 0;
}
OUTPUT

Implementation of kruskal’s algorithm


Enter the number of vertices :3
Enter the cost adjacency matrix:
0 10 1
10 0 6
1 6 0
Minimum cost=7
Time=119
Space =106

Aposteriori Analysis

N T

3 119

4 237

5 465

6 760

7 1320
Time

Input size(n)

41

You might also like