Algorithms and Complexity Midterm Topics
Algorithms and Complexity Midterm Topics
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”.
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.
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.
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:
Types of Algorithms:
There are several types of algorithms available. Some important algorithms are:
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.
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.
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.
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:
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.
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.
Now let’s design the algorithm with the help of the above pre-requisites:
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
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.
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.
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
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
Examples:
1. Proof Techniques
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 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
Relation:
𝑛
T(n)=2T(2 )+cn
ALGORITHMS & COMPLEXITY
where T(n) represents the running time of Merge Sort.
Compare p=logb a=log2 2=1 with the degree of f(n), which is also 1.
G(x)(1−x−x2)=x. 𝑛 – Input size The size of the input for which the algorithm is
solving the problem.
This function encodes the Fibonacci sequence, and coefficients of xn in its expansion give the n-th
Fibonacci number.
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.
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.
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.
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.
A) For some algorithms, all the cases (worst, best, average) are asymptotically the same. i.e., there are
no worst and best 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.
import java.util.Arrays;
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.
2. Special Array Sum : In this example, we will take an array of length (n) and deals with the following
cases :
If (n) is odd then our output will be the sum of the elements of the array.
import java.util.Arrays;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr1[i];
}
return sum; // (n) is odd
}
15
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.
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.
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.
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.
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.
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 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.
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:
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.
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.
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
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
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.
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
Question 1. Draw a flowchart to find the greatest number among the 2 numbers.
Solution:
Algorithm:
1. Start
3. Now check the condition If a > b, goto step 4, else goto step 5.
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
6. Stop
Flow Chart:
Solution:
Algorithm:
1. Start
2. Input number a
3. Now initialize c = 1
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:
Solution:
Algorithm:
1. Start
2. Now initialize c = 1
4. Print 3 * c
5. c += 1. Then go to step 3.
6. Stop
ALGORITHMS & COMPLEXITY
Flow Chart:
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.
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.
Pseudocode Examples:
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[].
else
HIGH = MID – 1
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.
Here, LOW is the starting index and HIGH is the ending index.
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
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
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?
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?
Question 3) What will be the output of the following pseudocode for a=2, b=7, c=7?
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:
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.
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.
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
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