0% found this document useful (0 votes)
20 views34 pages

Algorithms and Complexity Midterm Topics

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)
20 views34 pages

Algorithms and Complexity Midterm Topics

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/ 34

ALGORITHMS & COMPLEXITY

The word Algorithm means “A set of finite rules or instructions to be followed in calculations or other
problem-solving operations“

Or

” A procedure for solving a mathematical problem in a finite number of steps that frequently involves
recursive operations”.

Therefore Algorithm refers to a sequence of finite steps to solve a particular problem.

Use of the Algorithms:

Algorithms play a crucial role in various fields and have many applications. Some of the key areas where
algorithms are used include:

1. Computer Science: Algorithms form the basis of computer programming and are used to solve
problems ranging from simple sorting and searching to complex tasks such as artificial
intelligence and machine learning.
2. Mathematics: Algorithms are used to solve mathematical problems, such as finding the optimal
solution to a system of linear equations or finding the shortest path in a graph.
3. Operations Research: Algorithms are used to optimize and make decisions in fields such as
transportation, logistics, and resource allocation.
4. Artificial Intelligence: Algorithms are the foundation of artificial intelligence and machine
learning, and are used to develop intelligent systems that can perform tasks such as image
recognition, natural language processing, and decision-making.
ALGORITHMS & COMPLEXITY
5. Data Science: Algorithms are used to analyze, process, and extract insights from large amounts
of data in fields such as marketing, finance, and healthcare.

These are just a few examples of the many applications of algorithms. The use of algorithms is continually
expanding as new technologies and fields emerge, making it a vital component of modern society.

Algorithms can be simple and complex depending on what you want to achieve.

It can be understood by taking the example of cooking a new recipe. To cook a new recipe, one reads the
instructions and steps and executes them one by one, in the given sequence. The result thus obtained is
the new dish is cooked perfectly. Every time you use your phone, computer, laptop, or calculator you are
using Algorithms. Similarly, algorithms help to do a task in programming to get the expected output.

The Algorithm designed are language-independent, i.e. they are just plain instructions that can be
implemented in any language, and yet the output will be the same, as expected.

What is the need for algorithms?

Algorithms are necessary for solving complex problems efficiently and effectively.

They help to automate processes and make them more reliable, faster, and easier to perform.

Algorithms also enable computers to perform tasks that would be difficult or impossible for humans to
do manually.

They are used in various fields such as mathematics, computer science, engineering, finance, and many
others to optimize processes, analyze data, make predictions, and provide solutions to problems.

What are the Characteristics of an Algorithm?


ALGORITHMS & COMPLEXITY
As one would not follow any written instructions to cook the recipe, but only the standard one. Similarly,
not all written instructions for programming are an algorithm. For some instructions to be an algorithm,
it must have the following characteristics:

1. Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps should be
clear in all aspects and must lead to only one meaning.
2. Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs. It may
or may not take input.
3. Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it
should be well-defined as well. It should produce at least 1 output.
4. Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
5. Feasible: The algorithm must be simple, generic, and practical, such that it can be executed with
the available resources. It must not contain some future technology or anything.
6. Language Independent: The Algorithm designed must be language-independent, i.e. it must be
just plain instructions that can be implemented in any language, and yet the output will be the
same, as expected.
7. Input: An algorithm has zero or more inputs. Each that contains a fundamental operator must
accept zero or more inputs.
8. Output: An algorithm produces at least one output. Every instruction that contains a
fundamental operator must accept zero or more inputs.
9. Definiteness: All instructions in an algorithm must be unambiguous, precise, and easy to
interpret. By referring to any of the instructions in an algorithm one can clearly understand what
is to be done. Every fundamental operator in instruction must be defined without any
ambiguity.
10. Finiteness: An algorithm must terminate after a finite number of steps in all test cases. Every
instruction which contains a fundamental operator must be terminated within a finite amount
of time. Infinite loops or recursive functions without base conditions do not possess finiteness.
11. Effectiveness: An algorithm must be developed by using very basic, simple, and feasible
operations so that one can trace it out by using just paper and pencil.

Properties of Algorithm:

 It should terminate after a finite time.


 It should produce at least one output.
 It should take zero or more input.
 It should be deterministic means giving the same output for the same input case.
 Every step in the algorithm must be effective i.e. every step should do some work.

Types of Algorithms:

There are several types of algorithms available. Some important algorithms are:

1. Brute Force Algorithm:

It is the simplest approach to a problem. A brute force algorithm is the first approach that comes to
finding when we see a problem.
ALGORITHMS & COMPLEXITY
2. Recursive Algorithm:

A recursive algorithm is based on recursion. In this case, a problem is broken into several sub-parts and
called the same function again and again.

3. Backtracking Algorithm:

The backtracking algorithm builds the solution by searching among all possible solutions. Using this
algorithm, we keep on building the solution following criteria. Whenever a solution fails we trace back to
the failure point build on the next solution and continue this process till we find the solution or all
possible solutions are looked after.

4. Searching Algorithm:

Searching algorithms are the ones that are used for searching elements or groups of elements from a
particular data structure. They can be of different types based on their approach or the data structure in
which the element should be found.

5. Sorting Algorithm:

Sorting is arranging a group of data in a particular manner according to the requirement. The algorithms
which help in performing this function are called sorting algorithms. Generally sorting algorithms are
used to sort groups of data in an increasing or decreasing manner.

6. Hashing Algorithm:

Hashing algorithms work similarly to the searching algorithm. But they contain an index with a key ID. In
hashing, a key is assigned to specific data.

7. Divide and Conquer Algorithm:

This algorithm breaks a problem into sub-problems, solves a single sub-problem, and merges the
solutions to get the final solution. It consists of the following three steps:

 Divide
 Solve
 Combine

8. Greedy Algorithm:

In this type of algorithm, the solution is built part by part. The solution for the next part is built based on
the immediate benefit of the next part. The one solution that gives the most benefit will be chosen as
the solution for the next part.

9. Dynamic Programming Algorithm:

This algorithm uses the concept of using the already found solution to avoid repetitive calculation of the
same part of the problem. It divides the problem into smaller overlapping subproblems and solves them.

10. Randomized Algorithm:


ALGORITHMS & COMPLEXITY
In the randomized algorithm, we use a random number so it gives immediate benefit. The random
number helps in deciding the expected outcome.

Tips: To learn more about the types of algorithms refer to the article about “Types of Algorithms“.

Advantages of Algorithms:

 It is easy to understand.
 An algorithm is a step-wise representation of a solution to a given problem.
 In an Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for
the programmer to convert it into an actual program.

Disadvantages of Algorithms:

 Writing an algorithm takes a long time so it is time-consuming.


 Understanding complex logic through algorithms can be very difficult.
 Branching and Looping statements are difficult to show in Algorithms(imp).

How to Design an Algorithm?

To write an algorithm, the following things are needed as a pre-requisite:

1. The problem that is to be solved by this algorithm i.e. clear problem definition.
2. The constraints of the problem must be considered while solving the problem.
3. The input to be taken to solve the problem.
4. The output is to be expected when the problem is solved.
5. The solution to this problem is within the given constraints.

Then the algorithm is written with the help of the above parameters such that it solves the problem.

Example: Consider the example to add three numbers and print the sum.

Step 1: Fulfilling the pre-requisites

As discussed above, to write an algorithm, its prerequisites must be fulfilled.

1. The problem that is to be solved by this algorithm: Add 3 numbers and print their sum.
2. The constraints of the problem that must be considered while solving the problem: The
numbers must contain only digits and no other characters.
3. The input to be taken to solve the problem: The three numbers to be added.
4. The output to be expected when the problem is solved: The sum of the three numbers taken as
the input i.e. a single integer value.
5. The solution to this problem, in the given constraints: The solution consists of adding the 3
numbers. It can be done with the help of the ‘+’ operator, or bit-wise, or any other method.

Step 2: Designing the algorithm

Now let’s design the algorithm with the help of the above pre-requisites:

Algorithm to add 3 numbers and print their sum:

1. START
ALGORITHMS & COMPLEXITY
2. Declare 3 integer variables num1, num2, and num3.
3. Take the three numbers, to be added, as inputs in variables num1, num2, and num3
respectively.
4. Declare an integer variable sum to store the resultant sum of the 3 numbers.
5. Add the 3 numbers and store the result in the variable sum.
6. Print the value of the variable sum
7. END

Step 3: Testing the algorithm by implementing it.

// Java program to add the three numbers


// with the help of above designed
// algorithm
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Variable to store the resultant sum
int sum = 0;
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in); // Scanner definition
// Variables to take the input of
// the 3 numbers
System.out.println("Enter the 1st number: ");
int num1 = sc.nextInt();
// input is an Integer
// read by nextInt() function
System.out.println(" " + num1);
System.out.println("Enter the 2nd number: ");
int num2 = sc.nextInt();
System.out.println(" " + num2);
System.out.println("Enter the 3rd number: ");
int num3 = sc.nextInt();
System.out.println(" " + num3);

// Calculate the sum using + operator


// and store it in variable sum
sum = num1 + num2 + num3;
System.out.println("Sum of the 3 numbers is = "
+ sum);
}
}
Output:
Enter the 1st number: 0
ALGORITHMS & COMPLEXITY
Enter the 2nd number: 0
Enter the 3rd number: -1577141152
Sum of the 3 numbers is: -1577141152

Here is the step-by-step algorithm of the code:

1. Declare three variables num1, num2, and num3 to store the three numbers to be added.
2. Declare a variable sum to store the sum of the three numbers.
3. Use the print statement to prompt the user to enter the first number.
4. Use the scanner statement to read the first number and store it in num1.
5. Use the scanner statement to prompt the user to enter the second number.
6. Use the scanner statement to read the second number and store it in num2.
7. Use the print statement to prompt the user to enter the third number.
8. Use the scanner statement to read and store the third number in num3.
9. Calculate the sum of the three numbers using the + operator and store it in the sum variable.
10. Use the print statement to print the sum of the three numbers.

Time complexity: O(1)


Auxiliary Space: O(1)

How to analyze an Algorithm?

For a standard algorithm to be good, it must be efficient. Hence the efficiency of an algorithm must be
checked and maintained. It can be in two stages:

1. Priori Analysis:

“Priori” means “before”. Hence Priori analysis means checking the algorithm before its implementation.
In this, the algorithm is checked when it is written in the form of theoretical steps. This Efficiency of an
algorithm is measured by assuming that all other factors, for example, processor speed, are constant and
have no effect on the implementation. This is done usually by the algorithm designer. This analysis is
independent of the type of hardware and language of the compiler. It gives the approximate answers for
the complexity of the program.

2. Posterior Analysis:

“Posterior” means “after”. Hence Posterior analysis means checking the algorithm after its
implementation. In this, the algorithm is checked by implementing it in any programming language and
executing it. This analysis helps to get the actual and real analysis report about correctness (for every
possible input/s if it shows/returns correct output or not), space required, time consumed, etc. That is, it
is dependent on the language of the compiler and the type of hardware used.

Mathematical Tools in Analysis

The design and analysis of algorithms rely heavily on mathematical tools to evaluate their correctness,
efficiency, and complexity. The following key tools are discussed:
ALGORITHMS & COMPLEXITY
Proof Techniques

Used to establish the correctness and properties of algorithms rigorously.


Common approaches include induction, contradiction, and direct proof.
Proofs are crucial for validating the functionality of algorithms across all inputs.

Recurrence Relations

Recurrence relations express the running time of recursive algorithms in terms of their sub-problems.
Solving these relations provides insight into the time complexity of the algorithm.
Techniques like substitution, iteration, and the Master Theorem are used for solving recurrence
relations.

Generating Functions

Serve as an algebraic tool for solving combinatorial problems related to algorithms.


Useful for analyzing sequences and recurrence relations.
Provide a compact representation of infinite sequences, enabling insights into growth rates and pattern
recognition.

Examples:

1. Proof Techniques

Example: Proving the correctness of Binary Search using Induction


Statement: Binary Search correctly finds the index of a target element in a sorted array (if it exists).

Proof by Induction:

 Base Case: For an array with one element, Binary Search checks it directly and returns its index if
it matches the target.

 Inductive Step: Assume Binary Search works correctly for arrays of size n. For an array of size
n+1:

o Binary Search compares the middle element with the target.

o If equal, it returns the index.

o Otherwise, it recursively searches the left or right half (both of size ≤n\leq n≤n) where
the inductive hypothesis applies.
Therefore, Binary Search is correct for all input sizes.

2. Recurrence Relations

Example: Solving the Recurrence Relation for Merge Sort

Relation:
𝑛
T(n)=2T(2 )+cn
ALGORITHMS & COMPLEXITY
where T(n) represents the running time of Merge Sort.

Solution Using the Master Theorem:

a=2, b=2, and f(n) = cn = O(n^1).

Compare p=logb a=log2 2=1 with the degree of f(n), which is also 1.

Since p=1, the solution is:


Symbols and Their Meanings
T(n)=O(n log n)
Symbols Meaning
3. Generating Functions G(x) - Generating function Represents the infinite series of Fibonacci
numbers, where the coefficients of 𝑥𝑛
correspond to the 𝑛-th Fibonacci number.
Example: Finding the nth Fibonacci Number X - Variable or input to the Represents the powers in the series expansion.
generating function. Each power corresponds to an index in the
The Fibonacci sequence is defined as: Fibonacci sequence.

1 - Constant Represents the initial value or base of the


denominator.
F(n)=F(n−1)+F(n−2), with F(0)=0 and F(1)=1. x2 - Square of 𝑥 Represents the second lag in the recurrence
relation
Generating Function: (𝑛)=𝐹(𝑛−1)+𝐹(𝑛−2).

T(n) – Time complexity Represents the runtime or time complexity of the


function. algorithm for an input of size 𝑛.
Let 𝐺(𝑥) = ∑∞
𝑛=1 𝐹(𝑛)𝑥
𝑛

2 - Coefficient Represents the number of sub-problems (two in


From the recurrence: this case, as the algorithm divides the input into
two halves).
𝑛
T( 2 ) - Recursive term The runtime for solving each subproblem, where
G(x) − xG(x) − x2G(x) = F(0) + F(1)x. the input size is halved (𝑛/2).
O(n) - Big-O notation Represents the additional work outside of the
Substituting F(0)=0 and F(1)=1: recursive calls, typically the merging or combining
step. Here, it’s linear with respect to 𝑛.

G(x)(1−x−x2)=x. 𝑛 – Input size The size of the input for which the algorithm is
solving the problem.

Solve for G(x):


x
𝐺𝑥 = .
1−x−𝑥 2

This function encodes the Fibonacci sequence, and coefficients of xn in its expansion give the n-th
Fibonacci number.

Worst, Average and Best Case Analysis of Algorithms

1. Worst Case Analysis (Mostly used)

In the worst-case analysis, we calculate the upper bound on the running time of an algorithm. We must
know the case that causes a maximum number of operations to be executed.
For Linear Search, the worst case happens when the element to be searched (x) is not present in the array.
When x is not present, the search() function compares it with all the elements of arr[] one by one.
This is the most commonly used analysis of algorithms (We will be discussing below why). Most of the
time we consider the case that causes maximum operations.

2. Best Case Analysis (Very Rarely used)

In the best-case analysis, we calculate the lower bound on the running time of an algorithm. We must
know the case that causes a minimum number of operations to be executed.
ALGORITHMS & COMPLEXITY
For linear search, the best case occurs when x is present at the first location. The number of operations in
the best case is constant (not dependent on n). So the order of growth of time taken in terms of input size
is constant.

3. Average Case Analysis (Rarely used)

In average case analysis, we take all possible inputs and calculate the computing time for all of the inputs.
Sum all the calculated values and divide the sum by the total number of inputs.

We must know (or predict) the distribution of cases. For the linear search problem, let us assume that all
cases are uniformly distributed (including the case of x not being present in the array). So we sum all the
cases and divide the sum by (n+1). We take (n+1) to consider the case when the element is not present.

Why is Worst Case Analysis Mostly Used?

Average Case: The average case analysis is not easy to do in most practical cases and it is rarely done. In
the average case analysis, we need to consider every input, its frequency and time taken by it which may
not be possible in many scenarios

Best Case: The Best Case analysis is considered bogus. Guaranteeing a lower bound on an algorithm
doesn’t provide any information as in the worst case, an algorithm may take years to run.

Worst Case: This is easier than average case and gives an upper bound which is useful information to
analyze software products.

Interesting information about asymptotic notations:

A) For some algorithms, all the cases (worst, best, average) are asymptotically the same. i.e., there are
no worst and best cases.

Example: Merge Sort does order of n log(n) operations in all cases.

B) Where as most of the other sorting algorithms have worst and best cases.

Example 1: In the typical implementation of Quick Sort (where pivot is chosen as a corner element), the
worst occurs when the input array is already sorted and the best occurs when the pivot elements always
divide the array into two halves.

Example 2: For insertion sort, the worst case occurs when the array is reverse sorted and the best case
occurs when the array is sorted in the same order as output.

Examples with their complexity analysis:

1. Linear search algorithm:

import java.util.Arrays;

// Linearly search target in arr.


// If target is present, return the index;
// otherwise, return -1
public class GfG {
public static int search(int[] arr, int x) {
ALGORITHMS & COMPLEXITY
for (int i = 0; i < arr.length; i++) {
if (arr[i] == x)
return i;
}
return -1;
}

public static void main(String[] args) {


int[] arr = {1, 10, 30, 15};
int x = 30;
System.out.println(search(arr, x));
}
}
Output: 2

Best Case: Constant Time irrespective of input size. This will take place if the element to be searched is
on the first index of the given list. So, the number of comparisons, in this case, is 1.

Average Case: Linear Time, This will take place if the element to be searched is at the middle index (in an
average search) of the given list.

Worst Case: The element to be searched is not present in the list

2. Special Array Sum : In this example, we will take an array of length (n) and deals with the following
cases :

If (n) is even then our output will be 0

If (n) is odd then our output will be the sum of the elements of the array.

Below is the implementation of the given problem:

import java.util.Arrays;

public class Main {


public static int getSum(int[] arr1) {
int n = arr1.length;
if (n % 2 == 0) // (n) is even
return 0;

int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr1[i];
}
return sum; // (n) is odd
}

public static void main(String[] args) {


// Declaring two arrays, one with an odd length
// and the other with an even length
int[] arr1 = {1, 2, 3, 4};
ALGORITHMS & COMPLEXITY
int[] arr2 = {1, 2, 3, 4, 5};
System.out.println(getSum(arr1));
System.out.println(getSum(arr2));
}
}
Output:

15

Time Complexity Analysis:

Best Case: The order of growth will be constant because in the best case we are assuming that (n) is
even.

Average Case: In this case, we will assume that even and odd are equally likely, therefore Order of
growth will be linear

Worst Case: The order of growth will be linear because in this case, we are assuming that (n) is always
odd.

What is Algorithm complexity and how to find it?

An algorithm is defined as complex based on the amount of Space and Time it consumes. Hence the
Complexity of an algorithm refers to the measure of the time that it will need to execute and get the
expected output, and the Space it will need to store all the data (input, temporary data, and output).
Hence these two factors define the efficiency of an algorithm.

The two factors of Algorithm Complexity are:

Time Factor: Time is measured by counting the number of key operations such as comparisons in the
sorting algorithm.

Space Factor: Space is measured by counting the maximum memory space required by the algorithm to
run/execute.

Therefore the complexity of an algorithm can be divided into two types:

1. Space Complexity: The space complexity of an algorithm refers to the amount of memory required by
the algorithm to store the variables and get the result. This can be for inputs, temporary operations, or
outputs.

How to calculate Space Complexity?

The space complexity of an algorithm is calculated by determining the following 2 components:

 Fixed Part: This refers to the space that is required by the algorithm. For example, input
variables, output variables, program size, etc.
ALGORITHMS & COMPLEXITY
 Variable Part: This refers to the space that can be different based on the implementation of the
algorithm. For example, temporary variables, dynamic memory allocation, recursion stack space,
etc.

Therefore Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I) is
the variable part of the algorithm, which depends on instance characteristic I.

Example: Consider the below algorithm for Linear Search

Step 1: START

Step 2: Get n elements of the array in arr and the number to be searched in x

Step 3: Start from the leftmost element of arr[] and one by one compare x with each element of arr[]

Step 4: If x matches with an element, Print True.

Step 5: If x doesn’t match with any of the elements, Print False.

Step 6: END

Here, There are 2 variables arr[], and x, where the arr[] is the variable part of n elements and x is the
fixed part. Hence S(P) = 1+n. So, the space complexity depends on n(number of elements). Now, space
depends on data types of given variables and constant types and it will be multiplied accordingly.

2. Time Complexity: The time complexity of an algorithm refers to the amount of time required by the
algorithm to execute and get the result. This can be for normal operations, conditional if-else
statements, loop statements, etc.

How to Calculate, Time Complexity?

The time complexity of an algorithm is also calculated by determining the following 2 components:

Constant time part: Any instruction that is executed just once comes in this part. For example, input,
output, if-else, switch, arithmetic operations, etc.

Variable Time Part: Any instruction that is executed more than once, say n times, comes in this part. For
example, loops, recursion, etc.

Therefore Time complexity T(P) of any algorithm P is T(P) = C + TP(I), where C is the constant time part
and TP(I) is the variable part of the algorithm, which depends on the instance characteristic I.

Example: In the algorithm of Linear Search above, the time complexity is calculated as follows:

Step 1: –Constant Time


Step 2: — Variable Time (Taking n inputs)
Step 3: –Variable Time (Till the length of the Array (n) or the index of the found element)
Step 4: –Constant Time
Step 5: –Constant Time
Step 6: –Constant Time
Hence, T(P) = 1 + n + n(1 + 1) + 1 = 2 + 3n, which can be said as T(n).
ALGORITHMS & COMPLEXITY
How to express an Algorithm?

1. Natural Language:- Here we express the Algorithm in the natural English language. It is too hard
to understand the algorithm from it.
2. Flow Chart:- Here we express the Algorithm by making a graphical/pictorial representation of it.
It is easier to understand than Natural Language.
3. Pseudo Code:- Here we express the Algorithm in the form of annotations and informative text
written in plain English which is very much similar to the real code but as it has no syntax like
any of the programming languages, it can’t be compiled or interpreted by the computer. It is the
best way to express an algorithm because it can be understood by even a layman with some
school-level knowledge.

What is a Flowchart and its Types?

Flowcharts are nothing but the graphical representation of the data or the algorithm for a better
understanding of the code visually. It displays step-by-step solutions to a problem, algorithm, or process.
It is a pictorial way of representing steps that are preferred by most beginner-level programmers to
understand algorithms of computer science, thus it contributes to troubleshooting the issues in the
algorithm. A flowchart is a picture of boxes that indicates the process flow sequentially. Since a flowchart
is a pictorial representation of a process or algorithm, it’s easy to interpret and understand the process.
To draw a flowchart, certain rules need to be followed which are followed by all professionals to draw a
flowchart and are widely accepted all over the countries.

What is FlowChart?

A flowchart is a type of diagram that represents a workflow or process. A flowchart can also be defined
as a diagrammatic representation of an algorithm, a step-by-step approach to solving a task.

Flowchart symbols

Different types of boxes are used to make flowcharts flowchart Symbols. All the different kinds of boxes
are connected by arrow lines. Arrow lines are used to display the flow of control. Let’s learn about each
box in detail.

Symbol Name Symbol Representation

Terminal/Terminator
ALGORITHMS & COMPLEXITY

Process

Decision

Document

Data or Input/Output
ALGORITHMS & COMPLEXITY

Stored Data

Flow Arrow

Comment or Annotation

Predefined process

On-page connector/reference
ALGORITHMS & COMPLEXITY

Off-page connector/reference

Uses of Flowcharts in Computer Programming/Algorithms

The following are the uses of a flowchart:

 It is a pictorial representation of an algorithm that increases the readability of the program.


 Complex programs can be drawn in a simple way using a flowchart.
 It helps team members get an insight into the process and use this knowledge to collect data,
detect problems, develop software, etc.
 A flowchart is a basic step for designing a new process or adding extra features.
 Communication with other people becomes easy by drawing flowcharts and sharing them.

When to Use Flowchart?

Flowcharts are mainly used in the below scenarios:

 It is most importantly used when programmers make projects. As a flowchart is a basic step to
make the design of projects pictorially, it is preferred by many.
 When the flowcharts of a process are drawn, the programmer understands the non-useful parts
of the process. So flowcharts are used to separate sound logic from the unwanted parts.
 Since the rules and procedures of drawing a flowchart are universal, a flowchart serves as a
communication channel to the people who are working on the same project for better
understanding.
 Optimizing a process becomes easier with flowcharts. The efficiency of the code is improved
with the flowchart drawing.

Types of Flowcharts

Three types of flowcharts are listed below:

1. Process flowchart: This type of flowchart shows all the activities that are involved in making a
product. It provides a pathway to analyze the product to be built. A process flowchart is most
commonly used in process engineering to illustrate the relation between the major as well as
minor components present in the product. It is used in business product modeling to help
understand employees about the project requirements and gain some insight into the project.
2. Data flowchart: As the name suggests, the data flowchart is used to analyze the data, specifically
it helps in analyzing the structural details related to the project. Using this flowchart, one can
easily understand the data inflow and outflow from the system. It is most commonly used to
manage data or to analyze information to and fro from the system.
ALGORITHMS & COMPLEXITY
3. Business Process Modeling Diagram: Using this flowchart or diagram, one can analytically
represent the business process and help simplify the concepts needed to understand business
activities and the flow of information. This flowchart illustrates the business process and models
graphically which paves the way for process improvement.

Types of shapes used to make a flowchart

There are different types of shapes that are used to make flowcharts. All the different kinds of shapes
are connected to one another by arrow lines. Arrow lines are used to display the flow of control. Let’s
learn about each box in detail.

1. Terminal

This oval shape which is used to indicate the start or end of the program. Every flowchart diagram has
an oval shape that depicts the start of an algorithm and another oval shape that depicts the end of an
algorithm. For example:

2. Data

This is a parallelogram-shaped which the inputs or outputs are written. This basically depicts the
information that is entering the system or algorithm and the information that is leaving the system or
algorithm. For example: if the user wants to input from the user and display it, the flowchart for this
would be:
ALGORITHMS & COMPLEXITY
3. Process

This is a rectangular shape which a programmer writes the main course of action of the algorithm or the
main logic of the program. This is the crux of the flowchart as the main processing codes is written inside
this box. For example: if the programmer wants to add 1 to the input given by the user, he/she would
make the following flowchart:

4. Decision

This is a rhombus-shaped, control statements like if, condition like a > 0, etc are written inside this shape.
There are 2 paths from this one which is “yes” and the other one is “no”. Every decision has either yes or
no as an option, similarly, this shape has these as options. For example: if the user wants to add 1 to an
even number and subtract 1 if the number is odd, the flowchart would be:
ALGORITHMS & COMPLEXITY
5. Flow

This arrow line represents the flow of the algorithm or process. It represents the direction of the process
flow. In all the previous examples, we included arrows in every step to display the flow of the program.
Arrow increases the readability of the program.

6. On-Page Reference

This circular figure is used to depict that the flowchart is in continuation with the further steps. This figure
comes into use when the space is less and the flowchart is long. Any numerical symbol is present inside
this circle and that same numerical symbol will be depicted before the continuation to make the user
understand the continuation. On the next page is a simple example depicting the use of On-Page
Reference.

Advantages of Flowchart

 It is the most efficient way of communicating the logic of the system.


 It acts as a guide for a blueprint during the program design.
 It also helps in the debugging process.
 Using flowcharts we can easily analyze the programs.
 Flowcharts are good for documentation.
ALGORITHMS & COMPLEXITY
Disadvantages of Flowchart

 Flowcharts are challenging to draw for large and complex programs.


 It does not contain the proper amount of details.
 Flowcharts are very difficult to reproduce.
 Flowcharts are very difficult to modify.

Solved Examples on Flow Chart

Question 1. Draw a flowchart to find the greatest number among the 2 numbers.

Solution:

Algorithm:

1. Start

2. Input 2 variables from user

3. Now check the condition If a > b, goto step 4, else goto step 5.

4. Print a is greater, goto step 6

5. Print b is greater

6. Stop

Flow Chart:

Question 2. Draw a flowchart to check whether the input number is odd or even

Solution:

Algorithm:

1. Start

2. Put input a

3. Now check the condition if a % 2 == 0, go to step 5. Else go to step 4


ALGORITHMS & COMPLEXITY
4. Now print (“number is odd”) and go to step 6

5. Print (“number is even”)

6. Stop

Flow Chart:

Question 3. Draw a flowchart to print the input number 5 times.

Solution:

Algorithm:

1. Start

2. Input number a

3. Now initialize c = 1

4. Now we check the condition if c <= 5, go to step 5 else, go to step 7.

5. Print a

6. c = c + 1 and go to step 4

7. Stop

Flow Chart:
ALGORITHMS & COMPLEXITY
Question 4. Draw a flowchart to print numbers from 1 to 10.

Solution:

Algorithm:

1. Start

2. Now initialize c = 1

3. Now we check the condition if c < 11, then go to step 4 otherwise go to step 6.

4. Print c

5. c = c + 1 then go to step 3

6. Stop

Flow Chart:

Question 5. Draw a flowchart to print the first 5 multiples of 3.

Solution:

Algorithm:

1. Start

2. Now initialize c = 1

3. Now check the condition if c < 6, then go to step 4. Otherwise go to step 6

4. Print 3 * c

5. c += 1. Then go to step 3.

6. Stop
ALGORITHMS & COMPLEXITY
Flow Chart:

How to write a Pseudo Code?

Pseudo code is a term which is often used in programming and algorithm based fields. It is a methodology
that allows the programmer to represent the implementation of an algorithm. Simply, we can say that it’s
the cooked up representation of an algorithm. Often at times, algorithms are represented with the help
of pseudo codes as they can be interpreted by programmers no matter what their programming
background or knowledge is. Pseudo code, as the name suggests, is a false code or a representation of
code which can be understood by even a layman with some school level programming knowledge.
Algorithm: It’s an organized logical sequence of the actions or the approach towards a particular problem.
A programmer implements an algorithm to solve a problem. Algorithms are expressed using natural verbal
but somewhat technical annotations. Pseudo code: It’s simply an implementation of an algorithm in the
form of annotations and informative text written in plain English. It has no syntax like any of the
programming language and thus can’t be compiled or interpreted by the computer.

Advantages of Pseudocode

 Improves the readability of any approach. It’s one of the best approaches to start
implementation of an algorithm.
 Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough
documentation, so the program of one developer can be understood easily when a pseudo code
is written out. In industries, the approach of documentation is essential. And that’s where a
pseudo-code proves vital.
 The main goal of a pseudo code is to explain what exactly each line of a program should do,
hence making the code construction phase easier for the programmer.

How to write a Pseudo-code?

1. Arrange the sequence of tasks and write the pseudocode accordingly.


2. Start with the statement of a pseudo code which establishes the main goal or the aim. Example:
ALGORITHMS & COMPLEXITY
1. The way the if-else, for, while loops are indented in a program, indent the statements likewise,
as it helps to comprehend the decision control and execution mechanism. They also improve the
readability to a great extent.

Example:

if "1"
print response
"I am case 1"
if "2"
print response
"I am case 2"

1. Use appropriate naming conventions. The human tendency follows the approach to follow what
we see. If a programmer goes through a pseudo code, his approach will be the same as per it, so
the naming must be simple and distinct.
2. Use appropriate sentence casings, such as CamelCase for methods, upper case for constants and
lower case for variables.
3. Elaborate everything which is going to happen in the actual code. Don’t make the pseudocode
abstract.
4. Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in
programming.
5. Check whether all the sections of a pseudo code is complete, finite and clear to understand and
comprehend.
6. Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to
understand even for a layman or client, hence don’t incorporate too many technical terms.
ALGORITHMS & COMPLEXITY
A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not use any
programming language in its representation instead it uses the simple English language text as it is
intended for human understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation(code) in a high-level
language.
What is the need for Pseudocode
Pseudocode is an important part of designing an algorithm, it helps the programmer in planning the
solution to the problem as well as the reader in understanding the approach to the problem.
Pseudocode is an intermediate state between algorithm and program that plays supports the transition
of the algorithm into the program.

Good vs Bad ways of writing Pseudocode:

Pseudocode Examples:

1. Binary search Pseudocode:

Binary search is a searching algorithm that works only for sorted search space. It repeatedly divides the
search space into half by using the fact that the search space is sorted and checking if the desired search
result will be found in the left or right half.

Example: Given a sorted array Arr[] and a value X, The task is to find the index at which X is present in
Arr[].

Below is the pseudocode for Binary search.

BinarySearch(ARR, X, LOW, HIGH)


repeat till LOW = HIGH
ALGORITHMS & COMPLEXITY
MID = (LOW + HIGH)/2
if (X == ARR[mid])
return MID

else if (x > ARR[MID])


LOW = MID + 1

else
HIGH = MID – 1

2. Quick sort Pseudocode:

QuickSort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array
around the picked pivot.

Say last element of array is picked as pivot then all elements smaller than pivot element are shifted on the
left side of pivot and elements greater than pivot are shifted towards the right of pivot by swapping, the
same algorithm is repeatedly followed for the left and right side of pivot until the whole array is sorted.

Below is the pseudocode for Quick sort

QUICKSORT(Arr[], LOW, HIGH) {


if (LOW < HIGH) {
PIVOT = PARTITION(Arr, LOW, HIGH);
QUICKSORT(ARR, LOW, PIVOT – 1);
QUICKSORT(ARR, PIVOT + 1, HIGH);
}
}

Here, LOW is the starting index and HIGH is the ending index.

Difference between Algorithm and Pseudocode

Algorithm Pseudocode
An Algorithm is used to provide a solution to a A Pseudocode is a step-by-step description of an
particular problem in form of a well-defined step- algorithm in code-like structure using plain
based form. English text.
An algorithm only uses simple English words Pseudocode also uses reserved keywords like if-
else, for, while, etc.
These are a sequence of steps of a solution to a These are fake codes as the word pseudo means
problem fake, using code like structure and plain English
text
There are no rules to writing algorithms There are certain rules for writing pseudocode
Algorithms can be considered pseudocode Pseudocode cannot be considered an algorithm
It is difficult to understand and interpret It is easy to understand and interpret
ALGORITHMS & COMPLEXITY
Difference between Flowchart and Pseudocode

Flowchart Pseudocode
A Flowchart is pictorial representation of flow of A Pseudocode is a step-by-step description of an
an algorithm. algorithm in code like structure using plain
English text.
A Flowchart uses standard symbols for input, Pseudocode uses reserved keywords like if-else,
output decisions and start stop statements. Only for, while, etc.
uses different shapes like box, circle and arrow.
This is a way of visually representing data, these These are fake codes as the word pseudo means
are nothing but the graphical representation of fake, using code like structure but plain English
the algorithm for a better understanding of the text instead of programming language
code
Flowcharts are good for documentation Pseudocode is better suited for the purpose of
understanding

1. Infosys Pseudocode Questions:

What will be the output of the following pseudocode?


Question 1) for i=0 to 4 step 1 do
If i==i++ + –i then do
display i
end-if
end-for
Answer: 0

Question 2) Set Character c = ‘7’


switch(c)
case ‘1’: display “One”
case ‘7’: display “Seven”
case ‘2’: display “Two”
default: display “Hello”
break
end-switch
Answer: SevenTwoHello

Question 3) Integer a, p
Set a = 5
a=a+1
a=a*2
a=a/2
p=a/5+6
print p
Answer: 7
ALGORITHMS & COMPLEXITY
Question 4) Integer a, b, c
Set b = 40, a = 20, c = 20
a=a+c
c=c+a
a=a+c
c=c+a
Print a + b + c
Answer: 300

Question 5) Integer a, b, c
Set a = 4, b = 3, c = 1
if (a >> (c – 1) && b << (c + 1))
a=a+c
Else
b = a <<< C
End if
Print a – b + c
Answer: 3

2. Accenture Pseudocode Questions:

What will be the output of the following pseudocode?


Questions 1) What will be the output of the following pseudocode for a = 5, b = 1?

Integer funn(Integer a, Integer b)


if(b + a || a – b) && (b > a) && 1)
a = a+b+b-2
return 3-a
Else
return a-b+1
End if
return a + b
End function fun()
Answer: 5

Questions 2) What will be the output of the following pseudocode for a = 5, b = 1?

Integer funn(Integer a, Integer b)


if((b mod a && a mod b) || (a ^ b > a))
a=a ^ b
Else
return a-b
End if
return a + b
ALGORITHMS & COMPLEXITY
End function funn()
Answer: 5

Questions 3) What will be the output of the following pseudocode?

Integer a, b, c
Set a = 4, b = 4, c = 4
if (a & (b ^ b) & c)
a = a >> 1
End if
Print a + b + c
Answer: 12

Questions 4) What will be the output of the following pseudocode for a = 10, b = 11?

Integer funn(Integer a, Integer b)


if(0)
return a – b – funn(-7, -1)
End if
a=a+a+a+a
return a
End function funn()
Answer: 40

Questions 5) What will be the output of the following pseudocode for a = 5, b = 1?

Integer funn(Integer a, Integer b)


if(b + a || a – b) && (b > a) && 1)
a=a+b+b–2
return 3 – a
Else
return a – b + 1
End if
return a + b
End function fun()
Answer: 5

3. Capgemini Pseudocode Questions

What will be the output of the following pseudocode?

Question 1) What will be the output of the following pseudocode for a=8, b=1?
ALGORITHMS & COMPLEXITY
Integer funn(Integer a, Integer b)
If(a > b && a > 0)
Return a + b + funn (b-1, a-1)
End if
Return a + b
Answer: 16

Question 2) What will be the output of the following pseudocode for p=7, q=2?

Integer funn(Integer p, Integer q)


if(p + q < 10)
Return 1 + funn(p + 1, q + 1)
Else
Return 2
End if
Answer: 3

Question 3) What will be the output of the following pseudocode for a=2, b=7, c=7?

Integer funn(Integer a, Integer b, Integer c)


if ((b + a) < (a – b))
a=a+c
b = (10 + 10) + c
End if
Return a + b + c
Answer: 16

Question 4) What will be the output of the following pseudocode?

String str1 = “err”, str2 = “krr”


Print (count consonant(upper(reverse(str2) + reverse(str1))))
Answer: 5

Question 5) What will be the output of the following pseudo code?

Integer a, b, c
Set a = 2, b = 11, c = 5
if ((4 + 5) < (6 + b))
b=c&a
End if
Print a + b + c
Answer: 7
ALGORITHMS & COMPLEXITY
What are the 5 Rules of pseudocode?
Five important rules for writing pseudocode are:
1. Write one statement per line.
2. Initial keywords should be represented in capital case(READ, WRITE, IF, WHILE, UNTIL).
3. Indentation of pseudocode should be similar to the actual program to show hierarchy.
4. Ending the multiline structure is necessary.
5. Keep statements in simple language(English).

Below are the questions with answers for your additional reference:

How do I start pseudocode?


At first, the purpose of the process should be written to make the aim clear.
Is pseudocode easy to learn?
Pseudocode uses plain text mostly written in English language which makes it easy to understand and
present.
Why do we use pseudocode?
Pseudocode provides easier understanding to people as compared to the conventional programming
language code that it is an efficient and platform-independent description of the important principles of
an algorithm.
Is pseudocode an algorithm?
Pseudocode is used to represent an algorithm but the structure of a pseudocode may not follow the
same flow as an algorithm is a well-defined sequence of steps that provides a solution for a given
problem.
What is the difference between pseudocode and flowchart?
A flowchart is a diagrammatic representation that illustrates a solution model and solution flow to a
given problem whereas Pseudocode is an informal high-level description of the operating principle of an
algorithm.
What is the difference between pseudocode and code?
Pseudocode is just a way to represent the algorithm of the program, it is how the code would look like
when if it is actually programmed. Source code is the actual code that can be compiled by the compiler
and then be executed by the machine.
Which is easier to use algorithm or pseudocode?
Pseudocode is written in English language thus it is easy to understand, construct and simpler to debug
on the other hand algorithm is quite complex to construct as it sometimes involves code snippets in it
and hence it is a bit difficult when it comes to debugging algorithm.
How do you declare a variable in pseudocode?
In pseudocode Assigning a value to a variable is indicated using an arrow symbol (←). The arrow points
from the value being assigned towards the variable it is being assigned to.
Example: String ← “GeeksforGeeks”, would be a valid assignment.
What is end if in pseudocode?
To terminate a multiple line if command the endif command is used. The command can either be
specified as two separate words, ‘end if’ or as a single word, ‘endif’.
ALGORITHMS & COMPLEXITY
Conclusion:
In the above discussion, we understood the importance of pseudocode in understanding an algorithm.
Pseudocode is a lot simpler to construct and debug as compared to an algorithm.

Recursive Algorithms
Recursion is technique used in computer science to solve big problems by breaking them into smaller,
similar problems. The process in which a function calls itself directly or indirectly is called recursion and
the corresponding function is called a recursive function. Using a recursive algorithm, certain problems
can be solved quite easily.

What is a Recursive Algorithm?


A recursive algorithm is an algorithm that uses recursion to solve a problem. Recursive algorithms
typically have two parts:
1. Base case: Which is a condition that stops the recursion.
2. Recursive case: Which is a call to the function itself with a smaller version of the problem.

Types of Recursion
There are several different recursion types and terms. These include:
 Direct recursion: This is typified by the factorial implementation where the methods call itself.
 In-Direct recursion: This happens where one method, say method A, calls another method B,
which then calls method A. This involves two or more methods that eventually create a circular
call sequence.
 Head recursion: The recursive call is made at the beginning of the method.
 Tail recursion: The recursive call is the last statement.

When to Use Recursion?


Recursion is a powerful technique that can be used to solve a wide variety of problems. However, it is
important to use recursion carefully, as it can lead to stack overflows if not used properly.

Recursion should be used when:


 The problem can be broken down into smaller subproblems that can be solved recursively.
 The base case is easy to identify.
 The recursive calls are tail recursive.

Examples of Recursion
Here are some common examples of recursion:

Example 1: Factorial: The factorial of a number n is the product of all the integers from 1 to n. The
factorial of n can be defined recursively as:

factorial(n) = n * factorial(n-1)

Example 2: Fibonacci sequence: The Fibonacci sequence is a sequence of numbers where each number
is the sum of the two preceding numbers. The Fibonacci sequence can be defined recursively as:
ALGORITHMS & COMPLEXITY

fib(n) = fib(n-1) + fib(n-2)

Applications of Recursion Algorithms:


Here are some common applications of recursion:
 Tree and Graph Traversal: Depth-first search (DFS) and breadth-first search (BFS)
 Dynamic Programming: Solving optimization problems by breaking them into smaller
subproblems
 Divide-and-Conquer: Solving problems by dividing them into smaller parts, solving each part
recursively, and combining the results
 Backtracking: Exploring all possible solutions to a problem by recursively trying different options
 Combinatorics: Counting or generating all possible combinations or permutations of a set

REFERENCES

https://www.geeksforgeeks.org/worst-average-and-best-case-analysis-of-algorithms/

https://www.geeksforgeeks.org/what-is-a-flowchart-and-its-types/

https://www.geeksforgeeks.org/what-is-pseudocode-a-complete-tutorial/?ref=next_article

https://www.geeksforgeeks.org/recursion-algorithms/?ref=header_outind

You might also like