Unit 2
Unit 2
Algorithm-Specification
Def: An algorithm is a combination of, sequence of, finite number of steps to solve a problem.
Example
ATN()
{
1. Read two numbers;
2. Add the numbers and store the result in a variable
3. Print or write the result in a file.
}
Properties of an algorithm
1. Every algorithm must terminate after a finite number of steps.
Example: while(1)
{
Printf (“DSA”);
} //It is not an algorithm.
2. Every algorithm must produce some output.
3. Every algorithm may or may not take some input.
4. Every statement in algorithm must be effective.
Example: x = x; // waste of CPU time. So, not an effective statement.
5. Every algorithm must be deterministic.
6. Algorithm is independent of programming language.
DR. V SREENIVASULU 1
Better: If a problem has more than one algorithm, one the better one is selected. How to find
the better one? Two metrics 1. Time 2. Space
Time Complexity: Time taken by the CPU to run the algorithm should be less.
Space Complexity: Space (memory) needs to run the algorithm should be less.
Time Complexity
Analysis
Aposteriori Apriori
1 It can also be called as Relative 1 It can also be called as absolute
analysis analysis
2 It is dependent on compiler and 2 It is independent on compiler and
processor processor
3 It gives more realistic analysis 3 It gives approximate analysis
4 Analysis change from system to 4 No change of analysis irrespective of
system any system
Algorithm A
I3 100ns O(1)
I5 10ns O(1)
I7 2ns O(1)
Super Computer ns/100 Log(n)
DR. V SREENIVASULU 2
Exercise: Finding Time complexity for the given problems
1. main()
{
x = y + z;
}
T.C (1) order of magnitude O(1) or Ω(1) or Θ(1)
----------------------------------------------------------------------------------------------------------------
2. Find out the time complexity of the given snippet
main()
{
x = y + z;
a = b + c;
p = q + r;
r = s + t;
}
T.C 4ns O(1) ignore constant
----------------------------------------------------------------------------------------------------------------
3. Find out the time complexity of the given snippet
main()
{
x = y + z;
for( i = 0; i < n; i++ )
p = q + r;
r = s + t;
}
T.C 1 + n + n - 1 + 1 = 2n + 1 O(n) approximation
----------------------------------------------------------------------------------------------------------------
4. Find out the time complexity of the given snippet
main()
{
x = y + z;
for( i = 0; i < n; i++ )
p = q + r;
for( i = 0; i < n; i++ )
r = s + t;
}
T.C 1 + n + n -1 + n + n - 1 = 4n - 1 O(n) approximation
----------------------------------------------------------------------------------------------------------------
DR. V SREENIVASULU 3
5. Find out the time complexity of the given snippet
main()
{
x = y + z;
for( i = 0; i < n; i++ )
p = q + r;
for( i = 0; i < n; i++ )
for( j = 0; j < n; j++ )
r = s + t;
}
T.C = O(n2) approximation
----------------------------------------------------------------------------------------------------------------
6. Find out the time complexity of the given snippet
main()
{
for( i = 0; i < n/2; i++ )
for( j = 0; j < n/2; j++ )
r = s + t;
}
T.C = O(n2) approximation
----------------------------------------------------------------------------------------------------------------
7. Find out the time complexity of the given snippet
main()
{
for( i = 0; i < n2; i++ )
for( j = 0; j < n2; j++ )
r = s + t;
}
T.C = O(n2) approximation
----------------------------------------------------------------------------------------------------------------
--
8. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i < n )
{
i = i + 1;
}
DR. V SREENIVASULU 4
}
T.C = 1 + n + n – 1 = 2n O(n) approximation
----------------------------------------------------------------------------------------------------------------
9. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i < n )
{
i = i + 2;
i = i + 18;
i = i – 5;
}
}
T.C = 1 + 20 – 5 = n . 1/15 1/15 is constant. So, O(n) approximation
----------------------------------------------------------------------------------------------------------------
10. Find out the time complexity of the given snippet
main()
{
i = n;
while(i > 1 )
{
i = i + 2;
}
}
T.C = n is already bigger. Again incrementing by 2. Violating algorithm properties.
----------------------------------------------------------------------------------------------------------------
11. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i > 1 )
{
i = i * 2;
}
}
T.C = (log2n)
DR. V SREENIVASULU 5
12. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i > 1 )
{
i = i * 20;
i = i/20;
i = i/5;
}
}
T.C = (log n)
----------------------------------------------------------------------------------------------------------------
13. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i > 1 )
{
i = i * 2;
}
}
T.C = (log2n)
----------------------------------------------------------------------------------------------------------------
14. Find out the time complexity of the given snippet
main()
{
i = 1;
while(i > 1 )
{
i = i2;
}
}
T.C = (log2log2n)
----------------------------------------------------------------------------------------------------------------
DR. V SREENIVASULU 6
15. Find out the time complexity of the given snippet
main()
{
i = 5;
while(i > 1 )
{
i = i7;
}
}
T.C = (log7log5 n)
----------------------------------------------------------------------------------------------------------------
Recursion
1. A function is calling itself with the same code to solve a problem is termed as
recursion.
2. Solving a big problem in terms of a small problems. Call first, completed last stack.
3. A stack is used to execute recursive program,
n * fact (n – 1)
n * fact (n – 1)
n * fact (n – 1)
n * fact (n – 1)
n * fact (n – 1)
n * fact (n – 1)
4 Easy for programmer and 4 Easy for the CPU but complex for the
complex for the CPU programmer.
DR. V SREENIVASULU 7
5. Algorithms
6. Base Condition: Function call is a push operation. If no base condition, it pushes and
pushes till internal “Stack overflows”. Displays error message run time error.
7. Comparing RP and NRP, RP takes more memory space. # stack units are used in RP.
Factorial Computation
The factorial of a number n, denoted as n!, is the product of all positive integers less than or
equal to n. Mathematically, it is defined as
Example: 5! = 5 X 4 X 3 X 2 X 1 = 120
Recursive Definition of Factorial
In recursion, a function calls itself with a smaller argument until it reaches a base case. The
factorial function can be defined recursively as
DR. V SREENIVASULU 8
1_Write a C Program that reads a number and find out the factorial for that number
using non-recursion
#include<stdio.h>
int fact(int);
int main()
{
int num;
printf ("Enter a number...");
scanf ("%d", &num);
fact(num);
return 0;
}
OUTPUT
Case1:
Enter a number...5
Factorial of 5 is ...120
Case 2:
Enter a number...6
Factorial of 6 is ...720
DR. V SREENIVASULU 9
2_Write a C Program that reads a number and find out factorial for that number using
recursion
#include<stdio.h>
int fact(int n);
int main()
{
int num, f(int), factorial;
printf ("Enter a number...");
scanf ("%d",&num);
factorial = fact(num);
printf ("Factorial of %d is ...%d\n", num, factorial);
return 0;
}
int fact (int n)
{
if(n == 0)
return 1;
else
return (n * fact(n-1));
}
OUTPUT
Case1:
Enter a number...5
Factorial of 5 is ...120
Case 2:
Enter a number...6
Factorial of 6 is ...720
DR. V SREENIVASULU 10
3_Write a C Program that reads any two numbers and finds the GCD of for that two
numbers using non-recursion
#include <stdio.h>
return 0;
}
OUTPUT
Case1:
Enter two integers: 24 18
GCD of 24 and 18 is: 6
Case2:
Enter two integers: 24 36
GCD of 24 and 36 is: 12
DR. V SREENIVASULU 11
4_Write a C Program that reads any two numbers and finds the GCD of for that two
numbers using recursion
#include<stdio.h>
void main ()
{
int num1, num2, gcd;
printf ("Enter two numbers ...");
scanf ("%d %d", &num1,&num2);
OUTPUT
Case1:
Enter two numbers ...50 24
GCD of 50, 24 is 2
Case2:
Enter two numbers ...36 18
GCD of 36, 18 is 18
DR. V SREENIVASULU 12
Fibonacci Sequence
Fibonacci sequence is a series of numbers in which each number is the sum of the previous
two numbers usually starting with 0 and 1.
#include <stdio.h>
return 0;
}
DR. V SREENIVASULU 13
OUTPUT
Case 1
Enter the number of terms: 8
Fibonacci sequence: 0 1 1 2 3 5 8 13
Case 2
Enter the number of terms: 9
Fibonacci sequence: 0 1 1 2 3 5 8 13 21
Towers Of Hanoi
The Towers of Hanoi is a mathematical puzzle involving three pegs and a set of disks of
different sizes. The puzzle starts with all the disks in descending order of size with the largest
disk at the bottom and the smallest disk at the top.
Objective
The goal is to move all the disks from the source peg to another peg with these rules:
1. Only one disk can be moved at a time.
2. A disk can only be moved to the top of another peg.
3. No larger disk can be placed on top of a smaller disk.
Recursive Approach
Recursive can be used to solve the Towers of Hanoi puzzle. For n disks, the solution involves
as given below.
DR. V SREENIVASULU 14
6_Write a C Program that uses Recursive Algorithm for Solving the Towers of Hanoi
Problem
#include <stdio.h>
void shiftDisk(int n, char source, char aux, char des) // Function to move disks
{
if (n == 1)
{
printf ("Shift disk 1 source %c Destination %c\n", source, des);
return;
}
shiftDisk(n - 1, source, des, aux); // Shift n-1 disks from the source to auxiliary
shiftDisk(n - 1, aux, source, des); // Shift the n-1 disks from auxiliary to destination
}
int main()
{
int n,i;
printf ("\nDisks on Source Peg S\n"); // Displaying initial state of the source peg
DR. V SREENIVASULU 15
OUTPUT
Enter the number of disks...3
Initial State
Post A
Disk 3
Disk 2
Disk 1
Fixed Size: Arrays have a predetermined size once they are created. In many languages,
Change the size of an array is not possible after its declaration.
Indexed Access: Elements can be accessed directly using an index. Indexing starts at 0 in
most programming languages.
Homogeneous Elements: All elements in an array are of the same data type.
DR. V SREENIVASULU 16
Common Operations in Array ADT
Access: Retrieve an element at a given index.
Example: array[i]
Definition of Arrays
An array is a data structure that stores a collection of elements, all of the same type, in a
contiguous block of memory. Arrays allow to store multiple values under a single variable
name and access them using an index.
Properties of Arrays
1. Fixed Size: Once an array is created, its size is fixed and cannot be changed. This is
why specify the size when creating an array.
2. Same Data Type: All elements in an array must be of the same data type, such as
integers, floats, or strings.
DR. V SREENIVASULU 17
Advantages of Arrays
Efficiency: Arrays provide constant-time access to elements using their index.
Compactness: Arrays store elements in a contiguous block of memory, reducing
overhead.
Limitations of an array
Fixed Size: Arrays have a fixed size, so First of all give the size of the array. It leads to
some other problems over size and below size.
Same Data Type: Arrays can only hold elements of a single data type.
Initialization of 1D Array
Full Initialization: int arr[5] = {10, 20, 30, 40, 50};
Partial Initialization: int arr [5] = {1, 2}; // Rest are set to 0
Implicit Size: int arr [] = {10, 20, 30}; // Size is automatically set to 3
All Zeros: int arr [5] = {0}; // All elements are initialized to 0
Dynamic Assignment: Declare first, then assign using indices: arr[0] = 10;
7_Write a C Program that performs Array initialization, reading and printing the
elements
#include <stdio.h>
int main()
{
int n, i;
int intArray[n];
char charArray[n];
double doubleArray[n];
DR. V SREENIVASULU 18
printf ("\nEnter %d doubles...", n);
for (i = 0; i < n; i++)
{
scanf ("%lf", &doubleArray[i]);
}
return 0;
}
OUTPUT
Enter the number of elements... 3
Enter 3 integers...1 2 3
Enter 3 characters...A B C
Enter 3 doubles...1.2 2.3 3.4
DR. V SREENIVASULU 19
Elements in the characters array
Character[0]: A
Character[1]: B
Character[2]: C
2D array
A 2D array (two-dimensional array) is an array of arrays, where data is stored in a table-like
structure with rows and columns. Each element in a 2D array is accessed using two indices:
one for the row and one for the column.
Table Structure: A 2D array is like a table with rows and columns. For example, a 3x3 matrix
has 3 rows and 3 columns.
Two Indices: Elements are accessed elements using two indices. The first index represents
the row and the second index represents the column.
Fixed Size: The size of a 2D array is fixed so size must be specified both the number of rows
and columns when declaring it.
Same Data Type: All elements in the array must be of the same data type (e.g., all integers,
all doubles, etc.).
Syntax of 2D Array in C
data_type array_name[rows][columns];
Where
DR. V SREENIVASULU 20
8_Write a C Program that reads elements for two 2D arrays, add element to element
and display the resultant array
#include <stdio.h>
int main()
{
int rows, columns, i, j;
DR. V SREENIVASULU 21
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
printf ("%d ", sumArray[i][j]);
}
printf ("\n");
}
return 0;
}
OUTPUT
DR. V SREENIVASULU 22
Array representation of polynomial
Example 4x5 + 3 x3 + 2 x2 + 5x + 2
4 5 3 3 2 2 5 1 2 0
struct Poly
{
int coeff;
int exp;
} p[20];
Algorithm
1. Declare an array of structure.
2. Read the number of terms from the keyboard.
3. The number of terms of the polynomial indicates, the number of elements in the array.
4. Use a loop to read the coefficient and exponent of each term of the polynomial.
5. The term should be in the descending order of their exponents.
6. Display the polynomial.
Addition of polynomials
A (x) = 4x5 + 3 x3 + 2 x2 + 5x + 2
4 5 3 3 2 2 5 1 2 0
6 5 4 4 7 2 8 1
DR. V SREENIVASULU 23
A (x) + B (x) = 10x5 +4x4 + 3 x3 + 9 x2 + 13x + 2
10 5 4 4 3 3 9 2 13 1 2 0
Case 3: Exponent of the term in first polynomial < exponent of the term in second
Polynomial
Copy the coefficient and exponent of the greater term to the resultant
polynomial and advance the index of the second polynomial to the next term
and also advance the index
If one of the polynomials gets exhausted copy the remaining terms of the other
polynomial into the resultant polynomial.
Print the resultant polynomial.
Note: Other operations include polynomial subtraction and Multiplication.
DR. V SREENIVASULU 24
9_Write a C Program for Adding Two Polynomials of Different Degrees Using Arrays
to Represent Coefficients for addition of two polynomials and display the Output
#include <stdio.h>
void addPolynomials (int poly1[], int deg1, int poly2[], int deg2, int result [])
{
int i;
int maxDegree = (deg1 > deg2) ? deg1 : deg2;
int main ()
{
int i, degree1, degree2;
DR. V SREENIVASULU 25
for (i = degree2; i >= 0; i--)
{
printf ("Coefficient of x^%d: ", i);
scanf ("%d", &poly2[i]);
}
return 0;
}
OUTPUT
Case 1
Enter degree of first polynomial ... 3
Enter coefficients of first polynomial from highest to lowest degree
Coefficient of x^3: 2
Coefficient of x^2: 0
Coefficient of x^1: 3
Coefficient of x^0: 4
DR. V SREENIVASULU 26
Case 2
Enter degree of first polynomial ... 4
Enter coefficients of first polynomial from highest to lowest degree
Coefficient of x^4: 2
Coefficient of x^3: 3
Coefficient of x^2: 0
Coefficient of x^1: 0
Coefficient of x^0: 4
Enter degree of second polynomial: 3
Enter coefficients of second polynomial from highest to lowest degree)
Coefficient of x^3: 1
Coefficient of x^2: 7
Coefficient of x^1: 0
Coefficient of x^0: 5
Resultant polynomial after addition 2x^4 + 4x^3 + 7x^2 9
Sparse Matrix
Sparse are those matrices that have more number of zeros than non-zero elements.
0 0 1
Sparse Matrix S = 0 7 0 3X3 matix
0 8 0
Remedy: Instead of storing zeros, better to store only non-zero elements in triple matrix
without changing the location.
DR. V SREENIVASULU 27
0 0 1 0
7 0 0 0
Sparse Matrix S-
0 8 1 0
4 0 0 2
0 0 1 0 7 0 0 0 0 8 1 0 4 0 0 2
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <stdio.h>
#define MAX 10
DR. V SREENIVASULU 28
for (j = 0; j < cols; j++)
{
if (sparse [i][j] != 0)
{
triple [k][0] = i;
triple [k][1] = j;
triple [k][2] = sparse[i][j];
k++;
}
}
}
int main()
{
int sparse[MAX][MAX], i, j, rows, cols;
printf ("Enter the number of rows and columns of the sparse matrix... ");
scanf ("%d %d", &rows, &cols);
return 0;
}
DR. V SREENIVASULU 29
OUTPUT
Case 1
Enter the number of rows and columns of the sparse matrix: 4 4
Enter the elements of the sparse matrix:
0010700008104002
Triple Matrix (row, column, value):
Row Column Value
0 2 1
1 0 7
2 1 8
2 2 1
3 0 4
3 3 2
Case 2
Enter the number of rows and columns of the sparse matrix: 6 5
Enter the elements of the sparse matrix:
000070040001005200000800001002
Triple Matrix (row, column, value):
Row Column Value
0 4 7
1 2 4
2 1 1
2 4 5
3 0 2
4 1 8
5 1 1
5 4 2
DR. V SREENIVASULU 30
Indexing: Accessing a specific character in a string by its position.
Example: "Hello"[1] = 'e' (index starts at 0)
#include <stdio.h>
#include <string.h>
int main()
{
int i;
char str1[50];// = " PS students ";
char str2[50];// = "Learning DSA";
printf("Enter a string...");
scanf("%s",str1);
printf("Enter another string...");
DR. V SREENIVASULU 31
scanf("%s",str2);
strcat(str1, str2);
printf("Concatenated String: %s\n", str1);
char str3[50];
strcpy(str3, str1);
printf("Copied String: %s\n", str3);
if (strcmp(str1, str3) == 0)
{
printf("str1 and str3 are equal\n");
}
return 0;
}
OUTPUT
Enter a string...Hyderabad
Enter another string...Khammam
Concatenated String: HyderabadKhammam
Length of str1: 16
Copied String: HyderabadKhammam
str1 and str3 are equal
Reversed String: mammahKdabaredyH
DR. V SREENIVASULU 32
Pattern Matching
Pattern matching is done using string manipulation functions.
A given pattern is verified in the string that is embedded in it or not.
Ex: Text [0…n-1]
Pattern [0…m-1]
For verification, we use different algorithms.
Brute force algorithm is the basic algorithm.
Brute Force Algorithm
Requirements 1. Two strings i) text ii) pattern
Procedure
The first character of the text is compared with the pattern.
If both characters match then compare the second character of the text with the second
character of the pattern. If matched, go to third character. It repeats till the end of the
pattern.
Then, it is declared that the pattern is available. Then no need to compare the
remaining text.
Stop the iteration. Otherwise, declare that the pattern is not available.
Text a b b b a b a b a a b
Pattern a b a A
DR. V SREENIVASULU 33
Algorithm-Brute Force (t (0 ..n-1, p(0…m-1))
{
m = strlen (p);
n = strlen (t);
for (i = 0; i <= n - m; i++)
{
for ( j = 0; j < m; j++)
{
if (t(i + j) != p(j))
break;
}
if (j==m) return i;
}
}
Procedure:
1. Compare the first symbol of the text with the first symbol of the pattern. If both
are equal move i to next location of the text.
2. Again, the second symbol of the text is compared with the pattern. Since, it is
equal, move i to the next location of the text.
3. Third symbol mismatches. If mismatch occurs, shift the pattern one cell to the
right and backtracks the variable i.
#include <stdio.h>
#include<string.h>
DR. V SREENIVASULU 34
if (j == m)
{
return i;
}
}
return -1;
}
int main()
{
char text[100], pattern[50];
if (match != -1)
printf("Pattern found at position... %d\n", match + 1);
else
printf("Pattern not found.\n");
return 0;
}
OUTPUT
Case 1
Enter the main string… abbbababaab
Enter the pattern to search… abaa
Pattern found at position… 7
Case 2
Enter the main string… abbbababaab
Enter the pattern to search… bbaa
Pattern not found.
DR. V SREENIVASULU 35