0% found this document useful (0 votes)
14 views37 pages

DAA - Lab Manual

The document is a lab manual for the DAA Lab course (E1UA306B) offered in the BCA 3rd semester at Galgotias University, detailing the course structure, faculty information, vision and mission statements, course outcomes, program outcomes, and program educational objectives. It includes a list of experiments focusing on various sorting and algorithm techniques, along with their objectives, prerequisites, and algorithms. The manual also outlines the assessment pattern and provides software and hardware requirements for the course.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views37 pages

DAA - Lab Manual

The document is a lab manual for the DAA Lab course (E1UA306B) offered in the BCA 3rd semester at Galgotias University, detailing the course structure, faculty information, vision and mission statements, course outcomes, program outcomes, and program educational objectives. It includes a list of experiments focusing on various sorting and algorithm techniques, along with their objectives, prerequisites, and algorithms. The manual also outlines the assessment pattern and provides software and hardware requirements for the course.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

LAB MANUAL

E1UA306B: DAA LAB

LTP 0 0 2
Course Type Core
Semester Offered BCA 3rd Sem

Faculty Details:
Name Dr. Vikas Chaudhary
Designation Professor
School School of Computer Applications and Technology

___________________
Vision and Mission
SCHOOL OF COMPUTER APPLICATIONS AND TECHNOLOGY

VISION AND MISSION OF GALGOTIAS UNIVERSITY

Vision
 To be known globally for value-based education, research, creativity and innovation

Mission

 Establish state-of-the-art facilities for world class education and research.


 Collaborate with industry and society to align the curriculum.
 Involve in societal outreach programs to identify concerns and provide sustainable
ethical solutions.
 Encourage life-long learning and team-based problem solving through an enabling
environment.

VISION AND MISSION OF DEPARTMENT

Vision
To be recognized globally as a premier School of Computer Applications and Technology imparting
quality and value based education engaged in multi-disciplinary and collaborative research.

Mission
The mission of the department is to:

M1: Developing a strong foundation in fundamentals of computer applications with responsiveness


towards emerging technologies.

M2: Establishing state-of-the-art facilities and adopt education 4.0 practices to analyze, develop, test
and deploy sustainable ethical IT solutions by involving multiple stakeholders.

M3: Establishing Centers of Excellence for multidisciplinary collaborative research in association


with industry and academia.
Course Outcomes, PO, PEO,

PSO and Syllabus


COURSE OUTCOMES (COs):

Course outcomes (COs)

CO1 Describe basic techniques for designing algorithms, including the techniques of
recursion, divide-and-conquer, and greedy.

CO2
Analyze algorithmic complexity for efficient problem-solving.

CO3
Develop problem-solving skills through algorithmic approaches.

CO4
Apply classical sorting, searching, optimization and graph algorithms.

PROGRAMME OUTCOMES (PO)


PO1: The program enhances analytical, managerial, communication and computing Application skills
besides inculcating the virtues of self-study.

PO2: Analyze and synthesis computing systems through quantitative and qualitative techniques.

PO3: Design and develop computer programs in the areas related to algorithm, web design, networking
and AI.

PO4: Inculcating essential skills as demanded by Indian and Global Software industries through latest
tools of learning. This also includes team-building skills, audio- visual presentations and personality
development programs.

PO5: To develop inter-twining competence in the field of Digital Marketing and Commerce, Computing
Skill and Computational tools.

PO6: To Develop practical skills to provide solutions to industry, society and business.

PO7: Understand environmental issues and lead a life with concerns for environment.

PO8: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
computing science practice.

PO9: To make graduates understand cross cultural, societal, professional, legal and ethical issues
prevailing in industry.

PO10: Communicate effectively in both verbal and written form.

PO11: To apply standard software engineering practices and strategies in software project development
using open source programming environment to deliver a quality of product for business success

PO12 Recognize the need for lifelong learning for continuous enhancement and up gradation of
technological changes in society.
PROGRAM EDUCATIONAL OBJECTIVES

The Graduates of Computer Application shall:

PEO1: be engaged with leading Global Software Services companies handling projects in
contemporary technologies.

PEO2: serve in technical or managerial roles at Government firms, Corporates and contributing to the
society as successful entrepreneurs through startup.

PEO3: undertake higher education at institutions of transnational reputation.

Programme Specific Outcome (PSO)

The students of Computer Application shall:

PSO1: Have the ability to work with emerging technologies in computing requisite to Industry 4.0.

PSO2: Demonstrate application development skills learned through technical training and projects tosolve
real world problems

EXPERIMENTAL SETUP DETAILS FOR THE COURSE


Software Requirements
 Turbo C 2.0/ Turbo C++3.0+

Hardware Requirements
 No specific requirements. Any computer Hardware capable of running DOS can be
used for this course.
LIST OF EXPERIMENTS

S. Title of Lab Experiments


No.

1 Write a program to sort given set of numbers in ascending/descending order using


Bubble sort and also search a number using binary search.

2 Write a program to sort given set of numbers in ascending/descending order using


Insertion sort and also search a number using linear search.

3 Write a program to sort given set of numbers in ascending/descending order using


Quick sort and any other sorting algorithm. Also record the time taken by these two
programs and compare them.

4 Write a program to sort given set of numbers using Heap sort.

5 Write a program to sort given set of numbers Merge Sort.

6 Write a program to sort given set of numbers Counting Sort.

7 Write a program to implement Matrix Chain Multiplication.

8 Write a program to implement Knapsack using Greedy technique.

9 Write a program to implement Knapsack using Dynamic programming.

10 Write a program to implement Dijkstra’s Algorithm.

11 Write a program to implement Bellman-Ford Algorithm.

12 Write a program to implement n-Queen Problem using backtracking.

13 Write a program to implement Naïve string-matching algorithm.

14 Write a program to implement String Matching using Rabin-Karp algorithm.


Lesson Plan
Lec. Duration(in Proposed
Points To Covered Co Mapping
No minute) Date
Write a program to sort given set of numbers
in ascending/descending order using Bubble
1 100 CO1
sort and also search a number using binary
search.
Write a program to sort given set of numbers
in ascending/descending order using Insertion
2 100 CO1
sort and also search a number using linear
search.
Write a program to sort given set of numbers
in ascending/descending order using Quick
3 100 sort and any other sorting algorithm. Also CO1
record the time taken by these two programs
and compare them.
Write a program to sort given set of numbers
4 100 CO1
using Heap sort.
Write a program to sort given set of numbers
5 100 CO2
Merge Sort.
Write a program to sort given set of numbers
6 100 Counting Sort. CO2

Write a program to implement Matrix Chain


7 100 CO2
Multiplication.
Write a program to implement Knapsack using
8 100 CO2
Greedy technique.
Write a program to implement Knapsack using
9 100 Dynamic programming. CO4

Write a program to implement Dijkstra’s


10 100 CO4
Algorithm.
Write a program to implement Bellman-Ford
11 100 Algorithm. CO4

Write a program to implement n-Queen


12 100 CO4
Problem using backtracking.
Write a program to implement Naïve string-
13 100 CO4
matching algorithm.
Write a program to implement String Matching
14 100 CO4
using Rabin-Karp algorithm.
ASSESSMENT PATTERN FOR INTEGRATED (BLENDED) COURSE:

CIE Total Marks


Type of Course (B) Final Marks
LAB
Work@ MT LAB CI SEE CIE*0.5+SEE*
E EXAM* E
+ Record 0.5
INTEGRATED 25 50 25 100 100 100
@Lab Work-15 marks + Lab Record-10 marks
Experiment No:1

Title Write a program to sort given set of numbers in ascending/descending order using
Bubble sort and also search a number using binary search.

Objective 1. To study and Implement Bubble Sort Algorithm


2. To study and Implement Binary Search Algorithm

Pre Knowledge of
requisite • Array Data Structure
Algorithm Bubble Sort Algorithm:

Input to the function is array A: The array to be sorted


procedure bubble Sort (A: list of sort able items)
repeat
swapped = false
for i = 1 to length(A) - 1 inclusive do:
/* if this pair is out of order */
if A[i-1] > A[i] then
/* swap them and remember something changed */
Swap (A[i-1], A[i])
swapped = true
end if
end for
until not swapped
end procedure

Binary Search Algorithm:

Input to the algorithm is A: Array in which key is to searched, key: the key is
to searched, imin: lower index of array, imax: upper index of array. int
binary_search(int A[],int key,int imin,int imax)
{
// test if array is empty
if(imax < imin)
// set is empty, so return value showing not found
return KEY_NOT_FOUND;
else
{
// calculate midpoint to cut set in half
int imid = midpoint(imin, imax);

// three-way comparison
if(A[imid]> key)
// key is in lower subset
return binary_search(A, key, imin, imid-1);
elseif(A[imid]< key)

// key is in upper subset


return binary_search(A, key, imid+101, imax);
else
// key has been found
return imid;
}
}
Sample Out
put
Experiment No:2

Title Write a program to sort given set of numbers in ascending/descending order using
Insertion sort and also search a number using linear search.

Objective 1. .To study and Implement Insertion Sort Algorithm


2. .To study and Implement Linear Search Algorithm

Pre-requi Knowledge of
site • Array Data Structure

Algorithm Insertion Sort Algorithm:

Input to the function is array A: The array to be sorted


for i ← 1 to length(A)
x ← A[i]
j←i
while j > 0 and A[j-1] > x
A[j] ← A[j-1]
j←j-1
A[j] ← x

Linear Search Algorithm:

Input to the algorithm is A: Array in which key is to searched, x: the key is


to searched
LinearSearch(A, x)
Set i to n.
Repeat this loop:
If i< 0, then exit the loop.
If A[i] = x, then exit the loop.
Set i to i − 1.
Return i.
If returned value is –ve then it means item not found otherwise search successful at
lo cation i.
Sample
Output
Experiment No:3

Title Write a program to sort given set of numbers in ascending/descending order using
Quick sort and any other sorting algorithm. Also record the time taken by these two
programs and compare them.

Objective To study and Implement Sort Algorithm

Pre-requi Knowledge of
site • Array Data Structure
• Divide and Conquer Technique

Algorithm Quick Sort Algorithm:

Input to the function is array A: The array to be sorted


The following procedure implements quick sort.
QUICKSORT(A, p, r)
1 if p < r
2 then q ← PARTITION(A, p, r)
3 QUICKSORT(A, p, q − 1)
4 QUICKSORT(A, q + 1, r)

To sort an entire array A, the initial call is QUICKSORT (A, 1,


length[A]). Partitioning the array
The key to the algorithm is the PARTITION procedure, which rearranges the
subarray A [p . . . r] in place.
PARTITION(A, p, r)
1 x ← A[r]
2i←p−1
3 for j ← p to r − 1
4 do if A[ j ] ≤ x
5 then i ←i + 1
6 exchange A[i ] ↔ A[ j ]
7 exchange A[i + 1] ↔ A[r]
8 return i + 1

Sample
Output
Experiment No:4

Title Write a program to sort given set of numbers using Heap sort.

Objective To study and Implement Heap Sort Algorithm.

Pre-req Knowledge of
uisite • Array Data Structure
• Tree
Algori The heap sort algorithm can be divided into two parts.
thm In the first step, a heap is built out of the data.
In the second step, a sorted array is created by repeatedly removing the largest
element from the heap, and inserting it into the array. The heap is reconstructed after
each re moval. Once all objects have been removed from the heap, we have a sorted
array. The direction of the sorted elements can be varied by choosing a min-heap or
max-heap in step one.
Input:- A is the array to be sorted
HEAPSORT(A)

1 BUILD-MAX-HEAP(A)
2 for i ← length[A] down to 2
3 do exchange A[1] ↔ A[i ]
4 heap-size[A] ← heap-size[A] − 1
5 MAX-HEAPIFY(A, 1)
MAX-HEAPIFY are an important subroutine for manipulating max-heaps. Its inputs
are an array A and an index i into the array. When MAX-HEAPIFY is called, it is
assumed that the binary trees rooted at LEFT(i ) and RIGHT(i ) are max-heaps, but
that A[i ] may be smaller than its children, thus violating the max-heap property. The
function of MAX
HEAPIFY is to let the value at A[i ] “float down” in the maxheap
So that the subtree rooted at index i become a max-heap.

MAX-HEAPIFY(A, i )
1 l ← LEFT(i )
2 r ← RIGHT(i )
3 if l ≤ heap-size[A] and A[l] > A[i ]
4 then largest ←l
5 else largest ←i
6 if r ≤ heap-size[A] and A[r] > A[largest]
7 then largest ←r
8 if largest _= i
9 then exchange A[i ] ↔ A[largest]
10 MAX-HEAPIFY(A, largest)

BUILD-MAX-HEAP(A)
1 heap-size[A] ← length[A]
2 for i ← _length[A]/2down to 1
3 do MAX-HEAPIFY(A, i )
Sample
Output
Experiment No:5

Title Write a program to sort given set of numbers Merge Sort.

Objective To study and Implement Merge Sort Algorithm

Pre-requi Knowledge of
site • Array Data Structure
• Divide and Conquer Technique

Algorithm Merge Sort Algorithm:

Input to the function is array A: The array to be sorted

MERGE-SORT(A, p, r)
1 if p < r
2 then q ← _(p + r)/2_
3 MERGE-SORT(A, p, q)
4 MERGE-SORT(A, q + 1, r)
5 MERGE(A, p, q, r)

MERGE(A, p, q, r)
1 n1 ← q − p + 1
2 n2 ←r − q
3 create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]
4 for i ← 1 to n1
5 do L[i ] ← A[p + i − 1]
6 for j ← 1 to n2
7 do R[ j ]← A[q + j ]
8 L[n1 + 1]←infinity
9 R[n2 + 1]←infinity
10 i ← 1
11 j ← 1
12 for k ← p to r
13 do if L[i ] ≤ R[ j ]
14 then A[k] ← L[i ]
15 i ← i + 1
16 else A[k] ← R[ j ]
17 j ← j + 1
Sample Out
put
Experiment No:6

Title Write a program to sort given set of numbers Counting Sort.

Objective To study and Implement Counting Sort Algorithm

Pre-requi Knowledge of
site • Array Data Structure

Algorithm Insertion Sort Algorithm:

Input to the function is array A: The array to be sorted


In the code for counting sort, we assume that the input is an array A [1 . . . n], and
Thus length [A] = n. We require two other arrays: the array B [1. . . n] holds the
sorted output, and the array C[0 . . k] provides temporary working storage.
COUNTING-SORT(A, B, k)
1 for i ← 0 to k
2 do C[i ] ← 0
3 for j ← 1 to length[A]
4 do C[A[ j ]] ← C[A[ j ]] + 1
5 C[i] now contains the number of elements equal to i .
6 for i ← 1 to k
7 do C[i ] ← C[i ] + C[i − 1]
8 C[i] now contains the number of elements less than or equal to
i . 9 for j ← length[A] down to 1
10 do B[C[A[ j ]]] ← A[ j ]
11 C[A[ j ]] ← C[A[ j ]] − 1

Sample Out
put
Experiment No:7

Title Write a program to implement Matrix Chain Multiplication.

Objective To study and Implement Matrix chain multiplication problem.

Pre-requi Knowledge of
site • Dynamic Programming
Algorithm Matrix-chain-multiplication Problem:-
The way we parenthesize a chain of matrices can have a dramatic impact on the
cost of evaluating the product. Consider first the cost of multiplying two matrices.
The stand ard algorithm is given by the following pseudocode. The attributes rows
and columns are the numbers of rows and columns in a matrix.

MATRIX-MULTIPLY(A, B)
1 if columns[A] _= rows[B]
2 then error “incompatible dimensions”
3 else for i ← 1 to rows[A]
4 do for j ← 1 to columns[B]
5 do C[i, j ]← 0
6 for k ← 1 to columns[A]
7 do C[i, j ] ← C[i, j ] + A[i, k] · B[k, j ]
8 return C

We can multiply two matrices A and B only if they are compatible: the number of
columns of A must equal the number of rows of B. If A is a p ×q matrix and B is a
q ×r matrix, the resulting matrix C is a p ×r matrix. The time to compute C is
dominated by the number of scalar multiplications in line 7, which is pqr.

MATRIX-CHAIN-ORDER(p)
1 n ← length[p] − 1
2 for i ← 1 to n
3 do m[i, i ] ← 0
4 for l ← 2 to n \\ l is the chain length.
5 do for i ← 1 to n − l + 1
6 do j ←i + l − 1
7 m[i, j ]←infinity
8 for k ←i to j − 1
9 do q ← m[i, k] + m[k + 1, j ] + pi−1pk pj
10 if q < m[i, j ]
11 then m[i, j ]← q
12 s[i, j ] ← k
13 return m and s

The algorithm first computes m [i, i]← 0 for i = 1, 2. . . n (the minimum costs for
chains of length 1) in lines 2–3. During the first execution of the loop in lines 4–12.
The second time through the loop, it computes m [i, i +2] for i = 1, 2. . . n−2 (the
minimum costs for chains of length l = 3), and so forth. At each step, the m [i, j]
cost computed in lines 9–12 depends only on table entries m [i, k] and m [k + 1, j ]
already computed.
Sample Out
put
Experiment No:8

Title Write a program to implement Knapsack using Greedy technique.

Objec To study and Implement Knapsack Algorithm.


tive

Pre Knowledge of
requi • Array Data Structure
site • Greedy Programming

Algo Knapsack Problem:


• Two main kinds of Knapsack Problems:
rithm
1. 0-1 Knapsack:
▪ N items (can be the same or different)
▪ Have only one of each
▪ Must leave or take (i.e. 0-1) each item (e.g. ingots of gold)
▪ DP works, greedy does not
2. Fractional Knapsack:
▪ N items (can be the same or different)
▪ Can take fractional part of each item (eg bags of gold dust)
▪ Greedy works and DP algorithms work
Fractional Knapsack: Greedy Solution
• Algorithm:
o Assume knapsack holds weight W and items have value v i and weight wi
o Rank items by value/weight ratio: v i / wi
▪ Thus: vi / wi ≥ vj / wj, for all i ≤ j
o Consider items in order of decreasing ratio
o Take as much of each item as possible
• Example: Knapsack Capacity W = 30 and
Item A B C D
Value 50 140 60 60
Size 5 20 10 12
Ratio 10 7 6 5
• Solution:
o All of A, all of B, and ((30-25)/10) of C (and none of D)
o Size: 5 + 20 + 10*(5/10) = 30
o Value: 50 + 140 + 60*(5/10) = 190 + 30 = 220
Sample
Output
Experiment No:9

Title Write a program to implement Knapsack using Dynamic programming.

Objective .To study and Implement Knapsack Algorithm.

Pre-requi Knowledge of
site • Array Data Structure
• Dynamic Programming

Algorithm Knapsack Problem:


• Two main kinds of Knapsack Problems:
1. 0-1 Knapsack:
▪ N items (can be the same or different)
▪ Have only one of each
▪ Must leave or take (i.e. 0-1) each item (e.g. ingots of gold)
▪ DP works, greedy does not
2. Fractional Knapsack:
▪ N items (can be the same or different)
▪ Can take fractional part of each item (eg bags of gold dust)
▪ Greedy works and DP algorithms work
0-1 Knapsack: Dynamic Solution
Here is a dynamic programming algorithm to solve the 0-1 Knapsack problem:

Input: S, a set of n items as described earlier, W the total weight of the knapsack.
(Assume that the weights and values are stored in separate arrays named w and v,
re spectively.)

Output: The maximal value of items in a valid knapsack.

int w, k;
for (w=0; w <= W; w++)
B[w] = 0
for (k=0; k<n; k++) {
for (w = W; w>= w[k]; w--) {
if (B[w – w[k]] + v[k]> B[w])
B[w] = B[w – w[k]] + v[k]
}
}
Sample Out
put
Experiment No:10

Title Write a program to implement Dijkstra’s Algorithm.

Objective To study and Implement Dijkstra’s Algorithm.

Pre-requi Knowledge of
site • Tree Data Structure
• Graph

Algorithm Dijkstra’s Algorithm:


Dijkstra’s algorithm solves the single-source shortest-paths problem on a weighted,
directed graph G = (V, E) for the case in which all edge weights are nonnegative.
Dijks tra’s algorithm maintains a set S of vertices whose final shortest-path weights
from the source s have already been determined. The algorithm repeatedly selects
the vertex u € V − S with the minimum shortest-path estimate, adds u to S, and
relaxes all edges leaving u. In the following implementation, a min-priority queue
Q of vertices is used, keyed by their d values.
Inputs:
G- The Graph
w- weight matrix
s- source vertex

DIJKSTRA(G,w, s)
1 INITIALIZE-SINGLE-SOURCE(G, s)
2 S ← NULL
3 Q ← V[G]
4 while Q != NULL
5 do u ← EXTRACT-MIN(Q)
6 S ← S UNION {u}
7 for each vertex v € Adj[u]
8 do RELAX(u, v,w)

INITIALIZE-SINGLE-SOURCE(G, s)
1 for each vertex v €V[G]
2 do d[v]←∞
3 π[v]← NIL
4 d[s] ← 0

RELAX(u, v,w)
1 if d[v] > d[u] + w(u, v)
2 then d[v] ← d[u] + w(u, v)
3 π[v]← u
Sample Out
999 is representing infinity. It means no paths exist.
put 0 in the input cost matrix denotes no direct paths exist.
Experiment No:11

Title Write a program to implement Bellman-Ford Algorithm.

Objective To study and Implement Dijkstra’s Algorithm.

Pre-requi Knowledge of
site • Tree Data Structure
• Graph

Algorithm Bellman-Ford Algorithm:


The Bellman-Ford algorithm solves the single-source shortest-paths problem in the
general case in which edge weights may be negative. Given a weighted, directed
graph G = (V, E) with source s and weight function w : E → R, the Bellman-Ford
algorithm returns a Boolean value indicating whether or not there is a negative-
weight cycle that is reachable from the source. If there is such a cycle, the
algorithm indicates that no solution exists. If there is no such cycle, the algorithm
produces the shortest paths and their weights. The algorithm uses relaxation,
progressively decreasing an estimate d[v] on the weight of a shortest path from the
source s to each vertex v € V until it achieves the actual shortest-path weight δ(s,
v). The algorithm returns TRUE if and only if the graph contains no negative-
weight cycles that are reachable from the source.
BELLMAN-FORD(G,w, s)
1 INITIALIZE-SINGLE-SOURCE(G, s)
2 for i ← 1 to |V[G]| − 1
3 do for each edge (u, v) € E[G]
4 do RELAX(u, v,w)
5 for each edge (u, v) € E[G]
6 do if d[v] > d[u] + w(u, v)
7 then return FALSE
8 return TRUE

INITIALIZE-SINGLE-SOURCE(G, s)
1 for each vertex v € V[G]
2 do d[v]←∞
3 π[v]← NIL
4 d[s] ← 0

RELAX(u, v, w)
1 if d[v] > d[u] + w(u, v)
2 then d[v] ← d[u] + w(u, v)
3 π[v]← u
Experiment No:12

Title Write a program to implement n-Queen Problem using backtracking.

Objective .To study and Implement N-Queen Problem

Pre-requisite Knowledge of
• Array Data Structure
• Backtracking

Algorithm/Th n-Queen Problem :


The n-queens problem consists in placing n non-attacking queens on an n-by-
e n chess board. A queen can attack another queen vertically, horizontally, or
ory
diag onally. E.g. placing a queen on a central square of the board blocks the
row and column where it is placed, as well as the two diagonals (rising and
falling) at whose intersection the queen was placed.
The algorithm to solve this problem uses backtracking, but we will unroll the
recursion. The basic idea is to place queens column by column, starting at the
left. New queens must not be attacked by the ones to the left that have already
been placed on the board. We place another queen in the next column if a con
sistent position is found. All rows in the current column are checked. We
have found a solution if we placed a queen in the rightmost column.
Following is a solution for 4 Queen problem.
Sample Output Enter the no. of queens:- 4

The solution is:-


.Q..

...Q

Q...

..Q.

The solution is:-


..Q.

Q...

...Q

.Q..
Experiment No:13

Title Write a program to implement Naive string-matching algorithm.

Objective To study and Implement Naive string-matching algorithm.

Pre-requi Knowledge of
site • String

Algorithm/ The simplest and least efficient way to see where one string occurs inside another is to
Theory check each place it could be, one by one, to see if it's there. So first we see if there's a copy
of the needle in the first character of the haystack; if not, we look to see if there's a copy of
the needle starting at the second character of the haystack; if not, we look starting at the
third character, and so forth. In the normal case, we only have to look at one or two
characters for each wrong position to see that it is a wrong position, so in the average case,
this takes O(n + m) steps, where n is the length of the haystack and m is the length of the
needle; but in the worst case, searching for a string like "aaaab" in a string like
"aaaaaaaaab", it takes O(nm)

Sample Out
put
Experiment No:14

Title Write a program to implement String Matching using Rabin-Karp algorithm.

Objective To study and Implement String Matching using Rabin-Karp algorithm

Pre-requisite Knowledge of
• String Data Structure

Algo The Rabin–Karp algorithm seeks to speed up the testing of equality of the pattern
to the substrings in the text by using a hash function. A hash function is a
rithm/Theory function which converts every string into a numeric value, called its hash value;
for example, we might have hash ("hello") =5. Rabin–Karp exploits the fact that
if two strings are equal, their hash values are also equal. Thus, it would seem all
we have to do is compute the hash value of the substring we're searching for, and
then look for a sub string with the same hash value.
However, there are two problems with this. First, because there are so many
different strings, to keep the hash values small we have to assign some strings the
same num ber. This means that if the hash values match, the strings might not
match; we have to verify that they do, which can take a long time for long
substrings. Luckily, a good hash function promises us that on most reasonable
inputs, this won't happen too of ten, which keeps the average search time good.
The algorithm is as shown:

function RabinKarp(string s[1..n], string sub[1..m])


hsub := hash(sub[1..m]); hs := hash(s[1..m])
for i from 1 to n-m+1
if hs = hsub
if s[i..i+m-1] = sub
return i
hs := hash(s[i+1..i+m])
return not found

You might also like