0% found this document useful (0 votes)
153 views31 pages

Practical - 1: Aim Software Requirements Hardware Requirements Knowledge Requirements

The document describes algorithms for factorial, Fibonacci series, matrix addition, matrix multiplication, and linear and binary search. It provides theory, formulas, examples, pseudocode and C++ programs for implementing each algorithm iteratively and recursively. The programs track the number of operations using a counter variable to analyze algorithm efficiency. Graphs are included to visualize complexity.

Uploaded by

programmer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
153 views31 pages

Practical - 1: Aim Software Requirements Hardware Requirements Knowledge Requirements

The document describes algorithms for factorial, Fibonacci series, matrix addition, matrix multiplication, and linear and binary search. It provides theory, formulas, examples, pseudocode and C++ programs for implementing each algorithm iteratively and recursively. The programs track the number of operations using a counter variable to analyze algorithm efficiency. Graphs are included to visualize complexity.

Uploaded by

programmer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Practical - 1

Aim: Implement and analyze algorithms given below.

Software Requirements: Code-blocks

Hardware Requirements: ---

Knowledge Requirements: Basic of C, C++.

1.1) Factorial (Iterative and Recursive)

Theory:

The factorial of a non-negative integer n denoted by n! is the product of all positive integers less than or equal
to n. Its most basic occurrence is the fact that there is n! ways to arrange n distinct objects into a sequence
(i.e., permutations of the set of objects). This fact was known at least as early as the 12th century, to Indian
scholars.
Formula: n! = 1×2×3×4×...×n

Example: 5! = 5x4x3x2x1=120.

Algorithm:

Step1 Start
Step 2. Read the number n
Step 3. [Initialize] i=1, fact=1
Step 4. Repeat step 4 through 6 until i = n
Step 5. fact = fact * i
Step 6. i = i+1
Step 7. Print fact
Step 8. Stop

Program (Iterative)

#include<iostream>
using namespace std;
int main ()
{
int i, j, n, cnt=0;
float ans=1;
cout<<"enter number: ";
cnt++;
cin>>n;
cnt++;
for(i=1;i<=n;i++)

Design and Analysis of Algorithm(CE342) 1 16CE026


cnt++;
{
ans = ans*i;
cnt++;
}
cout<<"factorial: "<<ans;
cnt++;
cout<<"cnt: "<<cnt;
return 0;
}

Output:

Graph:

Design and Analysis of Algorithm(CE342) 2 16CE026


Program (Recursive)

#include<iostream>
using namespace std;
int cnt1=0;
int fact (int n)
{
float ans;
cnt1++;
if(n==1)
{
ans=1;
cnt1++;
return ans;
cnt1++;
}
else
{
ans=n*fact(n-1);
cnt1++;
return ans;
}
}
int main ()
{
int i, j,n,cnt=0;
float ans;
cnt++;
cout<<"enter number: ";
cnt++;
cin>>n;
cnt++;
ans=fact(n);
cnt++;
cout<<"factorial: "<<ans;
cnt++;
int counter = cnt+cnt1;
cout<<endl<<"counter: "<<counter;
return 0;
}

Output:

Design and Analysis of Algorithm(CE342) 3 16CE026


Graph:

1.2) Fibonacci Series (Iterative and Recursive)

Theory:

By definition, the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on
the chosen starting point of the sequence, and each subsequent number is the sum of the previous two. The
Fibonacci sequence is named after Italian mathematician Leonardo of Pisa, known as Fibonacci.

Formula: Fn = Fn-1 + Fn-2

Example: 0,1,1,2,3,5,8,13,21,34,55,89,144...

Algorithm:

Step 1. Start
Step 2. Declare variables i, a, b , show
Step 3. Initialize the variables, a=0, b=1, and show = 0
Step 4. Enter the number of terms of Fibonacci series to be printed
Step 5. Print First two terms of series
Step 6. Use loop for the following steps
-> show = a+b
-> a=b
-> b=show
-> increase value of i each time by 1
-> print the value of show
Step 7. End

Design and Analysis of Algorithm(CE342) 4 16CE026


Program (Iterative)

#include<iostream>
using namespace std;
int cnt1=0;
void fibo(int n){
int first=0,sec=1,next;
cnt1++;
cout<<"fibonacci series:";
cnt1++;
for(int i=0;i<n;i++)
{
cout<<first;
cnt1++;
next=first+sec;
cnt1++;
first=sec;
cnt1++;
sec=next;
cnt1++;
}
}
int main()
{
int cnt=0,n;
cout<<"enter n:";
cnt++;
cin>>n;
cnt++;
fibo(n);
cnt++;
cout<<endl<<"Counter: "<<cnt<<endl;
return 0;
}

Output:

Design and Analysis of Algorithm(CE342) 5 16CE026


Graph:

Program (Recursive)

#include<iostream>
using namespace std;
int cnt1=0;
int fibonacci(int n)
{
if((n==1)||(n==0))
{
return(n);
cnt1++;
}
else
{
return(fibonacci(n-1)+fibonacci(n-2));
cnt1++;
}
}
int main()
{
int n,i=0,cnt=0;
cout<<"Enter number:";
cnt++;
cin>>n;
cnt++;
cout<<"\nFibonacci Series: ";
cnt++;

Design and Analysis of Algorithm(CE342) 6 16CE026


while(i<n)
{
cout<<" "<<fibonacci(i);
cnt++;
i++;
cnt++;
}
cout<<endl<<"counnter: "<<cnt+cnt1;
return 0;
}

Output:

Graph:

Design and Analysis of Algorithm(CE342) 7 16CE026


1.3) Matrix Addition and Matrix Multiplication (Iterative)

Theory:

Matrix addition is the operation of adding two matrices by adding the corresponding entries together.

Formula:

Example:
111 111 222
A= 123 B =1 2 3 A+B=246
111 111 222

Algorithm:

Step1: Start
Step2: Read: m and n
Step3: Read: Take inputs for Matrix A[1:m, 1:n] and Matrix B[1:m, 1:n]
Step4: Repeat for i = 1 to m by 1:
Repeat for j = 1 to n by 1:
C[i, j] = A[i, j] + B[i, j]
[End of inner for loop]
[End of outer for loop]
Step5: Print: Matrix C
Step6: Exit

 Matrix Multiplication:

Matrix multiplication is a binary operation that takes a pair of matrices and produces another
matrix. Numbers such as the real or complex numbers can be multiplied according to elementary arithmetic.

Design and Analysis of Algorithm(CE342) 8 16CE026


Formula:

Example:
111 100 111
A=111 B= 010 AXB=111
111 001 111

Algorithm:

Step1: Start.
Step2: Read: m, n, p and q
Step3: Read: Inputs for Matrices A[1:m, 1:n] and B[1:p, 1:q].
Step4: Repeat for i := 1 to m by 1:
Repeat for j := 1 to q by 1:
C[i, j] := 0 [Initializing]
Repeat k := 1 to n by 1
C[i, j] := C[i, j] + A[i, k] x B[k, j]
[End of for loop]
[End of for loop]
[End of for loop]
Step5: Print: C[1:m, 1:q]
Step6: Exit

Program (Matrix Addition)

#include<iostream>
using namespace std;
int main()
{
int a[2][2],b[2][2],c[2][2],cnt=0;
cout<<"enter array A:";
cnt++;

Design and Analysis of Algorithm(CE342) 9 16CE026


for(int i=0;i<2;i++)
{ for(int j=0;j<2;j++)
cin>>a[i][j];
cnt++;
}
cout<<"enter array B:";
cnt++;
for(int i=0;i<2;i++)
{ for(int j=0;j<2;j++)
cin>>b[i][j];
cnt++;
}
cout<<"Addition:";
cnt++;
for(int i=0;i<2;i++)
{ for(int j=0;j<2;j++)
c[i][j]=a[i][j]+b[i][j];
cnt++;
}
for(int i=0;i<2;i++)
{ for(int j=0;j<2;j++)
cout<<c[i][j]<<endl;
cnt++;
}
cout<<"Counter: "<<cnt<<endl;
return 0;
}

Output:

Design and Analysis of Algorithm(CE342) 10 16CE026


GRAPH:

Program (Matrix Multiplication)

#include<iostream>
using namespace std;
int main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
cout<<"Enter rows and columns of first matrix:";
cin>>m>>n;
cout<<"Enter rows and columns of second matrix:";
cin>>p>>q;

if(n==p)
{
cout<<"\nEnter first matrix:\n";
for(i=0;i<m;++i)
for(j=0;j<n;++j)
cin>>a[i][j];

cout<<"\nEnter second matrix:\n";


for(i=0;i<p;++i)
for(j=0;j<q;++j)
cin>>b[i][j];

cout<<"\nThe new matrix is:\n";


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

Design and Analysis of Algorithm(CE342) 11 16CE026


{
c[i][j]=0;
for(k=0;k<n;++k)
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
cout<<c[i][j]<<" ";
}
cout<<"\n";
}
}
else
cout<<"\nSorry!!!! Matrix multiplication can't be done";

return 0;
}

Output:

GRAPH:

Design and Analysis of Algorithm(CE342) 12 16CE026


1.4) Recursive Linear Search and Binary Search (Comparative Study)

Theory:

Linear search is a method for finding a target value within a list. It sequentially checks each element of the
list for the target value until a match is found or until all the elements have been searched. Linear search runs
in at worst linear time and makes at most n comparisons, where n is the length of the list.

Example:
Input: 10 8 78 89 77 56 45 23 52 23
Element To Be Searched: 78
Found At Index: 3

Algorithm/Pseudo code:

Step 1: Start
Step 2: Set i to 1
Step 3: if i > n then go to step 7
Step 4: if A[i] = x then go to step 6
Step 5: Set i to i+1
Step 6: Go to step 2
Step 7: Print element x found at index i and go to step 8
Step 8: Print element not found
Step 9: Exit

 Binary Search:

Binary search is a search algorithm that finds the position of a target value within a sorted array. It compares
the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie
is eliminated and the search continues on the remaining half until it is successful.

Example:
Input: 10 8 78 89 77 56 45 23 52 23
Element to be searched: 77
Found At Index: 5

Design and Analysis of Algorithm(CE342) 13 16CE026


Algorithm/Pseudo code:

Procedure binary_search
A <- sorted array
n <- size of array
x <- value to be searched

Set lowerBound = 1
Set upperBound = n

BINARYS (lowerBound, upperBound, A, x)


if upperBound < lowerBound
Return -1

Set midpoint = ( lowerBound + upperBound ) / 2

If (A[midpoint] < x)
Return (midpoint+1, upperBound, A, x)
Else if (A[midpoint] > x)
Return (lowerBound, midpoint-1, A, x)
Else
Return midpoint

Program (Linear search)

#include<iostream>
using namespace std;
int main()
{
int n,temp,s,cnt=0;
cout<<"enter n:";
cnt++;
cin>>n;
cnt++;
int a[n];
cnt++;
cout<<"enter array:";
cnt++;
for(int i=0;i<n;i++)
{
cin>>a[i];

Design and Analysis of Algorithm(CE342) 14 16CE026


cnt++;
}
cout<<"enter array to be searched:";
cnt++;
cin>>s;
cnt++;
for(int i=0;i<n;i++)
{
if(a[i]==s)
{
cout<<"number is found";
cnt++;
}
}
cout<<endl<<"counter: "<<cnt;
return 0;
}

Output:

GRAPH:

Design and Analysis of Algorithm(CE342) 15 16CE026


Program (Binary Search)

#include<iostream>
using namespace std;
int cnt1=0;
int main()
{
int search(int [],int,int);
int n,i,a[100],e,res,cnt=0;;
cout<<"How Many Elements:";
cnt++;
cin>>n;
cnt++;
cout<<"\nEnter Elements of Array in Ascending order\n";
cnt++;
for(i=0;i<n;++i)
{
cin>>a[i];
cnt++;
}
cout<<"\nEnter element to search:";
cnt++;

Design and Analysis of Algorithm(CE342) 16 16CE026


cin>>e;
cnt++;
res=search(a,n,e);
cnt++;
if(res!=-1)
{cout<<"\nElement found at position "<<res+1;
cnt++;}
else
{cout<<"\nElement is not found....!!!";
cnt++;}
cout<<"counter: "<<cnt+cnt1;
return 0;
}
int search(int a[],int n,int e)
{
int f,l,m;
cnt1++;
f=0;
cnt1++;
l=n-1;
cnt1++;
while(f<=l)
{
m=(f+l)/2;
cnt1++;
if(e==a[m])
{
cnt1++;
return(m);
}
else
if(e>a[m])
{f=m+1;
cnt1++;}
else
{l=m-1;
cnt1++;}
}
return 0;
}

Design and Analysis of Algorithm(CE342) 17 16CE026


Output:

GRAPH:

Design and Analysis of Algorithm(CE342) 18 16CE026


Comparison:

Sr. Name Theoretical Practical

No Best Average Worst Case Best Average Case Worst


Case Case Case Case

1 Linear O(1) O(n) O(n) O(1) O(n) O(n)


Search

(Iterative)

2 Linear O(1) O(n) O(n) O(1) O(n) O(n)


Search

(Recursive)

Binary
Search
3 O(1) O(log n) O(log n) O(1) O(log n) O(log n)

Sr. Name Theoretic Practic


al al
No

1 Factorial (Iterative) O(n) O(n)

2 Factorial (Recursive) O(n) O(n)

3 Fibonacci Series (Iterative) O(n) O(n)

4 Fibonacci Series (Recursive) O(n) O(n)

5 Matrix Addition O(n2) O(n2)

6 Matrix Multiplication O(n3) O(n3)

Design and Analysis of Algorithm(CE342) 19 16CE026


Question/answer:

1) What is algorithm? and Why we need to do algorithm analysis?

Algorithm is a step by step procedure, which defines a set of instructions to be executed in


certain order to get the desired output. A problem can be solved in more than one ways. So, many
solution algorithms can be derived for a given problem. We analyze available algorithms to find
and implement the best suitable algorithm.

2) Define time and space complexity.

Time Complexity indicates how fast an algorithm runs.

T(P)=Compile Time+ Run Time (Tp).

Where Tp is no of add, sub, mul…

Space Complexity indicates how much extra memory the algorithm needs. Basically, it has three
components. They are instruction space, data space and environment space.

3) Define asymptotic notation.

The efficiency analysis framework concentrates on the order of growth of an algorithm’s basic
operation count as the principle indicator of the algorithm’s Efficiency. To compare and rank
such orders of growth scientists’ use three notations (Big Oh, Big Omega, and Big Theta, which
is called as asymptotic notation.

Conclusion: From this practical we have implemented and analyzed algorithms and time complexities of
Factorial and Fibonacci Series for both Iterative and Recursive approach. We have also analyzed time
complexities of Matrix Addition and Multiplication algorithms using iterative approach. We analyzed time
complexities for Linear Search, Recursive Search and Binary Search.

Design and Analysis of Algorithm(CE342) 20 16CE026


Practical-2
Aim: Implement and analyze algorithms given below (Compare them).
Software Requirements: Code-blocks

Hardware Requirements: ---

Knowledge Requirements: Basic of c, c++.

2.1) Bubble sort

Theory:

 Repeatedly compare neighbor pairs and swap if necessary.


 Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly
steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are
in the wrong order.
 The pass through the list is repeated until no swaps are needed, which indicates that the list is
sorted.
 The algorithm, which is a comparison sort, is named for the way smaller elements "bubble" to the
top of the list.

Algorithm:

1. Last ← n
2. Repeat thru step 5 for pass: 1,2,3..,n-1
3. E ← 0
4. Repeat for i=1,2,..,last-1
If k[i] > k[i+1]
then k[i] ↔ k[i+1]
E ← E+1
5. If E=0
then return
else
last ← last-1
6. Return number of passes

Program:

#include<iostream>
using namespace std;
int main()
{
int n,temp,cnt=0;
cnt++;
cout<<"enter n:";
cnt++;

Design and Analysis of Algorithm(CE342) 21 16CE026


cin>>n;
cnt++;
int a[n];
cnt++;
cout<<"enter array:";
cnt++;
for(int i=0;i<n;i++)
{
cin>>a[i];
cnt++;
}
for(int i=0;i<n;i++)
{for(int j=0;j<n;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
cnt++;
a[j]=a[j+1];
cnt++;
a[j+1]=temp;
cnt++;
}
}
}
cout<<"Bubble sort:";
cnt++;
for(int i=0;i<n;i++)
{
cout<<a[i];
cnt++;
}
cout<<endl<<"counter: "<<cnt;
return 0;
}

Output:

Design and Analysis of Algorithm(CE342) 22 16CE026


Graph:

Design and Analysis of Algorithm(CE342) 23 16CE026


2.2) Selection Sort

Theory:

 Repeatedly pick the smallest element to append to the result.


 The selection sort is a combination of searching and sorting. During each pass, the unsorted
element with the smallest (or largest) value is moved to its proper position in the array. The number
of times the sort passes through the array is one less than the number of items in the array.
 Selection sort is the most conceptually simple of all the sorting algorithms. It works by selecting
the smallest (or largest, if you want to sort from big to small) element of the array and placing it at
the head of the array. Then the process is repeated for the remainder of the array; the next largest
element is selected and put into the next slot, and so on down the line.
 Because a selection sort looks at progressively smaller parts of the array each time (as it knows to
ignore the front of the array because it is already in order), a selection sort is slightly faster than
bubble sort, and can be better than a modified bubble sort.

Algorithm:

1. Repeat thru step 4 for Pass=1,2,..,n-1


2. Min_index ← Pass
3. Repeat for i=Pass+1,Pass+2,..,n
if k[i] < k[Min_index] then Min_index ← i
4. if Min_index!=Pass
then k[Pass] ↔ k[Min_index]
5. Return

Program:

#include<iostream>
using namespace std;
int main(){
int n,cnt=0;
cout<<"n: ";
cnt++;
cin>>n;
cnt++;
int a[n];
cnt++;
cout<<"array: ";
cnt++;
for(int i=0;i<n;i++)
{cin>>a[i];
cnt++;}
int minindex;
cnt++;
int count=0;
cnt++;
for(int i=0;i<n;i++)
{

Design and Analysis of Algorithm(CE342) 24 16CE026


for(int k=i+1;k<n;k++)
{
if(a[i]>a[k])
{
int temp=a[i];
cnt++;
a[i]=a[k];
cnt++;
a[k]=temp;
cnt++;
}
}
}
for(int i=0;i<n;i++)
{cout<<endl<<a[i];
cnt++;}
cout<<endl<<"COUNTS:-"<<cnt;
return 0;
}

Output:

Graph:

Design and Analysis of Algorithm(CE342) 25 16CE026


2.3) Insertion Sort

Theory:

 Insertion sort maintains a sorted sub-array, and repetitively inserts new elements into it.
 repeatedly add new element to the sorted result.
 If the first few objects are already sorted, an unsorted object can be inserted in the sorted set in
proper place. This is called insertion sort. An algorithm considers the elements one at a time,
inserting each in its suitable place among those already considered. Insertion sort is an example of
an incremental algorithm; it builds the sorted sequence one number at a time.

Design and Analysis of Algorithm(CE342) 26 16CE026


Algorithm:

1. For j←2 to n
do key ← A[j]
2. i ← j-1
3. while i>0 & A[i]>key
do A[i+1] ← A[i]
i←i-1
4. A[i+1]←key

Program:

#include<iostream>
using namespace std;
int main()
{
int size, arr[50], i, j, temp,cnt=0;
cout<<"Enter Array Size : ";
cnt++;
cin>>size;
cnt++;
cout<<"Enter Array Elements : ";
cnt++;
for(i=0; i<size; i++)
{
cin>>arr[i];
cnt++;
}
for(i=1; i<size; i++)
{
temp=arr[i];
cnt++;
j=i-1;
cnt++;
while((temp<arr[j]) && (j>=0))
{
arr[j+1]=arr[j];
cnt++;
j=j-1;
cnt++;
}
arr[j+1]=temp;
cnt++;
}
cout<<"Array after sorting : \n";
cnt++;
for(i=0; i<size; i++)
{
cout<<arr[i]<<" ";
cnt++;
}
cout<<endl<<"counter: "<<cnt;
return 0;}

Design and Analysis of Algorithm(CE342) 27 16CE026


Output:

Graph:

Design and Analysis of Algorithm(CE342) 28 16CE026


Comparison:

Sr. Problem Practical Theatrical


No Definiti
on Time Complexity Time Complexity

1 Bubble Best O(n) Best O(n)


Sort
Average O(n2) Average O(n2)

Worst O(n2) Worst O(n2)

2 Selectio Best O(n2) Best O(n2)


n Sort
Average O(n2) Average O(n2)

Worst O(n2) Worst O(n2)

3 Insertion Best O(n) Best O(n)


Sort
Average O(n2) Average O(n2)

Worst O(n2) Worst O(n2)

Question/answer:

1) Explain what is the difference between best case scenario and worst case scenario
of an algorithm?

Best case scenario: Best case scenario for an algorithm is explained as the arrangement of data for
which the algorithm performs best. For example, we take a binary search, for which the best case
scenario would be if the target value is at the very center of the data you are searching. The best
case time complexity would be 0 (1).

Worst case scenario: It is referred for the worst set of input for a given algorithm. For example
quicksort, which can perform worst if you select the largest or smallest element of a sublist for the
pivot value. It will cause quicksort to degenerate to O (n2).

2) How insertion sort and selection sorts are different?

Both sorting techniques maintains two sub-lists, sorted and unsorted and both take one element at
a time and places it into sorted sub-list. Insertion sort works on the current element in hand and
places it in the sorted array at appropriate location maintaining the properties of insertion sort.

Design and Analysis of Algorithm(CE342) 29 16CE026


Whereas, selection sort searches the minimum from the unsorted sub-list and replaces it with the
current element in hand.

3) Explain in detail about sorting and different types of sorting techniques ?

Sorting is a technique to rearrange the elements of a list in ascending or descending order, which
can be numerical, lexicographical, or any user-defined order. Sorting is a process through which
the data is arranged in ascending or descending order. Sorting can be classified in two types;

Internal Sorts:- This method uses only the primary memory during sorting process. All data items
are held in main memory and no secondary memory is required this sorting process. If all the data
that is to be sorted can be accommodated at a time in memory is called internal sorting. There is a
limitation for internal sorts; they can only process relatively small lists due to memory constraints.
There are 3 types of internal sorts.

(i) SELECTION SORT: - Ex: - Selection sort algorithm, Heap Sort algorithm

(ii) INSERTION SORT: - Ex: - Insertion sort algorithm, Shell Sort algorithm

(iii) EXCHANGE SORT: - Ex: - Bubble Sort Algorithm, Quick sort algorithm

External Sorts: - Sorting large amount of data requires external or secondary memory. This process
uses external memory such as HDD, to store the data which is not fit into the main memory. So,
primary memory holds the currently being sorted data only. All external sorts are based on process
of merging. Different parts of data are sorted separately and merged together.

Conclusion: From this practical we have analyzed time complexities of various


Sorting algorithms like Bubble sort, Insertion sort and Selection Sort. We further analyzed time
complexities of these algorithms in their best case, average case and worst case.

Design and Analysis of Algorithm(CE342) 30 16CE026


Design and Analysis of Algorithm(CE342) 31 16CE026

You might also like