Labmannual Ada
Labmannual Ada
College of Engineering,
Ahmedabad
B.E. Semester 5
(Computer Engineering)
Faculty Details:
1) Prof. H. K. GEVARIYA
2) Prof. S. A. PATEL
3) Prof. S. R. MODI
Certificate
Place: __________
Date: __________
Institute’s Mission
To impart affordable and quality education in order to meet the needs of industries and
achieve excellence in teaching-learning process.
To create a conducive research ambience that drives innovation and nurtures research-
oriented scholars and outstanding professionals.
To collaborate with other academic & research institutes as well as industries in order to
strengthen education and multidisciplinary research.
To promote equitable and harmonious growth of students, academicians, staff, society and
industries, thereby becoming a center of excellence in technical education.
Department’s Vision
To Achieve Academic Excellence in Computer Engineering by Providing Value Based
Education.
Department’s Mission
To produce graduates according to the needs of industry, government, society and
scientific community.
To enhance the ability of students to address the real life issues by applying technical
expertise, human values and professional ethics.
To inculcate habit of using free and open source software, latest technology and soft skills
so that they become competent professionals.
To encourage faculty members to upgrade their skills and qualification through training
and higher studies at reputed universities.
Program Educational Objectives (PEOs)
Provide computing solutions of complex problems as per business and societal needs.
Procure requisite skills to pursue entrepreneurship, research and development, and
imbibe high degree of professionalism in the fields of computing.
Embrace life-long learning and remain continuously employable.
Work and excel in a highly competence supportive, multicultural and professional
environment which abiding to the legal and ethical responsibilities.
.
Graduates will be able to explore and propose effective solutions to the problems in the
area of Computer Engineering as per the needs of society and industry.
Graduates will be able to apply standard practice and strategies to develop quality software
products using modern techniques, programming skills, tools & an open ended
programming environment and work in a team.
Graduates will manifest the skills of continuous learning in the fast changing field of
Computer Engineering.
Programme Outcomes (POs)
Index
(Progressive Assessment Sheet)
Date:
Theory:
Result: Complete the below table based on your implementation of functions and time taken by
each function.
Time taken
Inputs
Loop method Equations Recursion
100
200
300
400
500
Equation
Chart:
<Draw Comparative Chart of inputs versus time taken by each algorithm>
2. If one algorithm has a growth rate of n2 and second algorithm has a growth rate of n then
which algorithm execute faster? Why?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
Theory:
Implement the program to use above sorting functions and calculate the time taken by each
functions on various inputs ranging from 1000 to 5000.
#include <stdio.h>
#include <time.h>
int main()
{
int n,temp,i,a[10],j; time_t start,end; double tc;
printf("Enter total number:"); scanf("%d",&n); for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
start=clock();
for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ if(a[i]>a[j]){
temp=a[i]; a[i]=a[j]; a[j]=temp;
}
}
}
end=clock();
for(i=0;i<n;i++){ printf("%d ",a[i]);
}
tc=difftime(end, start)/CLOCKS_PER_SEC; printf("\nTime Taken: %lf ",tc);
return 0;
}
2. Bubble Sort Program in C
Bubble sort:
#include <stdio.h>
#include <time.h>
int main(){
int n,a[10],t,i,j; time_t start,end; double tc;
printf("Enter the total number:"); scanf("%d",&n); for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
start=clock();
for(i=0;i<n-1;i++){
for(j=0;j<n-1;j++){
if(a[j]>a[j+1]){ t=a[j]; a[j]=a[j+1]; a[j+1]=t;
}
}
}
end=clock();
for(i=0;i<n;i++){ printf("%d ",a[i]);
}
tc=difftime(end, start)/CLOCKS_PER_SEC; printf("\nTime Taken: %lf ",tc);
return 0;
}
3. Insertion Sort Program in C
#include <stdio.h>
#include <time.h>
int main() {
int n,temp,i,a[10],j,k;
time_t start,end;
double tc;
printf("Enter total number:");
scanf("%d",&n);
start=clock();
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
for(k=0;k<i+1;k++)
{
for(j=k+1;j<i+1;j++)
{
if(a[k]>a[j])
{
temp=a[k];
a[k]=a[j];
a[j]=temp;
}
}
}
}
end=clock();
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
tc=difftime(end, start)/CLOCKS_PER_SEC;
printf("\nTime Taken: %lf ",tc);
return 0;
}
4. Merge Sort Program in C
#include <stdio.h>
#include <time.h>
#define max 10
int a[7]={7,6,5,4,3,2,1};
int b[10];
time_t start,end;
double tc;
int main()
{
printf("Hello");
int i;
start=clock();
sort(0,6);
end=clock();
for(i=0;i<7;i++)
{
printf("%d ",a[i]);
}
tc=difftime(end, start)/CLOCKS_PER_SEC;
printf(“\nTime Taken: %lf ",tc);
return 0;
}
5. Quick Sort Program in C
#include <stdio.h>
#include<time.h>
if(first<last)
{
pivot=first; i=first; j=last;
while(i<j)
{
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot]) j--;
if(i<j)
{
temp=number[i]; number[i]=number[j]; number[j]=temp;
}
}
temp=number[pivot]; number[pivot]=number[j]; number[j]=temp; quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main()
{
int i, count, number[25];
time_t start,end;
start=clock();
quicksort(number,0,count-1);
end=clock();
Result: Complete the below table based on your implementation of functions and time taken by
each function. Also, prepare similar tables for ascending order sorted data and descending
order sorted data.
Chart:
<Draw Comparative Charts of inputs versus time taken on various data (Random, ascending order sorted
and descending order sorted data) by each algorithm.>
Sample Chart is as below:
250000
200000
150000
100000
50000
0
100 200 300 400 500
Conclusion:
Quiz:
1. Which sorting function execute faster in case of ascending order sorted data?
Answer:
2. Which sorting function execute faster in case of descending order sorted data?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
Compare the performances of linear search and binary search for Best case, Average case and
Worst case inputs.
Date:
Objectives: (a) Identify Best, Worst and Average cases of given problem.
(b) Derive time complexity from steps count for different inputs.
Theory:
A linear search, also known as a sequential search, is a method of finding an element within a list.
It checks each element of the list sequentially until a match is found or the whole list has been
searched. A simple approach to implement a linear search is:
1. Begin with the leftmost element of arr[] and one by one compare x with each element.
2. If x matches with an element, then return the index.
3. If x does not match with any of the elements, then return -1.
Result: Complete the below table based on your implementation of sequential search algorithm
and steps executed by the function.
Prepare similar tables for Average case and Worst case of both algorithms.
Chart:
<Draw Comparative Charts of inputs versus time taken by both algorithms in various cases>
Conclusion:
Quiz:
1. Which element should be searched for the best case of binary search algorithm?
Answer:
2. Which element should be searched for the worst case of binary search algorithm?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms” by E. Horowitz et al.
Implement functions to print nth Fibonacci number using iteration and recursive method. Compare
the performance of two methods by time taken on various inputs. Also draw a comparative chart.
(Fibonacci series 1, 1, 2, 3, 5, 8….. Here 8 is the 6th Fibonacci number).
Date:
Objectives: (a) Compare the performances of two different versions of same problem.
(b) Find the time complexity of algorithms.
(C) Understand the polynomial and non-polynomial problems
Theory:
The Fibonacci series is the sequence of numbers (also called Fibonacci numbers), where every
number is the sum of the preceding two numbers, such that the first two terms are '0' and '1'. In
some older versions of the series, the term '0' might be omitted. A Fibonacci series can thus be
given as, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . It can thus be observed that every term can be
calculated by adding the two terms before it. We are ignoring initial zero in the series.
To represent any (n+1) th term in this series, we can give the expression as, Fn = Fn-1 + Fn-2. We can
thus represent a Fibonacci series as shown in the image below,
Result: Complete the below table based on your implementation of Iterative and Recursive
method and time taken by the function.
40
50
Time Complexity
Chart:
<Draw Comparative Charts of inputs versus time taken by both functions on various inputs>
Conclusion:
Quiz:
1. What is the time complexity of iterative version of Fibonacci function?
Answer:
3. Can you execute recursive version of Fibonacci function for more inputs?
Answer:
4. What do you mean by polynomial time algorithms and exponential time algorithms?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
Date:
Competency and Practical Skills: Algorithmic thinking, Programming Skills, Problem solving
Theory:
Making Change problem is to find change for a given amount using a minimum number of coins
from a set of denominations. If we are given a set of denominations D = {d0, d1, d2, …, dn} and
if we want to change for some amount N, many combinations are possible. Suppose {d1, d2, d5,
d8}, {d0, d2, d4}, {d0, d5, d7} all are feasible solutions but the solution which selects the
minimum number of coins is considered to be an optimal solution. The aim of making a change is
to find a solution with a minimum number of coins / denominations. Clearly, this is an
optimization problem.
General assumption is that infinite coins are available for each denomination. We can select any
denomination any number of times.
Sort all the denominations and start scanning from smallest to largest denomination. In every
iteration i, if current denomination di is acceptable, then 1 coin is added in solution and total
amount is reduced by amount di. Hence,
C[i, j] = 1 + (c [i, j – di])
C[i,j] is the minimum number of coins to make change for the amount j. Below figure shows the
content of matrix C.
using coins if current denomination is larger than current problem size, then we have to skip the
denomination and stick with previously calculated solution. Hence,
C[i, j] = C[i – 1, j]
If above cases are not applicable then we have to stick with choice which returns minimum
number of coin. Mathematically, we formulate the problem as,
C[i, j] = min {C[i – 1, j] , 1 + C[i, j – di]}
Algorithm MAKE_A_CHANGE(d,N)
// d[1…n] = [d1,d2,…,dn] is array of n denominations
// C[1…n, 0…N] is n x N array to hold the solution of sub problems
// N is the problem size, i.e. amount for which change is required
for i ← 1 to n do
C[i, 0] ← 0
end
for i ← 1 to n do
for j ← 1 to N do
if i = = 1 ans j < d [i] then
C[i, j] ← ∞
else if i == 1 then
C[i, j] ← 1 + C[1, j – d[1])
else if j < d [i] then
C[i, j] ← C[I – 1, j]
else
C[i, j] ← min (C[i – 1, j] ,1 + C[i, j – d[i])
end
end
end
return C[n, N]
Implement above algorithm and print the matrix C. Your program should return the
number of coins required and its denominations.
Observations:
Write observation based on whether this algorithm returns optimal answer or not on various
inputs.
Result
Write output of your program
Conclusion:
Quiz:
1. What is the time complexity of above algorithm?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
3. https://codecrucks.com/making-change-problem-using-dynamic-programming/
Date:
Competency and Practical Skills: Algorithmic thinking, Programming Skills, Problem solving
Theory:
Given a sequence of matrices A1, A2,...,An and dimensions p0, p1,...,pn where Ai is of dimension pi−1
× pi, determine the order of multiplication (represented, say, as a binary tree) that minimizes the
number of operations.
This algorithm does not perform the multiplications; it just determines the best order in which to
perform the multiplications
Two matrices are called compatible only if the number of columns in the first matrix and the
number of rows in the second matrix are the same. Matrix multiplication is possible only if they
are compatible. Let A and B be two compatible matrices of dimensions p x q and q x r
Suppose dimension of three matrices are:
A1 = 5 x 4
A2 = 4 x 6
A3 = 6 x 2
Matrix multiplication is associative. So
= 180
= 88
The answer of both multiplication sequences would be the same, but the numbers of
multiplications are different. This leads to the question, what order should be selected for a chain
of matrices to minimize the number of multiplications?
Let us denote the number of alternative parenthesizations of a sequence of n matrices by p(n).
When n = 1, there is only one matrix and therefore only one way to parenthesize the matrix. When
n ≥ 2, a fully parenthesized matrix product is the product of two fully parenthesized matrix sub-
products, and the split between the two subproducts may occur between the k and (k +
1)st matrices for any k = 1, 2, 3…, n – 1. Thus we obtain the recurrence.
The solution to the recurrence is the sequence of Catalan numbers, which grows as Ω(4n / n3/2),
roughly equal to Ω(2n). Thus, the numbers of solutions are exponential in n. A brute force attempt
is infeasible to find the solution.
Any parenthesizations of the product Ai Ai + 1 … Aj must split the product between Ak and Ak+1 for
some integer k in the range i ≤ k < j. That is for some value of k, we first compute the matrices
Ai….k and Ak + 1…j and then multiply them together to produce the final product Ai…j The cost of
computing these parenthesizations is the cost of computing Ai….k , plus the cost of computing Ak +
1…j plus the cost of multiplying them together.
We can define m[i, j] recursively as follows. If i == j, the problem is trivial; the chain consists of
only one matrix Ai…i = A. No scalar multiplications are required. Thus m[i, i] = 0 for i = 1, 2 …n.
To compute m[i, j] when i < j, we take advantage of the structure of an optimal solution of the first
step. Let us assume that the optimal parenthesizations split the product Ai Ai + 1…Aj between
Ak and Ak + 1, where i ≤ k < j. Then m[i, j] is equal to the minimum cost for computing the
subproducts Ai…k and Ak + 1…j plus the cost of multiplying these two matrices together.
Result
Write output of your program
Conclusion:
Quiz:
1. What is the time complexity of above algorithm?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
Date:
Competency and Practical Skills: Algorithmic thinking, Programming Skills, Problem solving
Theory:
The Longest Common Subsequence (LCS) problem is a classic computer science problem that
involves finding the longest subsequence that is common to two given sequences.
A subsequence is a sequence that can be derived from another sequence by deleting some or no
elements without changing the order of the remaining elements. For example, given the sequence
"ABCDE", "ACE" is a subsequence of "ABCDE", but "AEC" is not a subsequence.
Given two sequences X and Y, the LCS problem involves finding the longest common
subsequence (LCS) of X and Y. The LCS need not be contiguous in the original sequences, but it
must be in the same order. For example, given the sequences "ABCDGH" and "AEDFHR", the
LCS is "ADH" with length 3.
Naïve Method:
Let X be a sequence of length m and Y a sequence of length n. Check for every subsequence
of X whether it is a subsequence of Y, and return the longest common subsequence found. There
are 2m subsequences of X. Testing sequences whether or not it is a subsequence of Y takes O(n)
time. Thus, the naïve algorithm would take O(n2m) time.
Once the values are filled, the path is traced back from the last value in the table at T[5, 4].
Algorithm is as below:
Result
Write output of your program
Conclusion:
Quiz:
1. What is the time complexity of above algorithm?
Answer:
3. Does Dynamic programming approach to find LCS perform well compare to naïve approach?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
Date:
Competency and Practical Skills: Algorithmic thinking, Programming Skills, Problem solving
Theory:
The knapsack problem is useful in solving resource allocation problem. Let X = < x1, x2, x3, . . . . .
, xn> be the set of n items. Sets W = <w1, w2, w3, . . . , wn> and V = < v1, v2, v3, . . . , vn> are weight
and value associated with each item in X. Knapsack capacity is M unit.
The knapsack problem is to find the set of items which maximizes the profit such that collective
weight of selected items does not cross the knapsack capacity. Select items from X and fill the
knapsack such that it would maximize the profit.
Knapsack problem has two variations. 0/1 knapsack, that does not allow breaking of items. Either
add an entire item or reject it. It is also known as a binary knapsack. Fractional knapsack allows
breaking of items. Profit will be earned proportionally.
Following are the steps to implement binary knapsack using dynamic programming.
The above algorithm will just tell us the maximum value we can earn with dynamic programming.
It does not speak anything about which items should be selected. We can find the items that give
optimum result using the following algorithm.
Algorithm TRACE_KNAPSACK(w, v, M)
// w is array of weight of n items
// v is array of value of n items
// M is the knapsack capacity
SW ← { }
SP ← { }
i←n
j←M
while ( j> 0 ) do
if (V[i, j] == V[i – 1, j]) then
i←i–1
else
V[i, j] ← V[i, j] – vi
j ← j – w[i]
SW ← SW +w[i]
SP ← SP +v[i]
end
end
Implement program to solve Knapsack problem using dynamic programming.
Observations:
Write observation based on whether this algorithm returns optimal answer or not on various
inputs.
Result
Write output of your program
Conclusion:
Quiz:
1. What is the time complexity of above binary knapsack algorithm?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
Date:
Competency and Practical Skills: Algorithmic thinking, Programming Skills, Problem solving
Theory:
Knapsack problem is as stated below:
Given a set of items, each having different weight and value or profit associated with it. Find the
set of items such that the total weight is less than or equal to a capacity of the knapsack and the
total value earned is as large as possible.
Brute-force approach: The brute-force approach tries all the possible solutions with all the
different fractions but it is a time-consuming approach.
Greedy approach: In Greedy approach, we calculate the ratio of profit/weight, and accordingly, we
will select the item. The item with the highest ratio would be selected first.
Following are the steps to implement fractional knapsack using greedy design strategy.
Result
Write output of your program
Conclusion:
Quiz:
1. What is the time complexity of above knapsack algorithm?
Answer:
3. What is the time complexity solving knapsack problem using brute-force method?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
Date:
Competency and Practical Skills: Algorithmic thinking, Programming Skills, Problem solving
Theory:
Making Change problem is to find change for a given amount using a minimum number of coins
from a set of denominations. If we are given a set of denominations D = {d0, d1, d2, …, dn} and if
we want to change for some amount N, many combinations are possible. {d1, d2, d5, d8}, {d0, d2,
d4}, {d0, d5, d7} can be considered as all feasible solutions if sum of their denomination is N. The
aim of making a change is to find a solution with a minimum number of coins / denominations.
Following are the steps to solve coin change problem using greedy design technique
Result
Write output of your program
Conclusion:
Quiz:
1. What is the time complexity of above knapsack algorithm?
Answer:
4. What is the difference between the unbounded coin change problem and the limited coin
change problem?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
Date:
Competency and Practical Skills: Algorithmic thinking, Programming Skills, Problem solving
Objectives: (a) Understand how to use Kruskal's algorithm to find the minimum spanning tree.
(b) Solve the optimization based problem.
(c) Find the time complexity of the algorithm.
Theory:
In graph theory, a minimum spanning tree (MST) of an undirected, weighted graph is a tree that
connects all the vertices of the graph with the minimum possible total edge weight. In other
words, an MST is a subset of the edges of the graph that form a tree and have the smallest sum of
weights.
Result
Write output of your program
Conclusion:
Quiz:
1. What is the time complexity of krushkal’s algorithm?
Answer:
3. What data structure is typically used to keep track of the connected components in Kruskal's
algorithm?
Answer:
4. When does Kruskal's algorithm stop adding edges to the minimum spanning tree?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
Date:
Competency and Practical Skills: Algorithmic thinking, Programming Skills, Problem solving
Objectives: (a) Understand how to use Prim's algorithm to find the minimum spanning tree.
(b) Solve the optimization based problem.
(c) Find the time complexity of the algorithm.
Theory:
In graph theory, a minimum spanning tree (MST) of an undirected, weighted graph is a tree that
connects all the vertices of the graph with the minimum possible total edge weight. In other
words, an MST is a subset of the edges of the graph that form a tree and have the smallest sum of
weights.
Result
Write output of your program
Conclusion:
Quiz:
1. What is the time complexity of Prim’s algorithm?
Answer:
3. When does Prim's algorithm stop adding edges to the minimum spanning tree?
Answer:
4. What data structure is typically used to keep track of the vertices in Prim's algorithm?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
Date:
Competency and Practical Skills: Algorithmic thinking, Programming Skills, Problem solving
Theory:
Depth First Search is a graph traversal algorithm that explores as far as possible along each branch
before backtracking. It is used to search for a node or a path in a graph, and is implemented
recursively or iteratively.
The algorithm starts at a specified node and visits all the nodes in the graph by exploring each
branch as far as possible before backtracking to the previous node. When a node is visited, it is
marked as visited to prevent loops.
Conclusion:
Quiz:
1. What data structure is typically used in the iterative implementation of DFS and BFS?
Answer:
2. What is the time complexity of DFS on a graph with V vertices and E edges?
Answer:
3. What is the time complexity of BFS on a graph with V vertices and E edges?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.
Date:
Competency and Practical Skills: Algorithmic thinking, Programming Skills, Problem solving
Theory:
It is a string searching algorithm that is named after its authors Richard M. Carp and Michael O.
Rabin. This algorithm is used to find all the occurrences of a given pattern ‘P’’ in a given string
‘S’ in O(Ns + Np) time in average case, where ‘Ns’ and ‘Np’ are the lengths of ‘S’’ and ‘P’,
respectively.
We can see that “xyz” is occurring in “cxyzghxyzvjkxyz” at three positions. So, we have to print
that pattern ‘P’ is occurring in string ‘S’ at indices 1, 6, and 12.
Naive Pattern Searching (brute force) algorithm slides the pattern over text one by one and checks
for a match. If a match is found, then slide by 1 again to check for subsequent matches. This
approach has a time complexity of O(P* (S-P)).
The Rabin-Karp algorithm starts by computing, at each index of the text, the hash value of the
string starting at that particular index with the same length as the pattern. If the hash value of that
equals to the hash value of the given pattern, then it does a full match at that particular index.
Rabin Karp algorithm first computes the hash value of pattern P and first Np characters from S. If
hash values are same, we check the equality of actual strings. If the pattern is found, then it is
called hit. Otherwise, it is called a spurious hit. If hash values are not same, no need to compare
actual strings.
1. Calculate the hash value of the pattern: The hash value of the pattern is calculated using a hash
function, which takes the pattern as input and produces a hash value as output.
2. Calculate the hash values of all the possible substrings of the same length in the text: The hash
values of all the possible substrings of the same length as the pattern are calculated using the
same hash function.
3. Compare the hash value of the pattern with the hash values of all the possible substrings: If a
match is found, the algorithm checks the characters of the pattern and the substring to verify
that they are indeed equal.
4. Move on to the next possible substring: If the characters do not match, the algorithm moves on
to the next possible substring and repeats the process until all possible substrings have been
compared.
Implement the Rabin-Karp algorithm based on above steps and give different input text and
pattern to check its correctness. Also, find the time complexity of your implemented
algorithm.
Observations:
Write observation based on whether this algorithm able to find a pattern in a given text or not and
find it’s time complexity in worst case and average case based on its way of working.
Result
Write output of your program
Conclusion:
Quiz:
1. What is the Rabin-Karp algorithm used for?
Answer:
2. What is the time complexity of the Rabin-Karp algorithm in the average case?
Answer:
3. What is the main advantage of the Rabin-Karp algorithm over the brute force algorithm for
string matching?
Answer:
Suggested Reference:
1. "Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
and Clifford Stein
2. “Fundamentals of Algorithms”by E. Horowitz et al.