You are on page 1of 26

SYLHET ENGINEERING

COLLEGE
Lab Report

Course Title: Data Structures Sessional


Course Code: CSE 201
Name of algorithms:
1. Pattern Matching Algorithm
2. Array Insertion Algorithm
3. Linear search Algorithm
4. Binary search Algorithm
5. Elements deletion in an array Algorithm
6. Infix to Postfix expression Algorithm
7. Tower of Hanoi Algorithm
8. Bubble sort Algorithm

Date of Submission: 5/01/2023

Submitted By Submitted To

Shuvro Bhattacharjee Md. Lysuzzaman


Reg. No.: 2019331551 Assistant professor of CSE,
1st year 2nd Semester Sylhet Engineering College
Batch- 14
Department of CSE
Experiment No.: 01
Experiment Name: Pattern Matching Algorithm
Objective:
The main Objective of this algorithm is to match a pattern in a string. If a pattern
is matching with the string then we have to return the index of the string from
where the pattern is matching.
Algorithm:
Algorithm.Pattern_matching(s,p) : return int;
{
LS=Length(s)
LP=Length(p)
Max=LS-LP+1
for( i = 1 ; i <= Max ; i++)
{
flag=true;
for( j = 1 ; j <=LP && flag == true ; j++)
{
If( p[i] != s[i+j-1])
flag = false
}
If(flag==true)
return i ;
}
return 0;
}

Code For Pattern Matching:


#include <bits/stdc++.h>
#define int long long

using namespace std;


int main(){
string s,p;
cout<<"Input the main string: "<<endl;
cin>>s;
cout<<"Input the pattern String: "<<endl;
cin>>p;
int ls=s.size();
int lp=p.size();
int max=ls-lp+1;
bool flag;
for(int i=0;i<max;i++){
flag=true;
for(int j=0;j<lp && flag==true;j++){
if(p[j]!=s[i+j])
flag=false;
}
if(flag==true){
cout<<"Pattern is matched at index: "<<i+1<<endl;
break;
}
}

if(flag==false){
cout<<"Pattern is not matched"<<endl;
}
return 0;
}

Sample Input:
Input the main string:
sdfghjk
Input the pattern String:

hjk

Sample Output:
Pattern is matched at index: 5

Result & Discussion:


In the first sample we have a main string “sdfghjk” and the pattern string is “hjk”.
So the pattern string was matched in the main string at index 5. So we got the
output of index 5.
Experiment No.: 02
Experiment Name: Array Insertion
Objective:
When the insertion happens at the beginning, it causes all the existing data items
to shift one step downward. Here, we design and implement an algorithm to
insert an element at the beginning of an array. Inserting an element at the end of
a linear array can be easily done provided the memory space allocated for the
array is large enough to accommodate the additional element.

Algorithm:
INSERT(LA, N, K, ITEM)
Here LA is a linear array with N elements and K is a positive integer such that
K<=N.
1. [Initialize counter] Set J: = N
2. Repeat steps 3 and 4 while J>=K
3. [Move Jth element downward] Set LA[J+1] := LA[J]
4. [Decrease counter] Set J := J-1
[End od step 2 loop]
5. [Insert element] set LA[K] := ITEM
6. [Reset N] set N := N+1
7. Exit
Code:
#include<bits/stdc++.h>
using namespace std;
#define MAX 5
int main(){
int array[MAX] = {1, 2, 4, 5};

int N = 4;
int i = 0;
int index = 2;
int value = 3;

printf("Printing array before insertion −\n");

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


printf("array[%d] = %d \n", i, array[i]);
}

for(i = N; i >= index; i--) {


array[i+1] = array[i];
}

array[index] = value;
N++;

printf("Printing array after insertion −\n");


for(i = 0; i < N; i++) {
printf("array[%d] = %d\n", i, array[i]);
}
return 0;
}

Sample Input & Output:


Printing array before insertion −
array[0] = 1
array[1] = 2
array[2] = 4
array[3] = 5
Printing array after insertion −
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5

Result & Discussion:


In this scenario we are given a location (index) of an array before which a new
data element (value) has to be inserted. This time we seek till index-1 i.e., one
location ahead of given index, rest of the activities are same as in previous
example.
Experiment No: 03

Experiment Name : Linear Searching

Objective :

Linear Search is defined as a sequential search algorithm that starts at one end and
goes through each element of a list until the desired element is found, otherwise the
search continues till the end of the data set. It is the easiest searching algorithm.

Algorithm:
Alogo_LINEAR(LA[],ITEM,LOC,N){

For(i=0;i<N;i++){
if(LA[i]==ITEM){
break;
}
If(i==n){
printf(“Unsuccessfully Searching ”);
Loc=-1;
}
else {
print (“found at location ”,i)
loc =I ;
}
return (loc);
}

Code:
#include <bits/stdc++.h>
using namespace std;

int main()
{
int N = 10;

int LA[N] = { 7, 3, 5, 9, 4, 6, 11, 44, 77, 12 };

int K;
cout << "Enter the item you want to find : ";
cin >> K;
int i;
for (i = 0; i < N; ++i)
{
if (K == LA[i])
{
break;
}
}

if (i == N)
{
cout << "Unsuccessful searching \n";
}
else
{
cout << "Found item " << K << " at location at " << i + 1;
}
}

Sample Input & Output:


Sample 1 :
input:
Enter the item you want to find : 8
output :
Sample 2 :
input:
Enter the item you want to find : 9
output :
Found item 9 at location at 4

Result and Discussion :

In this case first we take an input of item .Then we search through the array and if
we find the item then we break the loop . Then we check if I is equal to the size of
the array if yes then we said unsuccessful found .else we get that item. Then we
return the position of the item .
The average case time complexity of linear search is O(n).

Experiment No: 04
Experiment Name : BINARY SEARCH .

Objective :
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:
Alogo_bineary_search(a[],lb,ub,item){
beg=lb;
end=ub;
mid=int((beg+end)/2)
while(a[mid]!=item and beg<=end){
if(a[mid]>item){
end=mid-1;
}
else
beg=mid+1;

mid=int((beg+end)/2)
}
If(a[mid]==item){
loc=mid
}
else
Loc=-1;
return loc;
}

Code:
#include <bits/stdc++.h>
using namespace std;

int main()
{
int N = 10;

int a[N] = { 13, 21, 32, 45, 56, 61, 74, 81, 95, 101 };
int item;
cout << "Enter the item you want to find : ";
cin >> item;

int beg = 0;
int end = N - 1;
int mid = (int)((beg + end) / 2);

while (a[mid] != item and beg <= end)


{
if (a[mid] > item)
{
end = mid - 1;
}
else beg = mid + 1;

mid = (int)((beg + end) / 2);


}

if (a[mid] == item)
{
cout << "Item " << item << " found at location " << mid + 1;
}
else cout << "Item not found ";

Sample Input 1:
Enter the item you want to find : 101

Sample Output 1:
Item 101 found at location 10
Sample Input 2:
Enter the item you want to find : 44

Sample Output 2:

Item not found

Result and Discussion :

First we started from the middle element then if the item is greater then the middle
element then we set the beg equal to mid+1 else we set end = mid -1.we continue
doing that until we get the item or the beg is less then equal end .
The average case time complexity of Binary search is O(logn).

Experiment No: 05

Experiment Name: Deleting from a Linear Array .

Objective :

Let J be any location in the array for one existing element. We have to delete the
element at J position. To do this starting from J every element is moved one place
forward so that the element after index J comes to position of Jth element. This is
the average case scenario in deletion in  linear array.
Algorithm:
DELETE(LA, N, K, ITEM)
{

Here LA is a linear array with N .elements and K is a positive integer such that
K <= N This algorithm deletes the Kth element from LA.

1. Set ITEM = LA[K].

2. Repeat for J = K to N - 1

[Move J + 1st element upward.] Set LA[J] = LA [J + 1] .

[End of loop.]

3. [Reset the number N of elements in LA.] Set N = N – 1


4. Exit.
}

Code:
#include <bits/stdc++.h>
using namespace std;

int main() {
int N = 10;

int LA[N] = {7, 3, 5, 9, 4, 6, 11, 44, 77, 12};

int K;
cout << "Enter the position of the item between 1 to 10: ";
cin >> K;
int ITEM = LA[K - 1];
for (int i = K - 1; i < N; ++i) {
LA[i] = LA[i + 1];
}
N = N - 1;

cout << "\nItem " << ITEM << " deleted from the position " << K << endl;
cout << "Modified array : ";
for (int i = 0; i < N; ++i) {
cout << LA[i] << " ";
}
}

Sample Input & Output:

input:
Enter the position of the item between 1 to 10: 4
output :
Item 9 deleted from the position 4
Modified array : 7 3 5 4 6 11 44 77 12

Result and Discussion :

In the example array ,elements from index J (4-1) to index 9 have to moved one
position forward so that an element at index 3 is replaced by element at index 4.
Similarly element at 5th postion comes at 4th position, element at 6th position comes
at 5th position and element at 7th position replaces element at 6th position
completing the deletion process.
The highest order term in this function defined in the terms of input size of the
algorithm is n, so we can say that the complexity of this algorithm is O(n). It also
means that the average time of element deletion in array grows linearly with the
size of array DATA.
Experiment No: 06
Experiment Name : INFIX TO POSTFIX OPERATION.

Objective :

To convert infix expression to postfix expression, we will use the stack data
structure. By scanning the infix expression from left to right, when we will get any
operand, simply add them to the postfix form, and for the operator and parenthesis,
add them in the stack maintaining the precedence of them.

Algorithm:
POLISH(Q, P)

Suppose Q is an arithmetic expression written in infix notation. This algorithm finds the equivalent
postfix expression P.

1. Push "(" onto STACK , and add ")" to the end of Q.


2. Scan Q from left to right and repeat Steps 3 to 6 for each element of Q until the STACK is empty:
3. If an operand is encountered, add it to P.
4. If a left parenthesis is encountered, push it onto STACK.
5. If an operator is encountered, then:
(a) Repeatedly pop from STACK and add to P each operator (on the top of STACK) which
has the same precedence as or higher precedence than  .
(b) Add  to STACK.
[End of If structure.]
6.If a right parenthesis is encountered, then:
(a) Repeatedly pop from STACK and add to P each operator (on the top of STACK) until a
left parenthesis is encountered.

Code for Infix to Postfix:


#include <bits/stdc++.h>
using namespace std;

int main() {
string s;
cin >> s;
stack<char> st;
st.push('(');
s.push_back(')');
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '^' or s[i] == '(') {
st.push(s[i]);
} else if (s[i] == ')') {
while (st.top() != '(') {
cout << st.top();
st.pop();
}
st.pop();
} else if (s[i] == '+' or s[i] == '-') {
if (st.top() == '-' or st.top() == '+' or st.top() == '/' or
st.top() == '*' or st.top() == '^') {
cout << st.top();
st.pop();
st.push(s[i]);
} else {
st.push(s[i]);
}
} else if (s[i] == '/' or s[i] == '*') {
if (st.top() == '/' or st.top() == '*' or st.top() == '^') {
cout << st.top();
st.pop();
st.push(s[i]);
} else {
st.push(s[i]);
}
} else
cout << s[i];
}
}

Sample Input & Output:

Sample:
input:
A+(B*C-(D/E^F)*G)*H
output :
Sample:
ABC*DEF^/G*-H*+
input:
x^y/(5*z)+2
output :
xy^5z*/2+
Result and Discussion :
In this case, we have operator's stack, output's stack and one input string.

Result & Discussion:

Operator's stack works as FILO(First In Last Out). Output's stack works as FIFO
(First In First Out).
The time complexity of the above solution is O(n), where  n  is the length of the infix expression.
The auxiliary space required by the program is O(n) for the stack data structure. Here we will
consider {+, −,∗,/, ^} as operators.

Experiment No.: 07
Experiment Name: Tower of Hanoi Algorithm

Objective:
Tower of Hanoi is an example of a recursive definitions and procedures. This
section shows how recursion may be used as a tool in developing an algorithm to
solve a particular problem.
Algorithm_Tower(N, BEG, AUX, END)
{
1. IF N=1 then,
a. Write BEG-> END
b. Return
[End of IF structure]
2. [Move N-1 disks from peg BEG to AUX]
Call Tower(N-1,BEG,END,AUX)
3. Write BEG-> END
4. [Move N-1 disks from peg AUX to END]
Call Tower(N-1, AUX, BEG, END)
5. Return
}

Algorithm:

Code:
#include <bits/stdc++.h>

using namespace std;


void tow(int n,char b,char a,char e){
if(n==1){
cout<<"Move N-1 disks from peg "<<b<<" to "<<e<<endl;
return;
}
else{
tow(n-1,b,e,a);
cout<<"Move N-1 disks from peg "<<b<<" to "<<e<<endl;
tow(n-1,a,b,e);
}
}
void Solve(int tc) {
int n;
char a,b,c;
cout<<"Inter N, A, B & C: "<<endl;
cin>>n>>b>>a>>c;
tow(n,b,a,c);

}
int32_t main(void) {
ios::sync_with_stdio(false);
cin.tie(0);
int tt = 1, tc = 0;
#ifdef MultipleCase
cin >> tt;
#endif
while (tt--) Solve(++tc);
return 0;
}

Sample Input:
Inter N, A, B & C:
3ABC
Sample Output:
Move N-1 disks from peg A to C
Move N-1 disks from peg A to B
Move N-1 disks from peg C to B
Move N-1 disks from peg A to C
Move N-1 disks from peg B to A
Move N-1 disks from peg B to C
Move N-1 disks from peg A to C

Result & Discussion:

1.First input the number of disks placed on three rods.


2. Declare a function which takes 4 parameters which are: no of disks and name of initial disk,
auxiliary disk and final disk.
3. The function recursively calls itself twice to solve the problem with a base case to stop when n
is 1.
4. Call this function from main function.
In each function call, we are calling the function twice so time complexity of tower of hanoi
program is O(2n).

Experiment No: 08
Experiment Name : BUBBE sort Algorithm.
Objective :

Bubble Sort is a simple algorithm which is used to sort a given set of n elements
provided in form of an array with n number of elements. Bubble Sort compares all
the element one by one and sort them based on their values.
If the given array has to be sorted in ascending order, then bubble sort will start by
comparing the first element of the array with the second element, if the first
element is greater than the second element, it will swap both the elements, and then
move on to compare the second and the third element, and so on.
If we have total n elements, then we need to repeat this process for n-1 times.
Sorting takes place by stepping through all the elements one-by-one and comparing
it with the adjacent element and swapping them if required.

Algorithm :

BUBBLE(DATA,N)
{
1.Repeat steps 2 and 3 for K=1 to N-1
2. Set PTR =1 .
3. Repeat while PTR <=N-K:
(a) If DATA[PTR]>DATA[PTR+1],then :
Interchange DATA [PTR] and DATA [PTR+1]
[End of if structure]
(b) Set PTR =PTR + 1
[End of inner loop ]
[End of step 1 outer loop]
4. Exit .
}
Code For Bubble Sort:
#include<bits/stdc++.h>

using namespace std;


int main() {

int N;

cout << "Enter number of elements : ";


cin >> N;
int DATA[N];
cout << "\n Input " << N << " number of elements :";

for (int i = 0; i < N; ++i) {

cin >> DATA[i];


}
int K = 1;
while (N - K) {
for (int i = 0; i < N - K; ++i) {
if (DATA[i] > DATA[i + 1]) {
swap(DATA[i], DATA[i + 1]);
}
}
K++;
}
cout << "Sorted DATA : ";
for (int i = 0; i < N; ++i) {
cout << DATA[i] << " ";
}
Sample-1
input:
Enter number of elements : 7
Input 7 number of elements : 64 34 25 12 22 11 90
output :
Sorted DATA : 11 12 22 25 34 64 90

Sample-2
input:
Enter number of elements : 10
Input 10 number of elements :99 12 44 22 66 11 14 54 43 1
output :
Sorted DATA : 1 11 12 14 22 43 44 54 66 99

Result and Discussion :

In the sample input first we take number of elements and then we take n number of
inputs. If we have total n elements, then we need to repeat this process for n-
1 times. This algorithm is not suitable for large data sets as its average and worst-
case time complexity is quite high,complexity are of Ο(n2) where n is the number
of items.

You might also like