Aoa Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

SUMAN EDUCATIONAL TRUST’S

DILKAP RESEARCH INSTITUTE OF ENGINEERING AND


MANAGEMENT STUDIES
Village Mamdapur, Post Neral, Tal: -Karjat, Dist Raigad – 410101

DEPARTMENT OF COMPUTER ENGINEERING

LAB MANUAL

Analysis of Algorithm
Class SE Sem IV

Prepared By

Swati Shelar

2024-2025
List of Experiment

SR NO NAME OF THE EXPERIMENT

1 Implementation of Selection Sort

2 Implementation of Insertion Sort

3 Implementation of Merge Sort

4 Implementation of Quick Sort

5 Implementation of Binary Search

6 Implementation of The Naïve string-matching Algorithms

7 Implementation of The Knuth-Morris-Pratt algorithm

8 Implementation of N-queen problem

9 Implementation of Minimum cost Spanning tree- Prim’s


Algorithm
10 Implementation of Longest Common Subsequence
Experiment No 1 . SELECTION SORT

Aim: To Implement Program for Selection Sort.

Description:

Selection sort is a simple and efficient sorting algorithm that works by


repeatedly selecting the smallest (or largest) element from the
unsorted portion of the list and moving it to the sorted portion of the
list. This process is repeated for the remaining unsorted portion until
the entire list is sorted. Lets consider the following array as an
example: arr[] = {64, 25, 12, 22, 11}.

First pass:
 For the first position in the sorted array, the whole array is traversed
from index 0 to 4 sequentially. The first position where 64 is stored
presently, after traversing whole array it is clear that 11 is the
lowest value.
 Thus, replace 64 with 11. After one iteration 11, which happens to
be the least value in the array, tends to appear in the first position
of the sorted list.

Second Pass:
 For the second position, where 25 is present, again traverse the rest
of the array in a sequential manner.
 After traversing, we found that 12 is the second lowest value in the
array and it should appear at the second place in the array, thus
swap these values.

Third Pass:
 Now, for third place, where 25 is present again traverse the rest of
the array and find the third least value present in the array.
 While traversing, 22 came out to be the third least value and it
should appear at the third place in the array, thus swap 22 with
element present at third position.
Fourth pass:
 Similarly, for fourth position traverse the rest of the array and find
the fourth least element in the array
 As 25 is the 4th lowest value hence, it will place at the fourth
position.

Fifth Pass:
 At last the largest value present in the array automatically get
placed at the last position in the array.
 The resulted array is the sorted array.

Complexity Analysis of Selection Sort

Time Complexity:
The time complexity of Selection Sort is O(N2) as there are two nested
loops:
 One loop to select an element of Array one by one = O(N)
 Another loop to compare that element with every other Array
element = O(N)
 Therefore overall complexity = O(N) * O(N) = O(N*N) = O(N )
2

Auxiliary Space: O(1) as the only extra memory used is for temporary
variables while swapping two values in Array. The selection sort never
makes more than O(N) swaps and can be useful when memory writing
is costly.
Advantages of Selection Sort Algorithm

 Simple and easy to understand.


 Works well with small datasets.

Disadvantages of the Selection Sort Algorithm

 Selection sort has a time complexity of O(n^2) in the worst and


average case.
 Does not work well on large datasets.
 Does not preserve the relative order of items with equal keys which
means it is not stable.

PROGRAM :

#include<stdio.h>
#include <conio.h>
int main()
{
int a[100], number, i, j, temp;
printf("\n Please Enter the total Number of Elements : ");
scanf("%d", &number);
printf("\n Please Enter the Array Elements : ");
for(i = 0; i < number; i++)
scanf("%d", &a[i]);

for(i = 0; i < number; i++) {


for(j = i + 1; j < number; j++) {
if(a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("\n Selection Sort Result : ");
for(i = 0; i < number; i++) {
printf(" %d \t", a[i]);
}
printf("\n");
return 0;
}
OUTPUT :

Conclusion: Thus we have Studied Selection Sort.


Experiment No. 2 : Insertion sort

Aim : To Implement Insertion sort

Description:

This is an in-place comparison-based sorting algorithm. Here, a sub-list


is maintained which is always sorted. For example, the lower part of an
array is maintained to be sorted. An element which is to be 'insert'ed in
this sorted sub-list, has to find its appropriate place and then it has to
be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and
inserted into the sorted sub-list (in the same array). This algorithm is
not suitable for large data sets as its average and worst case.

Algorithm :

The simple steps of achieving the insertion sort are listed as follows -

Step 1 - If the element is the first element, assume that it is already


sorted. Return 1.

Step2 - Pick the next element, and store it separately in a key.

Step3 - Now, compare the key with all elements in the sorted array.

Step 4 - If the element in the sorted array is smaller than the current
element, then move to the next element. Else, shift greater elements in
the array towards the right.

Step 5 - Insert the value.

Step 6 - Repeat until the array is sorted.

Time Complexity :
Case Time Complexity

Best Case O(n)


Average Case O(n2)

Worst Case O(n2)

Space Complexity O(1)

Program :
#include <stdio.h>
int main()
{
int a[100], number, i, j, temp;

printf("\n Please Enter the total Number of Elements : ");


scanf("%d", &number);

printf("\n Please Enter the Array Elements : ");


for(i = 0; i < number; i++)
scanf("%d", &a[i]);

for(i = 1; i <= number - 1; i++)


{
for(j = i; j > 0 && a[j - 1] > a[j]; j--)
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
printf("\n Insertion Sort Result : ");
for(i = 0; i < number; i++)
{
printf(" %d \t", a[i]);
}
printf("\n");
return 0;
}
OUTPUT :

Conclusion: Thus we have Studied Insertion Sort


Experiment No. 3 : Merge Sort

Aim : To Implement Merge sort

Description:

The “Merge Sort” uses a recursive algorithm to achieve its results. The
divide-and-conquer algorithm breaks down a big problem into smaller,
more manageable pieces that look similar to the initial problem. It then
solves these subproblems recursively and puts their solutions together
to solve the original problem.

What Is a Divide and Conquer Algorithm?

Divide-and-conquer recursively solves subproblems; each subproblem


must be smaller than the original problem, and each must have a base
case. A divide-and-conquer algorithm has three parts:

 Divide up the problem into a lot of smaller pieces of the same


problem.
 Conquer the subproblems by recursively solving them. Solve the
subproblems as base cases if they're small enough.
 To find the solutions to the original problem, combine the solutions
of the subproblems.

How to Implement the Merge Sort Algorithm?


 It splits the input array in half, calls itself for each half, and then
combines the two sorted parts. Merging two halves is done with
the merge() method. Merge (array[], left, mid, right) is a crucial
 process that assumes array[left..mid] and array[mid+1..right] are
both sorted sub-arrays and merges them into one.
Algorithm:

Step 1: Start
Step 2: Declare an array and left, right, mid variable
Step 3: Perform merge function.
mergesort(array,left,right)
mergesort (array, left, right)
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
Step 4: Stop

Time Complexity: O(nlog(n))

Advantages of the Merge Sort?

 Merge sort can efficiently sort a list in O(n*log(n)) time.


 Merge sort can be used with linked lists without taking up any more
space.
 A merge sort algorithm is used to count the number of inversions in
the list.
 Merge sort is employed in external sorting.

 What Are the Drawbacks of the Merge Sort?

 For small datasets, merge sort is slower than other sorting


algorithms.
 For the temporary array, mergesort requires an additional space of
O(n).
 Even if the array is sorted, the merge sort goes through the entire
process.
Program :

#include<stdio.h>

#include<conio.h>

int a[50];

void merge(int,int,int);

void merge_sort(int low,int high)

int mid;

if(low<high)

mid=(low+high)/2;

merge_sort(low,mid);

merge_sort(mid+1,high);

merge(low,mid,high);

void merge(int low,int mid,int high)

int h,i,j,b[50],k;

h=low;

i=low;
j=mid+1;

while((h<=mid)&&(j<=high))

if(a[h]<=a[j])

b[i]=a[h];

h++;

else

b[i]=a[j];

j++;

i++;

if(h>mid)

for(k=j;k<=high;k++)

b[i]=a[k];

i++;

}
}

else

for(k=h;k<=mid;k++)

b[i]=a[k];

i++;

for(k=low;k<=high;k++) a[k]=b[k];

int main()

int num,i;

printf("\t\t\tMERGE SORT\n");

printf("\nEnter the total numbers: ");

scanf("%d",&num);

printf("\nEnter %d numbers: \n",num);

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

scanf("%d",&a[i]);

}
merge_sort(1,num);

printf("\nSORTED ORDER: \n");

for(i=1;i<=num;i++) printf("\t%d",a[i]);

getch();

OUTPUT :

Conclusion: Thus we have Studied Merge Sort.


Experiment No. 4 : Quick Sort

Aim:- Program to implement Quick sort.

Theory :

Quick Sort divides the array according to the value of elements. It


rearranges elements of a given array A[0..n-1] to achieve its partition,
where the elements before position s are smaller than or equal to A[s]
and all the elements after position s are greater than or equal to A[s].

Algorithm:

Step 1: Start the process.

Step 2: Declare the variables.

Step 3: Enter the list of elements to be sorted using the get()function.

Step 4: Divide the array list into two halves the lower array list and
upper array list using the merge sort function.

Step 5: Sort the two array list.

Step 6: Combine the two sorted arrays.

Step 7: Display the sorted elements.

Step 8: Stop the process. T

Time complexities:

Quick sort has an average time of O(n log n) on n elements. Its worst
case time is O(n²)
Program:

#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;

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];
printf("How many elements are u going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);

quicksort(number,0,count-1);

printf("Order of Sorted elements: ");


for(i=0;i<count;i++)
printf(" %d",number[i]);

return 0;
}

OUTPUT:

Conclusion: Thus we have Studied Quick Sort .


Experiment No. 5 : Binary Search

Aim:- Program to implement Binary Search.

Theory:

Binary search is the search technique that works efficiently on sorted


lists. Hence, to search an element into some list using the binary search
technique, we must ensure that the list is sorted.

Binary search follows the divide and conquer approach in which the list
is divided into two halves, and the item is compared with the middle
element of the list. If the match is found then, the location of the
middle element is returned. Otherwise, we search into either of the
halves depending upon the result produced through the match.

Algorithm :

Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array,


'lower_bound' is the index of the first array element, 'upper_bound' is the
index of the last array element, 'val' is the value to search
Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
Step 2: repeat steps 3 and 4 while beg <=end
Step 3: set mid = (beg + end)/2
Step 4: if a[mid] = val
set pos = mid
print pos
go to step 6
else if a[mid] > val
set end = mid - 1
else
set beg = mid + 1
[end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the array"
[end of if]
Step 6: exit
PROGRAM:

#include <stdio.h>

int main()
{
int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter value to find\n");


scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) {


if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);

return 0;
}

OUTPUT:

Conclusion: Thus we have Studied Binary Search .


Experiment No. 6:

Aim:- Program to implement Naive String Matching Algorithm.

Theory:

 This is simple and efficient brute force approach. It compares the


first character of pattern with searchable text. If a match is found,
pointers in both strings are advanced. If a match is not found, the
pointer to text is incremented and pointer of the pattern is reset.
This process is repeated till the end of the text.
 The naïve approach does not require any pre-processing. Given text
T and pattern P, it directly starts comparing both strings character
by character.
 After each comparison, it shifts pattern string one position to the
right

Algorithm

1. There will be two loops: the outer loop will range from i=0 to i≤n-m,
and the inner loop will range from j=0 to j<m, where ‘m’ is the
length of the input pattern and n is the length of the text string.

2. Now, At the time of searching algorithm in a window, there will be


two cases:
o Case 1: If a match is found, we will match the entire pattern
with the current window of the text string. And if found the
pattern string is found in the current window after traversing,
print the result. Else traverse in the next window.

o Case 2: If a match is not found, we will break from the


loop(using the 'break' keyword), and the j pointer of the inner
loop will move one index more and start the search algorithm
in the next window.

Time Complexity: O(N2)


PROGRAM :

#include<stdio.h>

#include<conio.h>

#include<string.h>

int match(char st[100], char pat[100]);

int main(int argc, char **argv) {

char st[100], pat[100];

int status;

printf("*** Naive String Matching Algorithm ***\n");

printf("Enter the String.\n");

gets(st);

printf("Enter the pattern to match.\n");

gets(pat);

status = match(st, pat);

if (status == -1)

printf("\nNo match found");

else

printf("Match has been found on %d position.", status);

return 0;

int match(char st[100], char pat[100]) {

int n, m, i, j, count = 0, temp = 0;


n = strlen(st);

m = strlen(pat);

for (i = 0; i <= n - m; i++) {

temp++;

for (j = 0; j < m; j++) {

if (st[i + j] == pat[j])

count++;

if (count == m)

return temp;

count = 0;

return -1;

}
OUTPUT

Conclusion: Thus we have Studied of Naïve string Matching Algorithm.


Experiment No. 7: Knuth–Morris–Pratt Algorithm

Aim:- Program to Implement Knuth–Morris–Pratt algorithm(KMP)

Theory:

Knuth-Morris and Pratt introduce a linear time algorithm for the string
matching problem. A matching time of O (n) is achieved by avoiding
comparison with an element of 'S' that have previously been involved in
comparison with some element of the pattern 'p' to be matched. i.e.,
backtracking on the string 'S' never occurs

Components of KMP Algorithm:

1. The Prefix Function (Π): The Prefix Function, Π for a pattern


encapsulates knowledge about how the pattern matches against the
shift of itself. This information can be used to avoid a useless shift of
the pattern 'p.' In other words, this enables avoiding backtracking of
the string 'S.'

2. The KMP Matcher: With string 'S,' pattern 'p' and prefix function 'Π'
as inputs, find the occurrence of 'p' in 'S' and returns the number of
shifts of 'p' after which occurrences are found.

PROGRAM:

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

void computeLPSArray(char *pat, int M, int *lps);

void KMPSearch(char *pat, char *txt) {

int M = strlen(pat);
int N = strlen(txt);

// create lps[] that will hold the longest prefix suffix values for pattern

int *lps = (int *) malloc(sizeof(int) * M);

int j = 0; // index for pat[]

// Preprocess the pattern (calculate lps[] array)

computeLPSArray(pat, M, lps);

int i = 0; // index for txt[]

while (i < N) {

if (pat[j] == txt[i]) {

j++;

i++;

if (j == M) {

printf("Found pattern at index %d \n", i - j);

j = lps[j - 1];

// mismatch after j matches

else if (i < N && pat[j] != txt[i]) {


// Do not match lps[0..lps[j-1]] characters,

// they will match anyway

if (j != 0)

j = lps[j - 1];

else

i = i + 1;

free(lps); // to avoid memory leak

void computeLPSArray(char *pat, int M, int *lps) {

int len = 0; // lenght of the previous longest prefix suffix

int i;

lps[0] = 0; // lps[0] is always 0

i = 1;

// the loop calculates lps[i] for i = 1 to M-1

while (i < M) {

if (pat[i] == pat[len]) {

len++;
lps[i] = len;

i++;

} else // (pat[i] != pat[len])

if (len != 0) {

// This is tricky. Consider the example AAACAAAA and i = 7.

len = lps[len - 1];

// Also, note that we do not increment i here

} else // if (len == 0)

lps[i] = 0;

i++;

// Driver program to test above function

int main() {

char *txt = "ABABDABACDABABCABAB";

char *pat = "ABABCABAB";


KMPSearch(pat, txt);

return 0;

OUTPUT:

Conclusion: Thus we have Studied of KMP Algorithm.


Experiment No. 8: N-queen problem

Aim:- Program to implement N-queen problem

Theory:

N Queen problem demands us to place N queens on a N x N chessboard


so that no queen can attack any other queen directly.
Problem Statement: We need to find out all the possible arrangements
in which N queens can be seated in each row and each column so that

all queens are safe. The queen moves in 8 directions and can directly
attack in these 8 directions only.

Before starting with the actual N queen problem, let's shorten it down
to 4 - Queen problem, and then we will generalize it for N.
N Queen Problem Algorithm :

1. We create a board of N x N size that stores characters. It will store


'Q' if the queen has been placed at that position else '.'
2. We will create a recursive function called "solve" that takes board
and column and all Boards (that stores all the possible
arrangements) as arguments. We will pass the column as 0 so that
we can start exploring the arrangements from column 1.
3. In solve function we will go row by row for each column and will
check if that particular cell is safe or not for the placement of the
queen, we will do so with the help of isSafe() function.
4. For each possible cell where the queen is going to be placed, we
will first check isSafe() function.
5. If the cell is safe, we put 'Q' in that row and column of the board
and again call the solve function by incrementing the column by 1.
6. Whenever we reach a position where the column becomes equal
to board length, this implies that all the columns and possible
arrangements have been explored, and so we return.
7. Coming on to the boolean isSafe() function, we check if a queen is
already present in that row/ column/upper left diagonal/lower
left diagonal/upper right diagonal /lower right diagonal. If the
queen is present in any of the directions, we return false. Else we
put board[row][col] = 'Q' and return true.

Time and space Complexity:

The power of the set of all possible solutions of the n queen’s


problem is n! and the bounding function takes a linear amount of
time to calculate, therefore the running time of the n queens
problem is O(n!).

PROGRAM:

#include<stdio.h>

#include<conio.h>

#include<math.h>

int a[30],count=0;

int place(int pos)

{
int i;

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

if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos))))

return 0;

return 1;

void print_sol(int n)

int i,j;

count++;

printf("\n\nSolution #%d:\n",count);

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

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

if(a[i]==j)

printf("Q\t");

else printf("*\t");

printf("\n");
}

void queen(int n)

int k=1;

a[k]=0;

while(k!=0)

a[k]=a[k]+1;

while((a[k]<=n)&&!place(k))

a[k]++;

if(a[k]<=n)

if(k==n)

print_sol(n);

else

k++;

a[k]=0;

else k--;
}

void main()

int i,n;

clrscr();

printf("Enter the number of Queens\n");

scanf("%d",&n);

queen(n);

printf("\nTotal solutions=%d",count);

getch();

}
OUTPUT

Conclusion: Thus we have Studied of N-queen problem.


Experiment No. 9: Prim’s Algorithm

Aim:- Program to implement Prim’s Algorithm

Theory:

Prim's algorithm is a minimum spanning tree algorithm that takes a


graph as input and finds the subset of the edges of that graph which
 form a tree that includes every vertex

 has the minimum sum of weights among all the trees that can be
formed from the graph

How Prim's algorithm works

It falls under a class of algorithms called greedy algorithms that find the
local optimum in the hopes of finding a global optimum.
We start from one vertex and keep adding edges with the lowest
weight until we reach our goal.

The steps for implementing Prim's algorithm are as follows:

1. Initialize the minimum spanning tree with a vertex chosen at random.

2. Find all the edges that connect the tree to new vertices, find the
minimum and add it to the tree

3. Keep repeating step 2 until we get a minimum spanning tree

Prim's Algorithm Complexity

The time complexity of Prim's algorithm is O(E log V).

Prim's Algorithm Application


 Laying cables of electrical wiring
 In network designed
 To make protocols in network cycles

PROGRAM :

#include<stdio.h>

#include<conio.h>

int n, cost[10][10];

void prim() {

int i, j, startVertex, endVertex;

int k, nr[10], temp, minimumCost = 0, tree[10][3];

/* For first smallest edge */

temp = cost[0][0];

for (i = 0; i < n; i++) {

for (j = 0; j < n; j++) {

if (temp > cost[i][j]) {

temp = cost[i][j];

startVertex = i;

endVertex = j;

/* Now we have fist smallest edge in graph */


tree[0][0] = startVertex;

tree[0][1] = endVertex;

tree[0][2] = temp;

minimumCost = temp;

/* Now we have to find min dis of each vertex from eitherstartVertex


or endVertex by initialising nr[] array */

for (i = 0; i < n; i++) {

if (cost[i][startVertex] < cost[i][endVertex])

nr[i] = startVertex;

else

nr[i] = endVertex;

/* To indicate visited vertex initialise nr[] for them to 100 */

nr[startVertex] = 100;

nr[endVertex] = 100;

/* Now find out remaining n-2 edges */

temp = 99;

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

for (j = 0; j < n; j++) {

if (nr[j] != 100 && cost[j][nr[j]] < temp) {

temp = cost[j][nr[j]];

k = j;

}
}

/* Now i have got next vertex */

tree[i][0] = k;

tree[i][1] = nr[k];

tree[i][2] = cost[k][nr[k]];

minimumCost = minimumCost + cost[k][nr[k]];

nr[k] = 100;

/* Now find if k is nearest to any vertex

than its previous near value */

for (j = 0; j < n; j++) {

if (nr[j] != 100 && cost[j][nr[j]] > cost[j][k])

nr[j] = k;

temp = 99;

/* Now i have the answer, just going to print it */

printf("\nThe min spanning tree is:- ");

for (i = 0; i < n - 1; i++) {

for (j = 0; j < 3; j++)

printf("%d", tree[i][j]);

printf("\n");

}
printf("\nMin cost : %d", minimumCost);

void main() {

int i, j;

clrscr();

printf("\nEnter the no. of vertices :");

scanf("%d", &n);

printf("\nEnter the costs of edges in matrix form :");

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

for (j = 0; j < n; j++) {

scanf("%d", &cost[i][j]);

printf("\nThe matrix is : ");

for (i = 0; i < n; i++) {

for (j = 0; j < n; j++) {

printf("%d\t", cost[i][j]);

printf("\n");

prim();

getch();

}
OUTPUT :

Conclusion : Thus we have Studied of Prim’s Algorithm.


Experiment No. 10: LONGEST COMMON SUBSEQUENCE

Aim :- Program to implement LONGEST COMMON SUBSEQUENCE

Theory:

The Longest Common Subsequence (LCS) is a sequence of characters


that appears in the same order in two or more strings. It is the longest
sequence of characters that is present in all the strings, and it is not
necessarily contiguous (i.e., the characters can appear in any order
within the string). For example, given the strings “abcdef” and “abcfed”,
the LCS is “abc” because it appears in both strings and is the longest
sequence of characters common to both strings.LCS is a well-studied
problem in computer science and has many applications in fields such as
bioinformatics, text editing, and version control. It is often used to
compare and align sequences of DNA, protein, or text, and to identify
similarities and differences between them.There are several algorithms
for finding the LCS of two or more strings, and they differ in terms of
their time and space complexity. Some of the most common algorithms
for finding LCS include dynamic programming, divide and conquer, and
suffix trees.

Examples and Explanation of LCS:

Here are some examples of LCS


1. Given the strings “abcdef” and “abcfed”, the LCS is “abc” because it
appears in both strings and is the longest sequence of characters
common to both strings.
2. Given the strings “abcdefg” and “abcefgh”, the LCS is “abcef” because
it appears in both strings and is the longest sequence of characters
common to both strings.
3. Given the strings “abcdef” and “cdefgh”, the LCS is “cdef” because it
appears in both strings and is the longest sequence of characters
common to both strings.
4. Given the strings “abcdef” and “bcdefg”, the LCS is “bcdef” because it
appears in both strings and is the longest sequence of characters
common to both strings.
5. Given the strings “abcdef” and “efghij”, the LCS is “” (empty string)
because there are no common characters between the two strings.

Applications of LCS:

There are several applications of the Longest Common Subsequence


(LCS) algorithm in various fields, including:
1. Bioinformatics: LCS is often used to compare and align sequences of
DNA, protein, or other biological molecules. It can help identify
similarities and differences between the sequences, and it is a key tool
in the analysis of genetic data.
2. Text editing: LCS can be used to compare and merge text documents,
and to identify changes made to a document over time. This is useful in
version control systems, where multiple users may make changes to the
same document.
3. Data compression: LCS can be used to compress data by identifying
common patterns and replacing them with shorter sequences.
4. Machine learning: LCS can be used in machine learning algorithms to
identify patterns in data and to make predictions.
5. Speech recognition: LCS can be used to compare speech patterns and
to identify common features in different languages. This can be useful in
developing speech recognition systems that can understand multiple
languages.
6. Natural language processing: LCS can be used in natural language
processing algorithms to identify common patterns in text and to
improve the accuracy of language models.
7. Data mining: LCS can be used to identify patterns and trends in large
datasets, and to uncover hidden relationships between different
variables.
Algorithm for finding LCS:

There are several algorithms for finding the Longest Common


Subsequence (LCS) of two or more strings. One of the most common
algorithms is dynamic programming, which solves the problem by
building up solutions to smaller subproblems.
The basic idea behind the dynamic programming algorithm for LCS is as
follows:
1. Initialize a two-dimensional array, where the rows correspond to the
characters in the first string and the columns correspond to the
characters in the second string.

2. For each character in the first string, compare it to each character in


the second string. If the characters are the same, increment the value
in the array at that position by 1. If the characters are different, take
the maximum value between the value in the array at the current
position and the value in the array at the position above and to the left .
3. Repeat step 2 until all characters in both strings have been
compared.The LCS is the maximum value in the array.
Here is the pseudocode for the dynamic programming algorithm for
LCS:
function LCS(X[1..m], Y[1..n])
C = array(0..m, 0..n)
for i = 0 to m
C[i,0] = 0
for j = 0 to n
C[0,j] = 0
for i = 1 to m
for j = 1 to n
if X[i] = Y[j]
C[i,j] = C[i-1,j-1] + 1
else
C[i,j] = max(C[i,j-1], C[i-1,j])
return C[m,n]

This algorithm has a time complexity of O(mn), where m and n are the
lengths of the two strings. It has a space complexity of O(mn) as well
since it requires a two-dimensional array to store the intermediate
values.
Other algorithms for finding LCS include divide and conquer and suffix
trees. These algorithms have different time and space complexity
characteristics, and may be more suitable for different types of
problems.

PROGRAM :

#include<stdio.h>

#include<string.h>

int i,j,m,n,c[20][20];

char x[20],y[20],b[20][20];
void print(int i,int j)

if(i==0 || j==0)

return;

if(b[i][j]=='c')

print(i-1,j-1);

printf("%c",x[i-1]);

else if(b[i][j]=='u')

print(i-1,j);

else

print(i,j-1);

void lcs()

m=strlen(x);

n=strlen(y);

for(i=0;i<=m;i++)

c[i][0]=0;

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

//c, u and l denotes cross, upward and downward directions


respectively

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

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

if(x[i-1]==y[j-1])

c[i][j]=c[i-1][j-1]+1;

b[i][j]='c';

else if(c[i-1][j]>=c[i][j-1])

c[i][j]=c[i-1][j];

b[i][j]='u';

else

c[i][j]=c[i][j-1];

b[i][j]='l';

}
}

int main()

printf("Enter 1st sequence:");

scanf("%s",x);

printf("Enter 2nd sequence:");

scanf("%s",y);

printf("\nThe Longest Common Subsequence is ");

lcs();

print(m,n);

return 0;

}
Output :

Conclusion : Thus We have Studied of LONGEST COMMON


SUBSEQUENCE .

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy