Algorithms and Programming Concepts
Algorithms and Programming Concepts
AND
PROGRAMMING CONCEPTS
2019
PROGRAMME COORDINATOR
Prof. Sonali Karale
COURSE WRITERS
Prof. Vidya Kumbhar Prof. Sonal Khosla
Ms. Prerna Patil Prof. Nidhi Khare
EDITOR
Ms. Neha Mule
Acknowledgement
Every attempt has been made to trace the copyright holders of materials reproduced in this book.
Should any infringement have occurred, SCDL apologises for the same and will be pleased to make
necessary corrections in future editions of this book.
PREFACE
An algorithm is an effective method expressed as a finite list of well-defined instructions for calculating
a function. Starting from an initial state and initial input, the instructions describe a computation
that, when executed, proceeds through a finite number of well-defined successive states, eventually
producing “output” and terminating at a final ending state. The transition from one state to the next is
not necessarily deterministic; some algorithms, known as randomised algorithms, incorporate random
input. A sorting algorithm is an algorithm that puts elements of a list in a certain order. A search
algorithm is an algorithm for finding an item with specified properties among a collection of items.
The items may be stored individually as records in a database.
Once you go through the various methods of writing algorithms given in this SLM, you will be able to
apply them in any programming languages. We have also discussed special problems and algorithms
which will help the learners to understand and implement the concepts studied in the earlier units.
iii
ABOUT THE AUTHORS
Prof. Vidya Kumbhar has completed her Master of Computer Management (MCM) and Master of
Computer Applications (MCA). She has more than 10 years of teaching experience for various man-
agement institutes in Information Technology domain.
She is also associated with different institutes for various educational related assignments. She has
worked on various software development projects in National Informatics Centre, Pune and is cur-
rently working on minor research projects of Symbiosis Institute of Research and Innovation. She is
also working as Assistant Professor, and pursuing her PhD from Symbiosis International University,
Pune. She had published various research papers in National and International Journals and confer-
ences.
Prof. Sonal Khosla has completed her Master in Computer Application (MCA) from Maharishi
Dayanand University, Rohtak. She has nine plus years of teaching experience and is currently work-
ing with Symbiosis Institute of Computer Studies and Research, Pune, as Assistant Professor. Before
joining SICSR, she has worked with Ansal Institute of Technology, Gurgaon.
Her areas of specialisations are Database Management, Computer Networks, Algorithm Designing
and Programming. She also has various research papers to her credit in various national and interna-
tional journals and conferences.
Prof. Prerna Patil has completed her Master in Computer Science from Pune University. She has
nine plus years of software development/IT experience. Furthermore, she has rich experience in
Academics and Training. She has published several articles and has won the Trainer of the Year’
2010 award at Oracle Financial Service Software Limited. Her areas of specialization include cloud
computing, trends in software development and agile methodology.
Prof. Nidhi Khare has a rich experience of 13 years in Academics, Industry as well as Corporate
Training. She has also headed the Computer Department of a college during her Academics career.
Along with Masters in Computer Applications, she has Certifications in Advanced Computing and
Office Automation to her credit. She has published eight papers in National and International con-
ferences. She was the Faculty of Information Technology at SCDL.
iv
CONTENTS
2 Algorithms 13-36
2.1 Introduction
2.2 Basics of Algorithm
2.3 Benefits of Algorithm
2.4 Constructs for developing Algorithm
2.4.1 Sequence
2.4.2 Decision
2.4.3 Repetition
2.5 Tools to represent an Algorithm
2.5.1 Flowchart
2.6 Concept of Modularity and Sub-Algorithms
2.7 Concept of Object Oriented Programming
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
v
Unit No. TITLE Page No.
3 Designing and Analysing Algorithms 37-54
3.1 Introduction
3.2 Desirable Properties of an Efficient Algorithm
3.3 Computational Complexity of Algorithms
3.4 Asymptotic Notations
3.5 Different Analysis of Algorithms
3.6 Example Analysis
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
4 Writing Language-Neutral Algorithms 55-66
4.1 Introduction
4.2 Need for Language-Neutral Algorithms
4.3 Components of an Algorithm
4.4 Standard Format for writing an Algorithm
4.4.1 Predefined Keywords for an Algorithm
4.5 Organisation of an Algorithm
4.6 Verifying if Algorithm is Language-Neutral
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
vi
Unit No. TITLE Page No.
5 Algorithms for Programming Cases 67-88
5.1 Introduction
5.2 Sequential Flow
5.3 Random Jump in the Flow
5.4 Conditional Flow
5.5 Repetitive Flow
5.6 Iterative Flow
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
vii
Unit No. TITLE Page No.
viii
Pseudocodes
UNIT
1
Structure:
1.1 Introduction
1.2 Writing Pseudocodes
1.3 Rules for writing Pseudocodes
1.4 Writing Different Statements in Pseudocode
1.4.1 Sequence Statements in Pseudocode
1.4.2 Selection Statements in Pseudocode
1.4.3 Repetition Statements in Pseudocode
1.5 Advantages and Disadvantages of Pseudocode
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
Pseudocodes 1
Notes
Objectives
----------------------
After going through this unit, you will be able to:
----------------------
l Discuss imitation of the code before writing the actual one
----------------------
l Explain the structures available in various programming languages
---------------------- l Analyse the logic for writing computer programs
----------------------
---------------------- where marks is a variable that stores the value entered by the user.
----------------------
Display marks
----------------------
Write marks
----------------------
This statement prints the value stored in the variable marks. The value can ----------------------
be entered by the user or assigned to the variable.
To assign some value to a variable, a simple assignment statement can be written ----------------------
as follows: ----------------------
a=5 ----------------------
where the value at the right-hand side of the equal to operator is assigned to the ----------------------
variable a.
----------------------
The right-hand side can also contain an expression, which is computed
and assigned to the left-hand side. ----------------------
For example,
----------------------
a = 5*2
----------------------
So the result of computing 5*2 is assigned to the variable a.
----------------------
“Calculate” and “compute” words can be used for any kind of arithmetic
operations. These operations can be specified using words or mathematical ----------------------
symbols. The basic operators are also used, since pseudocode is a mimic of the
----------------------
actual code.
The list of various mathematical operators that can be used in a pseudocode ----------------------
are as follows. Also the order of operation of any operation in any expression is ----------------------
given from top to bottom.
Table 1.1 Mathematical Operators used in Pseudocode ----------------------
Operator Function
----------------------
() Parenthesis ----------------------
^ or ^^ Exponentiation ----------------------
- Negation ----------------------
*, / Multiplication, Division ----------------------
Pseudocodes 3
Notes % Modulus or Remainder
---------------------- +, - Addition, Subtraction
---------------------- = Assignment
----------------------
----------------------
Activity 1 ----------------------
----------------------
Find the value of x.
----------------------
x = 2 + 3 *2 / 1 ^ 2 - (2 + 3)
----------------------
----------------------
1.3 RULES FOR WRITING PSEUDOCODES
----------------------
Although pseudocode is written in an informal language, it is still
necessary to follow certain rules and conventions to make it mimic the code. ----------------------
Following are certain points to be kept in mind to write pseudocode:
----------------------
●● It should be able to convey the intention of the program.
----------------------
●● The statements should be simple and unambiguous.
●● Since it is a balance between code and informal natural language, it is ----------------------
necessary to follow the rules of both.
----------------------
●● Precise and comprehensible English sentences should be written instead
of full sentences. ----------------------
●● Comments should be included where useful and required for better ----------------------
understanding of the code.
●● Variable names should be written as mnemonics, so that it is easy to ----------------------
remember. They are also called identifiers. An identifier should not ----------------------
contain spaces.
●● Although the syntax is not important, it is better to use conventional ----------------------
programming statements like begin/end. ----------------------
●● Programming shorthand should be used instead of using equivalent
English sentences for the same, e.g., a group of statements can be repeated ----------------------
using while statement. ----------------------
●● For better readability, use one statement per line and should represent one
operation to be performed. ----------------------
Pseudocodes 5
Notes ●● Keywords should be written in capital letters, e.g., READ, GET, etc.
●● If hierarchical statements are used, then indent the statements.
----------------------
●● The code should be as far as possible written in a language-independent
---------------------- form.
---------------------- It means the values entered by the keyboard go into the three variables.
The first value entered goes into principal, the second value goes into rate and
---------------------- the third value goes into time.
---------------------- The statement
---------------------- Print si
---------------------- prints the value contained in the variable si to the output screen.
The comparison for the given values is done using the If-End If construct. ----------------------
It allows the branching of code with the evaluation of the Boolean expression.
If the Boolean expression returns true, then the set of statements associated ----------------------
with the true branch is executed. Otherwise, the set of statement with the false ----------------------
branch is executed (if given).
For example, pseudcode to check whether a given number is odd or even. ----------------------
d=number%2 ----------------------
If d==0 ----------------------
Print “Number is even” ----------------------
End if
----------------------
----------------------
Pseudocodes 7
Notes In the above pseudocode, a number is taken as input from the user and
stored in the variable number. The value of the number is divided by 2 and the
---------------------- remainder is stored in the variable d.
---------------------- Now the decision or selection control statement checks whether the value
of the remainder is 0 or not. If it is 0, the print statement is executed and prints
---------------------- “Number is even” on the output screen. If it is not equal to 0, it terminates the
code. Selection statement allows the programmer to compare the value of d
----------------------
with 0 and then make a decision.
---------------------- Sometimes, it is required to print another message if the comparison is
not true. In this situation if-Else-End if construct is used.
----------------------
Read number
----------------------
d=number%2
----------------------
If d==0
----------------------
Print “Number is even”
----------------------
else
---------------------- Print “Number is odd”
---------------------- End if
---------------------- Boolean expressions can be made more complex with the use of logical
operators. The different logical operators that are used in a Boolean expression
----------------------
are given in Table 1.3.
---------------------- Table 1.3 Logical Operators used in a Boolean Expression
---------------------- Logical Operator Function
----------------------
AND Returns true when both the conditions
---------------------- (Boolean expressions) are true
OR Returns true if either condition (Boolean expression) is true
----------------------
NOT Returns true if the condition (Boolean expression) is false
----------------------
Suppose there is a situation where a decision has to be made based on
---------------------- the condition if a given number is even and also a multiple of seven. In such
a scenario, the AND operator can be used. It will check both the conditions of
----------------------
even number and multiple of seven.
----------------------
Read number
----------------------
If number %2==0 AND number %7==0 then
---------------------- Print “ Even and multiple of seven”
---------------------- End if
●● While ----------------------
●● Do-while ----------------------
●● For loop
----------------------
So with the help of sequence/selection/repetition statements a complex logic
can be created to handle a variety of decision scenarios. ----------------------
----------------------
Check your Progress 2
----------------------
Fill in the blanks.
----------------------
1. _________ is another name for a loop structure.
----------------------
State True or False.
1. Logical operator AND and OR are used in if statement only. ----------------------
----------------------
----------------------
Pseudocodes 9
Notes
Activity 2
----------------------
----------------------
---------------------- ●● Since there is no standard, pseudocode written by two persons will differ.
----------------------
Summary
----------------------
●● Pseudocode is a detailed description of an algorithm or computer program
---------------------- with more focus on readability and understandability and less focus on
---------------------- technical requirements. It is written in a formally styled natural language.
It can be best described as a combination of code and English language.
----------------------
----------------------
Keywords
----------------------
●● Sequence: An ordered list.
----------------------
●● Selection: To select from the available list.
●● Iteration: Repetition statement. ----------------------
----------------------
Self-Assessment Questions
----------------------
1. Explain pseudocodes.
----------------------
2. Explain the method of writing pseudocodes for iteration statements.
----------------------
3. Write a pseudocode to accept three numbers and find their average.
----------------------
Answers to Check your Progress
----------------------
Check your Progress 1
----------------------
Multiple Choice Single Response.
----------------------
1. After a programmer plans the logic of a program, he will next:
iv. Code the program ----------------------
4. True ----------------------
5. True ----------------------
----------------------
Pseudocodes 11
Notes Check your Progress 2
Fill in the blank.
----------------------
1. Iteration is another name for a loop structure.
----------------------
State True or False.
---------------------- 1. True
---------------------- 2. True
---------------------- 3. False
Multiple Choice Single Response.
----------------------
1. Before the user’s selection enters the selection structure for the loop, it
---------------------- should be :
---------------------- i. Validated
----------------------
Suggested Reading
----------------------
1. Awad, Elias M. Systems Analysis and Design. Illinois: Richard D. Irwin.
----------------------
2. Goel, Anita. Computer Fundamentals. New Delhi: Pearson Education.
---------------------- 3. Huang, Chung-Yang (Ric), Chao-Yue Lai and Kwang-Ting (Tim) Cheng.
“Fundamentals of algorithms”. Electronic Design Automation. Morgan
----------------------
Kaufmann Publishers.
---------------------- 4. ITL Education Solutions Limited. Introduction to Information Technology.
New Delhi: Pearson Education India.
----------------------
5. Sinha, Pradeep and Priti Sinha. Computer Fundamentals. New Delhi:
---------------------- BPB Publications.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
2
Structure:
2.1 Introduction
2.2 Basics of Algorithm
2.3 Benefits of Algorithm
2.4 Constructs for developing Algorithm
2.4.1 Sequence
2.4.2 Decision
2.4.3 Repetition
2.5 Tools to represent an Algorithm
2.5.1 Flowchart
2.6 Concept of Modularity and Sub-Algorithms
2.7 Concept of Object Oriented Programming
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
Algorithms 13
Notes
Objectives
----------------------
---------------------- After going through this unit, you will be able to:
----------------------
2.1 INTRODUCTION
----------------------
We all know that computer is an electronic device and it performs the tasks
---------------------- as per the set of instructions provided to it. The set of instructions is termed as
program. Planning of a program involves defining its logic, that is, defining the
---------------------- correct sequence of instructions needed to solve the problem. The process of
---------------------- defining step- by-step procedure to solve the problem is termed as algorithm.
In this unit, we will try to understand the basics of algorithm along with the
---------------------- different constructs used in designing the algorithm and concept of OOP.
----------------------
2.2 BASICS OF ALGORITHM
----------------------
The term “algorithm” was originally referred to as any calculation or
---------------------- computation performed by applying set of rules applied to numbers. It represents
a solution to a problem. In our day-to-day life we perform many activities and
---------------------- we come across different problems too. To complete these activities or to solve
---------------------- these problems we follow intellectual steps to solve the problem. We follow a
method for carrying out some sequence of events, resulting in accomplishing the
---------------------- task and if we want these tasks to be performed by computer we must somehow
describe it to the computer too.
----------------------
The algorithm is the sequence of steps to take and get the result. It refers
---------------------- to the logic of a program. It is a step-by-step description of how to arrive at a
solution to a given problem. It is defined as a sequence of instructions that when
---------------------- executed in the specified sequence, gives the desired result. Figure 2.1 shows
---------------------- the notion of algorithm.
----------------------
----------------------
----------------------
----------------------
Algorithms help to document the “how to” part for accomplishing a ----------------------
particular task. Once the algorithm is written it can be used to solve the similar
----------------------
group of related tasks. Besides this algorithm has following benefits:
Algorithms 15
Notes 1. Better Problem Solving: Algorithm is a systematic process. It involves
identifying inputs, variables and different processes, tasks required for
---------------------- problem solving. This makes problem solving more rational.
---------------------- 2. Improved Efficiency: Algorithms improve the efficiency of solving
the problem. It checks whether all the input variables are considered in
---------------------- problem solving or not. Thus, it makes decision-making more consistent
and efficient.
----------------------
3. Provides Clarity: Algorithm provides clarity. As algorithm is a step-by-
---------------------- step process of problem solving, it provides easy access to identification
of errors and loopholes from the entire process. Thus, it provides clarity
----------------------
of the problem to the problem solver.
---------------------- 4. Provides Reusability: Once the algorithm is written it can be reused for
a similar type of problem solving.
----------------------
Let us see some more examples of algorithm.
----------------------
Example 1: Algorithm to display the addition of three numbers.
----------------------
Step 1: Start the algorithm.
---------------------- Step 2: Read the first number.
---------------------- Step 3: Read the second number.
----------------------
Activity 1 ----------------------
----------------------
Write an algorithm to calculate the area for different geometrical shapes,
such as circle, rectangle, triangle and square. ----------------------
----------------------
2.4 CONSTRUCTS FOR DEVELOPING ALGORITHM
----------------------
Constructs are nothing but different forms with the help of which an
----------------------
algorithm can be built. Constructs make an algorithm not only easy to understand
but also to debug and trace the errors. There are three types of constructs. ----------------------
2.4.1 Sequence
----------------------
In this type of construct the set of instructions are written sequentially.
The instructions are just written one after another. Figure 2.2 shows the ----------------------
diagrammatic representation of the same. ----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Fig. 2.2: Sequence Construct
----------------------
Each action is performed one after the other from top to bottom and left to
right as written. The statements are executed without any condition checking. A ----------------------
sequence construct can be a part of selection and repetition statements as well.
----------------------
Example 3: Algorithm to display the average of three numbers.
----------------------
Step 1: Start
Step 2: Read the first number. ----------------------
Step 3: Read the second number. ----------------------
----------------------
Algorithms 17
Notes Step 4: Read the third number.
----------------------
----------------------
----------------------
----------------------
a + 1 == b true ----------------------
a>b false ----------------------
a!=b true
----------------------
The comparison for the given values is done using the If-End If construct.
It allows the branching of code with the evaluation of the Boolean expression. ----------------------
If the Boolean expression returns true, then the set of statements associated with
----------------------
the true branch is executed. Otherwise the set of statement with the false branch
is executed (if given). ----------------------
Example 6: Algorithm to check whether number is even or odd. ----------------------
Step 1: Start the algorithm.
----------------------
Step 2: Read number a.
Step 3: If a%2==0 ----------------------
Step 4: Display ‘a’ is even ----------------------
Step 5: Else display a is odd.
----------------------
Step 6: End the algorithm.
----------------------
Example 7: Algorithm to find greatest of two numbers.
----------------------
Step 1: Start the algorithm.
----------------------
Step 2: Declare two variables a & b.
Step 3: If a>b ----------------------
Step 4: Display a is largest. ----------------------
Algorithms 19
Notes Step 5: Else display b is largest.
---------------------- Suppose there is a situation where a decision has to be made based on the
given condition, to check whether a given number is even and also a multiple of
---------------------- seven. In such a scenario, the AND operator can be used. It will check both the
---------------------- conditions of even number and multiple of seven.
Example 9: Algorithm to calculate the tax for an employee.
----------------------
Assume that salary is between 50,000 and 1,00,000, the tax percentage is
---------------------- 5% else tax percentage is 10%.
---------------------- Step 1: Start the algorithm.
Step 2: Read salary
----------------------
Step 3: If salary>50,000 and salary <1,00,000
----------------------
Step 4: tax=salary*0.05
---------------------- Step 5: Else tax=salary*0.10
----------------------
Temperature greater than or equal to 30 and less than 35: Too Hot ----------------------
Temperature greater than or equal to 35: Too Too Hot ----------------------
Step 1: Start the algorithm. ----------------------
Step 2: Read temperature.
----------------------
Step 3: If temperature<15
----------------------
Step 4: Display message as “Too Too Cold”.
----------------------
Step 5: Else If temperature>=15 AND temperature<20
Step 6: Display message as “Too Cold”
----------------------
Step7: Else If temperature>=20 AND temperature<25 ----------------------
Step8: Display message as “Cold” ----------------------
Step9: Else If temperature>=25 AND temperature<30
Step10: Display message as “Normal” ----------------------
Step11: Else If temperature>=30 AND temperature<35
----------------------
Step12: Display message as “Too Hot”
Step13: Else display message as “Too Too Hot” ----------------------
Step14: End the algorithm.
----------------------
2.4.3 Repetition
----------------------
Sometimes in problem solving we need to execute the same set of
instructions repeatedly. In such cases repetition or looping constructs are used. ----------------------
Figure 2.4shows the diagrammatic representation of the same.
----------------------
While(<condition>)
----------------------
{
----------------------
Action(s)
----------------------
}
----------------------
Fig. 2.4: Repetition Construct
----------------------
----------------------
Algorithms 21
Notes Example 10: Algorithm to find the correct seat in a movie theatre.
begin // Algorithm for finding the correct seat in a movie theatre
----------------------
repeat
----------------------
shift along the aisle to the next row of seats
---------------------- until the row number matches with the one printed on the ticket
---------------------- repeat
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Activity 2
----------------------
1. Write an algorithm to read a number from user and check whether it is ----------------------
prime number or not.
----------------------
2. Write an algorithm to print Fibonacci numbers from 1 to 100.
----------------------
----------------------
2.5 TOOLS TO REPRESENT AN ALGORITHM
----------------------
There are three main tools used to represent an algorithm. They are the
flowchart, pseudocode and the actual code. In the previous unit, we have learned ----------------------
in detail about pseudocode. Let us understand flowchart here.
----------------------
2.5.1 Flowchart
----------------------
Flowcharts are also called “Process flowcharts”. They were invented
by Frank Gilberth in 1921. They are pictorial representations of an algorithm. ----------------------
A flowchart does not use sentences but symbols. The words are enclosed in
symbols which are linked by flow lines with conceptual meanings indicated by ----------------------
their shapes. Flowcharts are the most common method of describing algorithms.
----------------------
Flowcharts are classified in four main types as document flow chart, system
flowchart, data flow- chart and program flowchart. Program flow chart is the ----------------------
tool to represent algorithm in pictorial format.
----------------------
Let us understand now the advantages of flowcharts:
1. They show logical relationships clearly. ----------------------
Algorithms 23
Notes 5. They are useful to the system analyst for experimenting with different
approaches to a particular problem.
----------------------
Table 2.4 shows different symbols to draw flowcharts.
---------------------- Table 2.4 Flow Chart Symbols
---------------------- Sr.No Symbol Symbol Meaning
---------------------- 1. This symbol indicates the beginning or
the end of the flowchart. This is filled
---------------------- with the words “start”, “stop” or the
name of the subroutine. This symbol is
----------------------
oval in shape.
---------------------- 2. This symbol is used to represent
processes like assigning a value to a
---------------------- variable or sorting a number. The shape
---------------------- of this symbol is a rectangle. It has one
arrow going inside to denote the input
---------------------- data to the process and another arrow
leaving from this symbol to denote the
---------------------- processed data.
---------------------- 3. Subroutine, also called subprogram, is a
small part of a main program. Generally,
---------------------- a major problem is subdivided into
functionally different modules and
----------------------
for each module a separate program
---------------------- is written. Each program or module is
called subprogram or subroutine and
---------------------- each subroutine symbol is functionally
independent. The subroutine symbol is
----------------------
used to represent these modules. The
---------------------- symbol is rectangle in shape with double
lines on left and right side. The symbol
---------------------- is filled with the name of the subroutine
and the logic for this subroutine is drawn
----------------------
as a separate flowchart diagram.
---------------------- 4. The parallelogram shaped symbol
is used to represent the input/output
---------------------- operations such as read and write.
---------------------- 5.
This represents the direct data.
----------------------
----------------------
----------------------
----------------------
Algorithms 25
Notes
----------------------
----------------------
----------------------
----------------------
----------------------
Fig. 2.5: Flowchart Representation of Algorithm Constructs
----------------------
Let us understand some examples of flowchart.
----------------------
Example 13: A flowchart to perform addition of three numbers.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Example 14: A flowchart to read two sides of rectangle from user and
----------------------
calculate area of rectangle.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
---------------------- Example 15: A flowchart to read two numbers from user and find maximum
of them.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Flowchart can be used for designing the basic concept of the program
in pictorial form but cannot be used for programming purposes. Some of the ----------------------
limitations of the flowchart are given below:
----------------------
• Complex: The major disadvantage in using flowcharts is that when
a program is very large, the flowcharts may continue for many pages, ----------------------
making them hard to follow. Flowcharts tend to get large very quickly and
it is difficult to follow the represented process. It is also very laborious ----------------------
to draw a flowchart for a large program. You can very well imagine the ----------------------
nightmare when a flowchart is to be developed for a program consisting
of thousands of statements. ----------------------
• Costly: Drawing flowcharts are viable only if the problem-solving logic ----------------------
is straightforward and not very lengthy. However, if flowcharts are to
be drawn for a huge application, the time and cost factor of program ----------------------
development may get out of proportion, making it a costly affair.
----------------------
• Difficult to modify: Due to its symbolic nature, any changes or
modification to a flowchart usually requires redrawing the entire logic, ----------------------
and redrawing a complex flowchart is not a simple task. It is not easy
----------------------
to draw thousands of flow lines and symbols along with proper spacing,
especially for a large complex program. ----------------------
• No update: Usually programs are updated regularly. However, the
----------------------
corresponding update of flowcharts may not take place, especially in the
case of large programs. As a result, the logic used in the flowchart may ----------------------
not match with the actual program’s logic. This inconsistency in flowchart
update defeats the main purpose of the flowcharts, that is, to give the ----------------------
users the basic idea about the program’s logic.
----------------------
2.6 CONCEPT OF MODULARITY AND SUB-ALGORITHMS ----------------------
Algorithms 27
Notes has to be designed along with how sub-algorithms should be integrated with
overall algorithm. For example, if we want to find the median value of finite
---------------------- number of integers, we have to include sorting of numbers as a sub-algorithm.
There can be several sorting algorithms. Any of the sub-algorithms of sorting
---------------------- has to be integrated with the main algorithm for finding mean value of n integers.
---------------------- This concept of sub-algorithms is implemented by modular programming
approach. Modular programming is a technique of software design, in which
----------------------
the functionality of a program is divided into smaller and interchangeable
---------------------- modules. This approach of modular programming is also called “top-down”
approach or “step-wise refinement” approach. The software modularity also
---------------------- indicates the number of application modules capable of solving a particular
business problem. These modules are divided based on functionality.
----------------------
---------------------- The modern languages such as C++, VC++, VB, Java, .NET, Python &
JavaScript are based on the concept of OOPS. (Object Oriented Programming
---------------------- Systems).
Class
----------------------
No access X private : (data) ----------------------
----------------------
public : (functions)
access allowed
----------------------
----------------------
----------------------
Fig 2.5: Class layour
Encapsulation: ----------------------
Algorithms 29
Notes In java program, data fields and methods are the two main elements. The
encapsulation enables user to hide, inside the object, both the data fields and the
---------------------- methods that act on that data. Thus the user can control access to the data. In
object-oriented programming, an object’s data is always private to the object.
---------------------- Other parts of a program should never have direct access to that data. Thus
---------------------- encapsulation is nothing but data-hiding.
We can always hide data inside functions, just by making that data local to
----------------------
the function. If the data is to be made available to other functions, make the
---------------------- data global to the program, which gives any function access to it. This concept
is available in conventional structured programming and will not serve the
---------------------- purpose of data hiding. The other way is to make our data global to the functions
that need it but still prevent other functions from gaining access. This role is
----------------------
performed by Encapsulation. In an object, the encapsulated data members are
---------------------- global to the object’s methods, yet they are local to the object. However they
are not global variables.
----------------------
One of the characteristics of object-oriented programming that is often touted
---------------------- in discussions of the subject is encapsulation. The term carries the connotation
of an object being enclosed in some sort of container - and that is exactly what
---------------------- it means. Encapsulation is the combining of data and the code that manipulates
that data into a single component - that is, an object. Encapsulation also refers
----------------------
to the control of access to the details of an object’s implementation. Object
---------------------- access is limited to a well-defined, controlled interface. This allows objects to
be self-contained and protects them from accidental misuse, both of which are
---------------------- important to reliable software design.
---------------------- The advantages of encapsulation are:
---------------------- 1) Data hiding: The object has a public interface. That is, the other objects
can communicate with it. However, object can maintain private data and
---------------------- methods that can be changed at any time without affecting the other objects
that depend on it. For example, principle of working and construction of
---------------------- bike is not required to be understood for using the bike.
---------------------- 2) Modularity: The Java language is a modular language. The source code
for an object can be written and maintained independently of the source
---------------------- code for other objects. We can easily pass the objects within a program.
---------------------- For example, we can give our bicycle to others and it will still work.
Inheritance:
----------------------
Inheritance enables you to create a class that is similar to a previously
---------------------- defined class, but one that still has some of its own properties. Suppose that
you have a class for a regular 2 wheeler bike. Let us suppose that we have to
----------------------
create a bike that has an additional high-speed gear. In conventional structured
---------------------- programming, we are required to modify the program extensively. This might
introduce bugs into the program.
----------------------
In order to avoid these problems, we can create a new class by inheritance.
---------------------- This new class inherits all the data and methods from the base class of bike. The
Polymorphism: ----------------------
Polymorphism is the ability to assume different forms. In programming, ----------------------
it is treated as the ability of objects to have many methods of the same name,
but with different forms. ----------------------
By using polymorphism, we can create new objects that perform the same ----------------------
functions as the base object but which perform one or more of these functions in
a different way. For example, consider area object that finds area of circle. By ----------------------
using polymorphism, you can create area object that computes area of rectangle.
----------------------
We can do this by creating a new method that calculates area of rectangle. Both
the old circle-area and the new rectangle-area methods have the same name say, ----------------------
method area.
----------------------
An example of Encapsulation, Inheritance, and Polymorphism is given below:
We have seen above that the bike is as an object which possesses various ----------------------
attributes such as direction, position and speed. The object bike has various ----------------------
means such as handle, kick and brakes. These means act on the attributes. In
order to construct a class for a bike object, the attributes (direction, position and ----------------------
speed) are considered as the class’s data fields and the means (handle, kick and
brakes) represent methods. ----------------------
The first step in creating an object is to define its class. ----------------------
class bike ----------------------
{
----------------------
data position;
----------------------
data direction;
data speed; ----------------------
Algorithms 31
Notes The above example shows how a class is created. It also shows how
encapsulation works. In the above example, bike is base class. It has three data
---------------------- fields viz. direction, position and speed. These three data fields can be operated
by the three methods Handle (), Kick (), and Brake (). The Handle () method is
---------------------- used to change direction of bike. Similarly the method Kick () is sued to start
---------------------- the bike and the method Brake () stops the bike. Thus position, direction and
speed can be controlled by these three methods. The data fields and methods
---------------------- are encapsulated inside the class. These data fields are private to the class.
Therefore, these data fields cannot be directly accessed from outside of the
---------------------- class. Only the three methods of class can access the data fields.
---------------------- Now, let us create a new bike that has a special gear. To do this, we can
use OOP inheritance to derive a new class from the bike base class.
----------------------
Class newbike inherits from bike
----------------------
{
---------------------- method newstyle();
---------------------- }
---------------------- The class newbike implicitly inherits all the data fields and methods from
the base class of bike. This performs a method called newstyle (). In addition, it
---------------------- also has the direction, position, and speed data fields and three methods Handle
(), Kick (), and Brake ().This is an example of inheritance.
----------------------
Now let us suppose that we want a new kind of bike that has all the
---------------------- characteristics of a newbike, except that its additional gear is twice as fast as the
gear of newbike.
----------------------
class Fastbike inherits from newbike
----------------------
{
---------------------- method newstyle();
---------------------- }
---------------------- The class Fastbike looks exactly like the original class newbike. However,
rather than just inheriting the newstyle() method, it defines its own version. This
---------------------- new version makes the bike move twice as fast as the newstyle () method of
class newbike.
----------------------
In this way, the Fastbike class implements the same functionality as the
---------------------- newbike () class, but it implements that functionality a little differently. Because
the Fastbike class inherits from newbike, which itself inherits from bike, a
----------------------
Fastbike also inherits all the data fields and methods of the bike class. We can
---------------------- control how inheritance using the public, protected, and private keywords.
For example, book is the object that provides access to information (data).
----------------------
The functions open, close, read etc., are associated with the term book.
---------------------- The process of creation of objects is provided by constructor. Using
---------------------- Objects, the program can be simplified. Moreover, the software developed can
be reused by us.
32 Algorithms and Programming Concepts
Messages: Notes
In a pure object-oriented programming model, such as that used by
----------------------
Smalltalk, objects interact by sending messages to each other. When an object
receives a message, the object invokes a method to process the message. The ----------------------
method may change the state of the object, return information contained in the
object, or cause objects to be created or deleted. ----------------------
The object model used by Java is consistent with the concept of message ----------------------
passing, but does not emphasize it. In the Java model, objects interact by
invoking each other’s methods. Methods provide access to the information ----------------------
contained in an object. The type of access varies depending on the method.
----------------------
Software objects interact and communicate with each other by sending
messages to each other. When object A wants object B to perform one of B’s ----------------------
methods, object A sends a message to object B.
----------------------
The message comprises of the following three components:
----------------------
1) The object to whom the message is addressed.
2) The name of the method to perform. ----------------------
----------------------
Fill in the blanks.
----------------------
1. Flowcharts are also called ________.
2. When the size and complexity of problem increases we need to ----------------------
divide the problem into smaller problems/tasks which is known as ----------------------
_________.
3. Approach of modular programming is also called as approach ----------------------
________or _____ approach. ----------------------
4. In case of modular programming the modules are divided based on
______________. ----------------------
----------------------
Algorithms 33
Notes
Activity 3
----------------------
---------------------- Draw flowcharts for all the algorithms written in Activity 1 and Activity 2.
----------------------
---------------------- Summary
---------------------- • The algorithm is the procedure of steps to take and get the result. It refers
to the logic of a program. It is a step-by-step description of how to arrive
----------------------
at a solution to a given problem.
---------------------- • Algorithm is defined as a sequence of instructions which when executed
in the specified sequence gives the desired results.
----------------------
• Finiteness, definiteness, input, output are important features of an
---------------------- algorithm.
• Algorithms help for better problem solving, improves efficiency, provides
----------------------
clarity and reusability.
---------------------- • Sequence, decision and repetition are the three constructs for developing
an algorithm.
----------------------
• Three main tools are used to represent an algorithm. They are flowchart,
---------------------- pseudocode and the actual code.
---------------------- • The pictorial representations of an algorithm are called flowcharts.
---------------------- • When the size and complexity of problem increases we need to divide the
problem into smaller problems/tasks which is known as sub-algorithms.
----------------------
• The concept of sub-algorithms is implemented by modular programming
---------------------- approach.
----------------------
Keywords
----------------------
• Algorithm: Step-by-step procedure for calculations.
---------------------- • Comparison and logical operators: Used with decision-making
---------------------- statements.
• Flowchart: Graphical representation of logic.
----------------------
• Modularity: Process of breaking down complex program into several
---------------------- modules.
----------------------
----------------------
----------------------
----------------------
2. Algorithm must get terminated or stopped after performing finite number ----------------------
of steps and each step must be executed finite number of times. This
----------------------
feature of an algorithm is termed as finiteness.
Match the following. ----------------------
i. – b. ----------------------
ii. – d. ----------------------
iii. – a.
----------------------
iv. – c.
----------------------
Check your Progress 2
Fill in the blanks. ----------------------
1. In sequence construct the set of instructions are written sequentially. ----------------------
2. In case of selection constructs, often it is required to perform comparison ----------------------
operation between different choices.
State True or False. ----------------------
1. True ----------------------
2. True ----------------------
----------------------
Algorithms 35
Notes Check your Progress 3
Fill in the blanks.
----------------------
1. Flowcharts are also called process flow charts.
----------------------
2. When the size and complexity of problem increases we need to divide the
---------------------- problem into smaller problems/tasks which are known as sub-algorithms.
----------------------
Suggested Reading
----------------------
1. Awad, Elias M. Systems Analysis and Design. Illinois: Richard D. Irwin.
---------------------- 2. Goel, Anita. Computer Fundamentals. New Delhi: Pearson Education.
---------------------- 3. Huang, Chung-Yang (Ric), Chao-Yue Lai and Kwang-Ting (Tim) Cheng.
“Fundamentals of algorithms”. Electronic Design Automation. Morgan
---------------------- Kaufmann Publishers.
---------------------- 4. ITL Education Solutions Limited. Introduction to Information Technology.
New Delhi: Pearson Education India.
----------------------
5. Sinha, Pradeep and Priti Sinha. Computer Fundamentals. New Delhi:
---------------------- BPB Publications.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
3
Structure:
3.1 Introduction
3.2 Desirable Properties of an Efficient Algorithm
3.3 Computational Complexity of Algorithms
3.4 Asymptotic Notations
3.5 Different Analysis of Algorithms
3.6 Example Analysis
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
---------------------- After going through this unit, you will be able to:
----------------------
----------------------
Check your Progress 1
----------------------
Multiple Choice Single Response. ----------------------
1. The time taken by an algorithm depends upon: ----------------------
i. Architecture of a machine
----------------------
ii. Size of the input
----------------------
iii. None
iv. Both ----------------------
State True or False. ----------------------
1. For judging the efficiency of an algorithm, the number of comparisons ----------------------
is of more importance at times.
2. The efficiency of an algorithm does not depend upon the storage ----------------------
medium of the input instance. ----------------------
3. The efficiency of an algorithm differs with different input instances.
----------------------
----------------------
Activity 1
----------------------
Assume an input instance of ten integers and compare the Bubble Sort
----------------------
and Selection Sort algorithms based on the number of comparisons involved
and the number of swappings required to sort the integers in ascending order. ----------------------
----------------------
3.2 DESIRABLE PROPERTIES OF AN EFFICIENT ----------------------
ALGORITHM
----------------------
Different people can write an algorithm in different ways. There can be
----------------------
different algorithms for the same purpose or objective. Most often, an algorithm
that gives a correct output is considered or selected. The efficiency of the ----------------------
algorithm or the availability of a better algorithm is not taken into consideration.
These factors are only considered in the industry, when the efficiency of the ----------------------
algorithm poses serious performance issues in terms of the time taken and the
----------------------
storage occupied.
For a similar problem, a solution can be written in many ways and it ----------------------
is necessary to identify the correct solution based on certain factors that can ----------------------
make a serious impact on the performance. Along with that, there should be
---------------------- c) Definiteness – Every algorithm has steps. These steps need to be well
defined and logical.
---------------------- d) Accuracy or Correctness - Ideally an algorithm should perform the task
---------------------- that it is designed to perform, for all permutations and combinations of
input. This behavior is consistent for permutations and combinations.
---------------------- e) Finiteness - An algorithm should produce an output after performing a
---------------------- finite number of computational steps.
f) Effectiveness - Every step of the algorithm must be performed precisely,
----------------------
in finite time.
---------------------- g) Generality -- An algorithm written for a specific algorithm should be
applicable to all algorithms of the same general form, with only slight
----------------------
modifications permitted.
---------------------- An algorithm is written in a language independent way. So to analyse the
---------------------- efficiency of the algorithm, we need ways or techniques to do it in a language
independent way. Also identification of the efficiency of an algorithm is done
---------------------- on the basis of the amount of resources required by an algorithm.
----------------------
3.3 COMPUTATIONAL COMPLEXITY OF ALGORITHMS
----------------------
To increase the efficiency of the algorithms so they can perform with
maximum optimisation, it is essential to calculate the complexity of the ----------------------
algorithms. Even if calculating it exactly may be impossible, approximate
calculation is necessary. Complexity can be evaluated using a few factors. They ----------------------
are:
----------------------
a) Efforts in terms of Efforts E(n) : It focuses on the number of operations
required to be executed to generate a specific required output. ----------------------
c) Time T(n):It measures the time required for complete execution of the ----------------------
algorithm.
----------------------
---------------------- (1) In the preceding algorithm, we note that there are n-1 comparisons within
the loop.
---------------------- (2) In a randomly ordered sequence, half the values will be less than the mean
---------------------- and a1 would be assumed to have the mean value for purposes of analysis.
Hence, there will be an average of n/2 I/O operations to replace the value
---------------------- max with ai. Thus, there are n/2 + 1 I/O operations.
---------------------- (3) This means that the preceding algorithm is O(n) in comparisons and I/O
operations. More precisely, we assert that, in the average case:
----------------------
W(n) = n-1 comparisons + (n/2 + 1) I/O operations.
---------------------- Let us now understand the concepts and theory in computational
complexity of algorithms. There are different techniques for calculating the
----------------------
same.
42 Algorithms and Programming Concepts
1. RAM Model of Computation Notes
2. Asymptotic analysis of worst case complexity
----------------------
We need ways to identify a correct algorithm from an incorrect one, which
is done with verification. This mathematical verification consists of many parts. ----------------------
Some of them are:
----------------------
1) There should be a clear precise statement of what a programmer is trying
to prove. ----------------------
2) There should be a set of assumptions of things that should be considered ----------------------
to be taken to be true and it should be used as a part of the proof.
----------------------
3) There should be a chain of reasoning that takes from these assumptions to
the statement you are trying to prove. ----------------------
The best case, the worst case and the average case is calculated. ----------------------
Performance evaluation is divided into two major phases:
----------------------
1. a priori estimates
----------------------
2. a posteriori testing
A priori estimates are also called as performance analysis as it is done ----------------------
before implementing an algorithm. While a posteriori testing is also called as ----------------------
performance measurement as it happens after implementing an algorithm.
The amount of memory needed by an algorithm for completion is known ----------------------
as Space Complexity. The space needed by an algorithm has two major parts: ----------------------
1. Fixed part: The fixed part of the algorithm is independent of the number
----------------------
and size of the input and output. This is the space occupied by an algorithm
because of its instructions (i.e. the space of the code), space occupied ----------------------
because of simple variables, constants, derived variables etc.
----------------------
2. Variable Part: The variable part of the algorithm is occupied by the
component variables. The size of the variable part depends upon problem ----------------------
instance, reference variables and the recursion stack space.
----------------------
The amount of computer time needed for completion of an algorithm is
termed as “Time Complexity”. ----------------------
----------------------
Asymptotic is a method to describe a function or behavior in terms of its
limits or without bounds. In graphical format we can say that asymptotic is a ----------------------
straight line which continuously approaches the curve but it meets the curve at
any finite distance. ----------------------
For example, following figure shows that the function x is asymptotic to ----------------------
x+1.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Asymptotic complexity is a method of expressing the main component of
---------------------- the cost of an algorithm in terms of some idealised units of some computational
work.
----------------------
Assume that f1(x) and g1(x) are functions of set of real numbers to the set
---------------------- of real numbers.
We say that f1 and g1 are asymptotic and write
----------------------
f1 (x) ≈ g1(x)
----------------------
if f1(x) / g1(x) = c (constant)
---------------------- There are mainly three asymptotic notations:
---------------------- 1) Big Oh Notation
---------------------- The “O” which is called as Big-Oh is a system of expressing the upper
bound of an algorithm at run time. It denotes the largest time an algorithm
---------------------- might take to execute.
---------------------- If there exists an integer and a constant c1>0 for all the integers for all
non-negative function f1(n) and g1(n) and if f1(n)<=c1g1(n) the function f1(n)
---------------------- is a Big O of g1(n). This is also denoted as “f1 (n)=O(g1(n))”.Thus g1(n) serves
as a upper bound to the curve of the function f1(n)
----------------------
Best Case Big Oh notation: This illustrates or shows an upper bound for
---------------------- best case input.
---------------------- Worst Case big Oh notation: describes an upper bound for all input
---------------------- Average Case: is similar to worst case.
2) Small Oh(Theta) Notation
----------------------
Best Case Theta notation: not used
----------------------
Worst Case: describes asymptotic bounds for worst case input
---------------------- Average Case: is similar to worst case.
---------------------- 3) Omega Notation
---------------------- The Omega notation is the asymptotically tight lower bound for a given
curve or function.
----------------------
----------------------
3.5 DIFFERENT ANALYSIS OF ALGORITHMS
----------------------
The “running time” of the algorithm is represented as a function of the
input size n, f1(n). For comparison of two algorithms with running time f1(n) ----------------------
and g1(n), a rough estimate can be made that is independent of the machine
----------------------
time, programming style etc.
Let us take an example for computing the running time of an algorithm. ----------------------
The goal or the objective is to search a list of elements. Given: a list of n elements
----------------------
which may be either ordered or unordered; the ordering may be numerical or
alphabetical; and an element x that needs to be searched in the list. The goal is ----------------------
to determine whether x appears in the list and if it does, then what is the index
position of the element x. ----------------------
The algorithm is as given below: ----------------------
procedure linear search1 (x1 : integer, a1 , a2 , …, an: distinct integers) ----------------------
i := 1
----------------------
while (i <= n )
i := i + 1 ----------------------
if x1 = ai then ----------------------
location1 := i
return location1 ----------------------
end if ----------------------
end while
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
3.6 EXAMPLE ANALYSIS
----------------------
When algorithms are considered or reflected the following terms are used
very often: ----------------------
Tractable - An algorithm belongs to a class P, such that the algorithm is ----------------------
solvable in polynomial time. Hence this refers the use of P for polynomial. This
means that complexity of the algorithm is O(nd), where d may be large (which ----------------------
---------------------- d. The amortised runtime complexity of the algorithm is the function defined
by a sequence of operations applied to the input of size a and averaged
---------------------- over time.
---------------------- Example
Let us consider an algorithm of sequential searching in an array of size n.
----------------------
Its worst-case runtime complexity is O(n)
----------------------
Its best-case runtime complexity is O(1)
---------------------- Its average case runtime complexity is O(n/2)=O(n)
---------------------- Example: Linear Search
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Figure 3.1: Schematic Diagram of Bubble Sort
----------------------
The above is the schematic diagram of bubble sort applied to input vector
---------------------- (2,1,4,2,3) to yield sorted vector (1,2,2,3,4).
---------------------- Objective: Consider an algorithm for sorting elements in an unordered
group of elements using bubble sort.
----------------------
Hypothesis: consider a set {a(n)}.of all un-sorted integer elements
----------------------
Execution Steps: Consider a set {a(n)}.of all integer elements. Local
---------------------- variable min, pos, temp
Step 1: Read the Input a[1] to a[n] //iterate the loop from a(i) to a(n).
----------------------
Step 2: Execute Swap(a[i],a[pos])
---------------------- Swap: from a[1] to a[n]
---------------------- When a[1] ; Set min = Set a[1]; Set pos=a[1]; Set temp[1]=min;
Step 3: Iterate from i=1 to i=n;
----------------------
Step 4: when a[i]=n, temp would be sorted.
---------------------- End;
---------------------- Analysis: The above algorithm consists of one loop, which has n iterations
and takes the efforts of (n-i+1) comparisons per iteration. Hence the complexity
50 Algorithms and Programming Concepts
of the algorithm is calculated to be is O(n<sup2< sup=””>) comparisons. Notes
In the best case scenario, the input is pre-sorted and bubble-sort requires
----------------------
a minimum number of I/O operations.
In the worst case scenario, the input is sorted opposite to the desired order ----------------------
of the sorted output and a maximum number of I/O operations are required.
----------------------
----------------------
State True or False.
1. To increase the efficiency of the algorithms so that they can perform ----------------------
with maximum optimisation, it is essential to calculate the complexity ----------------------
of the algorithms.
----------------------
2. Oh notation is an Asymptomatic Notation.
3. Any algorithm can have two cases of complexity. ----------------------
Fill in the blanks. ----------------------
1. Complexity can be evaluated using following factors: (a) ___________, ----------------------
(b) ____________, (c) ______________ and (d) __________.
2. The Space needed by an algorithm has two major parts: _________ ----------------------
and _____________. ----------------------
3. The amount of computer time needed for completion of an algorithm
----------------------
is termed as _____________.
----------------------
Summary ----------------------
• Algorithm is a set of procedures that takes some inputs, does some ----------------------
computations and produces an output.
----------------------
• The accepted values by the algorithm are termed ‘input’ or ‘arguments’ or
‘parameters’. ----------------------
• Every algorithm has steps. These steps need to be well defined and logical. ----------------------
• Algorithm is written in a language independent way.
----------------------
• Complexity of algorithms is in general represented using Work, Space,
Time and Cost. ----------------------
----------------------
----------------------
---------------------- 4. Analyse algorithms for selection of integer elements both linear and
binary.
----------------------
Answers to Check your Progress
----------------------
Check your Progress 1
----------------------
Multiple Choice Single Response.
----------------------
1. The time taken by an algorithm depends upon:
---------------------- iv. Both
---------------------- State True or False.
---------------------- 1. True
2. True
----------------------
3. False
----------------------
Check your Progress 2
----------------------
State True or False.
---------------------- 1. True
---------------------- Multiple Choice Single Response.
---------------------- 1. Major factors that govern the choice of an algorithm over another is the
iii. Both
----------------------
----------------------
----------------------
----------------------
2. False ----------------------
3. False ----------------------
Fill in the blanks.
----------------------
1. Complexity can be evaluated using the following factors: (a) Efforts,
----------------------
(b) Memory, (c) Time and (d) Cost.
2. The Space needed by an algorithm has two major parts: Fixed and ----------------------
Variable. ----------------------
3. The amount of computer time needed for completion of an algorithm is
----------------------
termed as Time Complexity.
----------------------
Suggested Reading ----------------------
1. Horowitz, Ellis, Sartaj Sahni, Sanguthevar Rajasekaran. Fundamentals of ----------------------
Computer Algorithms. Galgotia Publications.
2. Huang, Chung-Yang (Ric), Chao-Yue Lai. Fundamentals of Algorithms. ----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
4
Structure:
4.1 Introduction
4.2 Need for Language-Neutral Algorithms
4.3 Components of an Algorithm
4.4 Standard Format for writing an Algorithm
4.4.1 Predefined Keywords for an Algorithm
4.5 Organisation of an Algorithm
4.6 Verifying if Algorithm is Language-Neutral
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
----------------------
4.1 INTRODUCTION
----------------------
In the previous unit, we studied about algorithm and the basic design
----------------------
structure of an algorithm. It is important to be able to identify the activities
---------------------- needed to be performed by a program precisely and craft them into an algorithm.
After studying the design and complexity of an algorithm let us now
----------------------
proceed to writing algorithm which would enlist the desired set of activities to
---------------------- be performed by the program that needs to be designed based on it.
---------------------- Some of the questions we might ask while writing an algorithm are:
• What language must be used for writing an algorithm?
----------------------
• What is the structure of an algorithm?
----------------------
• What kind of terms should be used in an algorithm?
---------------------- • What is the organisation of an algorithm?
---------------------- • What checks are needed at the end of the algorithm?
---------------------- In this unit, we will answer these questions and learn the procedure of
writing a language-neutral algorithm. We will learn about the various ways we
---------------------- can add conditions or change the flow of an algorithm.
----------------------
4.2 NEED FOR LANGUAGE-NEUTRAL ALGORITHMS
----------------------
When we decide to write an algorithm, the primary question that arises
---------------------- is to which language to use to write the algorithm. The answer is ENGLISH!
----------------------
State True or False.
----------------------
1. Algorithms must be dependent on programming language.
----------------------
2. Algorithms are steps to solving a program logically.
----------------------
----------------------
4.3 COMPONENTS OF AN ALGORITHM
----------------------
Before we start writing an algorithm we must know the problem to be
solved. ----------------------
Algorithm to solve a problem is an efficient mechanism of arriving at the ----------------------
solution. So to solve a problem we need to design an algorithm for the solution.
Understanding the algorithm used to solve the problem helps us to predict ----------------------
the normal flow, special cases if any, cases in which software won’t work ----------------------
quickly, cases where the results would be undefined or unacceptable.
----------------------
Algorithms can be written in many ways and forms like charts, diagrams,
imperative programs, etc. For software algorithms we prefer to write in program- ----------------------
like structure in plain English.
----------------------
Algorithm has the following components:
• Input ----------------------
• Sequence of steps ----------------------
• Output ----------------------
----------------------
---------------------- Algorithm
----------------------
----------------------
----------------------
----------------------
---------------------- For example, if we need to find the average score of children in a given
age group, then we can find average score for each standard in the age group
---------------------- and find the average of these numbers to get the desired result.
---------------------- Input data needs to undergo all the required changes and operations to
form the desired output. This demands the need to store and manage data values
---------------------- – initial, intermittent, final.
----------------------
Activity 1
----------------------
Write the steps required to arrange five numbers in increasing order. ----------------------
----------------------
4.4 STANDARD FORMAT FOR WRITING AN ALGORITHM ----------------------
Now let us start learning how to write algorithms. ----------------------
Example 1: Write an algorithm to find largest of three numbers.
----------------------
Solution:
----------------------
Let us see the input that is given to us. Here we have to find largest of
three numbers. So the input would be three numbers. Since we do not know the ----------------------
values of the numbers, let us say the numbers are A, B, C.
----------------------
Input is: Numbers A, B, C
----------------------
Now let us think of the procedure to find the largest of these three numbers.
We know we can find largest of two numbers by comparing them. So for largest ----------------------
of three numbers we can start with comparing two numbers at a time. (We broke
down complex unknown problem into simple known problem here). ----------------------
Step 1: Compare A & B. ----------------------
What if A is greater than B, is that the largest number in the set? No. We ----------------------
need to compare it with C.
Step 2: If A > B then Compare A & C ----------------------
---------------------- Keyword is a commonly known word, which has some predefined meaning
associated with it because of which it cannot be used for naming variables or
---------------------- data structures and must be used in context of the original meaning.
---------------------- Here we are using italics to indicate a keyword. ‘…’ indicates there are
other steps which will be performed here depending on the logic. Let us see an
---------------------- example of a keyword.
---------------------- if.. then ..else..
For example ‘if’ indicates there is a condition, so it is a keyword. Similarly
----------------------
‘then’ and ‘else’ are also keywords used with ‘if’
---------------------- If a>b then …else …
---------------------- Let us check other keywords.
---------------------- There is another scenario when we need to perform certain activity and
then check if we must stop. For example, reducing the number until number is
---------------------- positive, etc.
case ----------------------
There are other keywords which are not depend on condition but consider ----------------------
set of cases.
----------------------
When we have specific scenarios in which we want to perform certain
activity, we can specify it as case. ----------------------
case a is 1: a is neither prime nor co prime…
----------------------
case a = 1, 2, 3: ….
----------------------
Some more keywords are return, break, and continue. These are used
to navigate from one step to another in an algorithm, not necessarily based on ----------------------
some condition.
----------------------
We shall see the uses of these keywords in the next unit. For now let us
quickly list all the keywords. ----------------------
If, then, else, for, do, while, repeat, until, go to, case, return, break, ----------------------
continue.
----------------------
Check your Progress 3 ----------------------
----------------------
Activity 2
----------------------
Identify keywords used in writing algorithms from the following set of ----------------------
words:
----------------------
how, if, where, then, case, pull, terminate, add, for, follow, do, jump, while.
----------------------
----------------------
4.6 VERIFYING IF ALGORITHM IS LANGUAGE- ----------------------
NEUTRAL
----------------------
It is very important to write language-neutral algorithms. Otherwise the
algorithm may be programmable in a specific language but not in any other ----------------------
programming language which is best suited for it.
----------------------
To verify if algorithm is language-neutral:
----------------------
1. List all the words used in each step apart from input data, variables and
output statement. ----------------------
2. Remove the words which indicate mathematical or logical computation ----------------------
like increment, compare, etc.
----------------------
3. Does the list consist of standard keywords? If yes, then algorithm is
language-neutral. ----------------------
4. If not replace them with suitable keywords.
----------------------
Let us check if our algorithm is language-neutral.
----------------------
Step 1: Compare A & B.
Step 2: If A > B then Compare A & C ----------------------
---------------------- Activity 3
----------------------
List the words which indicate mathematical or logical computation.
----------------------
----------------------
----------------------
Summary
----------------------
Self-Assessment Questions
----------------------
1. Write a short note on components of an algorithm.
2. Why is it important to write language-neutral algorithms? ----------------------
----------------------
Answers to Check your Progress
----------------------
Check your Progress 1
State True or False. ----------------------
1. False ----------------------
2. True ----------------------
Check your Progress 2
----------------------
Fill in the blanks.
----------------------
1. Algorithm involves input, steps and output.
2. Complex algorithms can be broken down into simple ones. ----------------------
2. True ----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
5
Structure:
5.1 Introduction
5.2 Sequential Flow
5.3 Random Jump in the Flow
5.4 Conditional Flow
5.5 Repetitive Flow
5.6 Iterative Flow
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
---------------------- 1. Start block ..End block: Statement like Start Block can be used to mark
the beginning of the block and statement End Block can be used to mark
---------------------- the end of the block. All statements within Start Block and End Block can
form the actual steps to be executed.
----------------------
For example:
----------------------
Start Block
---------------------- Statement 1
---------------------- Statement 2
---------------------- Statement 3
End Block
----------------------
Statement Start Block and End Block do not perform any calculation or
---------------------- activity. All the steps are encapsulated within the Start and End.
---------------------- Similarly, other words can be used like Start-End, Begin-End, etc.
2. Indentation: Indentation or moving the beginning of the steps to right
----------------------
to form next indent alignment, can be used to indicate the steps included
---------------------- inside a block.
----------------------
Fill in the blanks.
1. Normally the steps in an algorithm are executed in _____________ ----------------------
order.
----------------------
2. Order of execution of steps in sequential flow is in _____order of step
number. ----------------------
3. A set of steps executed in a sequence is called a _______. ----------------------
----------------------
5.3 RANDOM JUMP IN THE FLOW ----------------------
We have learnt that the default order of execution of steps in an algorithm ----------------------
is sequential. However, we may not always want to execute all the steps in a
sequence and may want to jump to some other point in the algorithm. ----------------------
We can use ‘go to’ keyword to jump to a specific step in an algorithm. ----------------------
Go to
----------------------
Whenever we do not want to execute the next sequential step we can use
‘go to’ keyword to decide the next step to be executed. ----------------------
For example ‘go to Step 3’ indicates that the execution should resume ----------------------
from Step 3. That means the next step to be executed would be Step 3. All the
steps in between current step and ‘go to’ step (Step 3 in this case) would be ----------------------
skipped. ----------------------
Let’s consider following case
----------------------
Step 1
----------------------
Step 2
Step 3 …go to Step 6 ----------------------
Step 4 ----------------------
Step 5 ----------------------
----------------------
Check your Progress 2
----------------------
State True or False.
----------------------
1. Steps in an algorithm can always be executed sequentially.
----------------------
2. ‘go to’ keyword can be used to jump to a specific step in an algorithm.
----------------------
----------------------
Activity 1
----------------------
Write down the order of execution of steps in the following algorithm: ----------------------
Step 1:
----------------------
Step 2: Go to Step 6
----------------------
Step 3:
Step 4: ----------------------
----------------------
5.4 CONDITIONAL FLOW
----------------------
We have learnt that the default order of execution of steps in an algorithm
is sequential and we can change this order by adding random jumps. There ----------------------
may be logical conditions when the normal flow should be changed like before
----------------------
executing certain steps we may want to check few conditions. In this section,
we will learn about such cases. ----------------------
When certain set of steps, i.e., blocks are executed based on certain
----------------------
conditions, the algorithm is said to have conditional flows.
----------------------
---------------------- Block 2
In a conditional flow, the condition is evaluated and based on the result of
---------------------- the condition, the corresponding block is executed.
---------------------- In the above example:
---------------------- • If the condition is true, then Block 1 will be executed.
----------------------
----------------------
Condition
----------------------
----------------------
Start ----------------------
Step 1: Get the 4 digit year number ----------------------
Step 2: Divide the year number by 4, store the remainder in X
----------------------
Step 3: If X is 0 then execute Step 4, else go to Step 5
----------------------
Step 4: The year is leap year. Go to End.
Step 5: The year is not leap year. ----------------------
End ----------------------
In this algorithm we can see that depending on the result of the condition ----------------------
certain steps may be executed or not.
----------------------
Let us check the execution of leap year algorithm for various scenarios:
Scenario 1: Year = 1980 ----------------------
Step 1: Year = 1980 ----------------------
Step 2: divide 1980 by 4; remainder =0, divisor= 495; X=0 ----------------------
Step 3: X=0
----------------------
(Condition is true, therefore we will execute step 4)
Step 4: 1980 is leap year ----------------------
(The execution with stop, Step 4 has Go to End) ----------------------
Scenario 2: Year = 1991 ----------------------
Step 1: Year = 1991
----------------------
Step 2: divide 1991 by 4; remainder =3, divisor= 497; X=3
Step 3: X=3, hence X is not equal to 0 ----------------------
(Condition is false, therefore we will go to step 5) ----------------------
Step 5: 1991 is not a leap year
----------------------
---------------------- Step 5: If loan amount between 10 lakh and 20 lakh then go to Step 6 else
go to Step 8
---------------------- Step 6: Rate of interest is 10% per annum.
---------------------- Step 7: Go to Step 10
---------------------- Step 8: If loan amount is more than 20 lakh then go to Step 9 else go to
Step 10
----------------------
Step 9: Rate of interest is 14% per annum.
---------------------- Step 10: Amount of Interest = (loan amount * rate of interest)/100
---------------------- End
---------------------- Note the indentation used to indicate the block of steps to be executed
after if condition. Also, Step 9 need not be followed by ‘Go to Step 10’ because
---------------------- that is the next step in the sequence.
---------------------- Let us check the execution of this algorithm for various scenarios.
Scenario 1: Loan Amount is 7 lakh
----------------------
Step 1: Loan Amount = 7 lakh
----------------------
Step 2: Loan Amount is less than 10 lakh;
---------------------- (Condition is true, so go to Step 3)
---------------------- Step 3: Rate of interest = 7%
---------------------- Step 4: Go to Step 10
Step 10: Amount of Interest = (7 lakh * 7)/100 = 49000
----------------------
----------------------
Multiple Choice Single Response.
1. Block following a condition is executed: ----------------------
i. If the condition is true ----------------------
ii. If the condition is false ----------------------
iii. If the condition has no result
----------------------
Multiple Choice Multiple Response.
----------------------
1. A condition must return result of following types:
i. True ----------------------
ii. False ----------------------
iii. No result ----------------------
----------------------
Activity 2
----------------------
Write an algorithm to check if the person is eligible to vote. ----------------------
---------------------- Step 6
In this case after Step 5, again Step 2 would be executed, then Step 3,
---------------------- Step 4, Step 5, again Step 2, and so on. However, to ensure this does not go on
---------------------- endlessly, we must exit out of block by checking a condition in Step 2, 3, 4 or
5 and then moving execution to Step 6 or elsewhere. In this case, we will be
---------------------- repeatedly execute Step 2 to Step 5. Such kind of flow is called repetitive flow.
Repetitive flow can be represented using the circular arrow symbol as in the
---------------------- figure below.
----------------------
----------------------
----------------------
----------------------
----------------------
Activity 3
----------------------
Write an algorithm to find the largest of a set of five numbers.
----------------------
----------------------
5.6 ITERATIVE FLOW
----------------------
Till now we have learnt to execute certain statements in algorithm
----------------------
depending on conditions and also repeat the statement conditionally. Sometimes
---------------------- we may have to repeat set of statement fixed number of times, i.e., iterate over
the statements certain number of times. These types of flows where we iterate
---------------------- over the block of steps are called iterative flows.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Fig. 5.5: Iterative Flow
----------------------
Let us understand this better with some examples.
----------------------
Example 8: Algorithm to add first n numbers.
To add first n numbers, we must add 1 and 2 first. Then add 3 to this sum ----------------------
and continue till we have added n to the sum. So the algorithm could be: ----------------------
Start
----------------------
Step 1: X = 1
----------------------
Step 2: Y = 2
Step 3: If Y = n+1 then go to Step 7 else go to Step 4 ----------------------
----------------------
----------------------
----------------------
----------------------
Summary
----------------------
Answers to Check your Progress
----------------------
Check your Progress 1
Fill in the blanks. ----------------------
----------------------
----------------------
6
Structure:
6.1 Introduction
6.2 Nested Sequences
6.3 Parallel Execution
6.4 Fork and Join
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
----------------------
---------------------- In this unit, we will learn about the advanced constructs in an algorithm
which can be used to deal with complex situations.
----------------------
6.2 NESTED SEQUENCES
----------------------
In an algorithm multiple steps are written one after the other, in the order
----------------------
in which they should be executed. We can jump to specific statements if that
---------------------- needs to be executed next. Unless a jump is introduced the algorithm continues
in sequence.
----------------------
If we need to repeat certain steps, we jump back to a previous step number.
---------------------- In Algorithm Example 6 in Unit 5, we had repeated steps to check if the given
number is a prime number. The algorithm is copied again here.
----------------------
The diagram below depicts a nested repetitive flow, where the outer ----------------------
repetitive loop contains an inner repetitive loop.
----------------------
----------------------
----------------------
----------------------
Condition 2
----------------------
Step 5 ----------------------
Step 6
----------------------
----------------------
---------------------- Scenario 1
Condition 1: false {Outer loop: 1}
----------------------
Step 3
----------------------
Step 4: Condition 2: false {Outer loop: 1, Inner loop: 1}
---------------------- Step 5
---------------------- Step 6
---------------------- Step 3
Step 4: Condition 2: false {Outer loop: 2, Inner loop: 1}
----------------------
Step 5
----------------------
Step 6
---------------------- Step 4: Condition 2: false {Outer loop: 2, Inner loop: 2}
---------------------- Step 5
---------------------- Step 6
Step 4: Condition 2: false {Outer loop: 2, Inner loop: 3}
----------------------
Step 5
----------------------
Step 6
---------------------- Step 4: Condition 2: true
----------------------
Scenario 2
Condition 1: false {Outer loop: 1} ----------------------
Step 3 ----------------------
Step 4: Condition 2: false {Outer loop: 1, Inner loop: 1} ----------------------
Step 5
----------------------
Step 6
----------------------
Step 4: Condition 2: false {Outer loop: 1, Inner loop: 2}
Step 5 ----------------------
Step 6 ----------------------
Step 4: Condition 2: false {Outer loop: 1, Inner loop: 3} ----------------------
Step 5
----------------------
Step 6
----------------------
Step 4: Condition 2: false {Outer loop: 1, Inner loop: 4}
Step 5 ----------------------
Step 6 ----------------------
Step 4: Condition 2: true ----------------------
Step 7 ----------------------
Condition 1: false {Outer loop: 2}
----------------------
Step 3
----------------------
Step 4: Condition 2: false {Outer loop: 2, Inner loop: 1}
Step 5 ----------------------
Step 6 ----------------------
Step 4: Condition 2: false {Outer loop: 2, Inner loop: 2} ----------------------
Step 5
----------------------
Step 6
----------------------
Step 4: Condition 2: true
Step 7 ----------------------
Condition 1: false {Outer loop: 3} ----------------------
Step 8: Move to next line (To start printing next table on next line) ----------------------
Step 9: Go to Step 2 ----------------------
Step 2: X is not equal to Y+1 (X=13, Y=15)
----------------------
…Algorithm thus continues to print multiplication tables of 13, 14 and 15
----------------------
----------------------
Check your Progress 1
----------------------
State True or False.
----------------------
1. In a nested flow the outer loop is executed within an inner loop.
----------------------
2. The number of repetitions of inner loop can be different for every
execution of outer loop. ----------------------
3. The values of inner loop variables are reset every time the outer loop ----------------------
repeats.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
---------------------- For optimising the memory utilisation, multiple steps may need to be
performed in parallel like checking the current memory use, freeing the memory
---------------------- occupied by unused objects, prioritising the current applications, moving the
objects occupying large amount of memory out of memory, etc. Let us try to
---------------------- write a simple algorithm for memory optimisation.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Fig. 6.3: Fork and Join
----------------------
In the above flow, after Step 3 there may be two separate programs. One
---------------------- set will execute Step 4, Step 5 and Step 6; the other set will execute Step 7
and Step 8. Once both the sets have finished execution then Step 9 will be
---------------------- performed.
---------------------- Steps after join do not continue unless all the steps in forked sets are
completed.
----------------------
Fork and join can be used to perform actions that can be performed in
---------------------- parallel but must be combined later to proceed. For example, to find the ratio
Step 3 ----------------------
Step 4 ----------------------
Step 5
----------------------
Or
----------------------
Scenario 2: When total population is found first
Step 1 ----------------------
Step 2 ----------------------
Step 4 ----------------------
Step 3
----------------------
Step 5
----------------------
In either scenario, Step 5 is not executed unless both the sets - Step 3 and
Step 4 are completed. Thus, the dependencies can be taken care of using fork ----------------------
and join.
----------------------
Now let us correct the algorithm to withdraw money from bank account
using fork and join by adding the dependency. ----------------------
Example 6: Algorithm to withdraw money from a bank account. ----------------------
Step 1: Start
----------------------
Step 2: Get the amount to be withdrawn
----------------------
Fork
----------------------
---------------------- Step 3: Check the current balance Step 5: Give the user the amount to be
withdrawn
---------------------- Step 4: If current balance is more than Step 6: Current Balance = Current
amount to be withdrawn then approve the Balance – Amount to be withdrawn
---------------------- withdrawal
---------------------- Join
---------------------- Step 2
Fork:
----------------------
Step 5
----------------------
Step 3
---------------------- Step 6
---------------------- Step 4
----------------------
Activity 2
----------------------
---------------------- Enlist three situations where fork and join can be used to write an algorithm.
----------------------
• In a nested flow, the body of one set of instructions contains another set of ----------------------
instructions.
----------------------
• In a nested flow every time the outer loop executes the inner loop starts
from beginning. ----------------------
• There can be special type of algorithms which need to call itself ----------------------
repetitively. It is called recursive flow.
----------------------
• Whenever multiple sets of instructions have to execute simultaneously,
then we can use parallel execution. ----------------------
• The order of execution of steps in different sets in a parallel flow cannot ----------------------
be predicted.
----------------------
• Since the order of execution cannot be defined, the dependent sets of
instructions should not be placed in parallel sets of execution. ----------------------
• Fork and join can be used to perform actions that can be performed in
----------------------
parallel but must be combined later to proceed.
• Fork indicates that the execution can be split into two set of steps which ----------------------
may execute in parallel. After both the set of steps are executed, the flow ----------------------
is connected using a join statement.
• Steps after join do not continue unless all the steps in forked sets are ----------------------
completed. ----------------------
Keywords ----------------------
----------------------
• Nested: Contained within another.
• Recursive: One which repeats itself. ----------------------
• Fork: Split the process. ----------------------
----------------------
Self-Assessment Questions
----------------------
1. Write a short note on parallel flow in an algorithm.
----------------------
2. Describe the following with examples:
i. Recursive flow ----------------------
----------------------
---------------------- 1. The order of execution of steps in different sets in parallel execution is:
ii. Not fixed
----------------------
2. If multiple blocks are executed in parallel, then logically dependent
---------------------- statements should be placed in:
---------------------- i. Same block
3. The implementation of parallel execution is dependent on the underlying:
----------------------
i. Operating system
----------------------
Check your Progress 3
----------------------
Fill in the blanks.
---------------------- 1. Fork and join are used in combination.
---------------------- 2. Steps after join do not continue unless all the steps in forked sets are
completed.
----------------------
3. Fork is used to split the execution into two sets.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
7
Structure:
7.1 Introduction
7.2 Searching Algorithms
7.3 Linear Search
7.3.1 Complexity of Linear Search
7.4 Binary Search
7.4.1 Complexity of Binary Search
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
----------------------
7.3 LINEAR SEARCH
----------------------
This is the most natural searching method. When data items are stored
in a collection such as a list, we say that they have a linear or sequential ----------------------
relationship. Each data item is stored in a position relative to the others. These
----------------------
relative positions are the index values of the individual items. Since these index
values are ordered, it is possible for us to visit them in sequence. This process ----------------------
gives rise to our first searching technique, the sequential search.
----------------------
Figure 7.1 shows how this search works. Starting at the first item in the
list, we simply move from item to item, following the underlying sequential ----------------------
ordering until we either find what we are looking for or run out of items. If we
run out of items, we have discovered that the item we were searching for was ----------------------
not present.
----------------------
----------------------
----------------------
----------------------
Fig. 7.1: Sequential Search of a List of Integers
----------------------
The most intuitive way to search for a given ITEM in LIST is to compare
ITEM with each element of LIST one by one. ----------------------
The algorithm for a sequential search procedure is presented below. ----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Forward iteration
----------------------
This pseudo code describes a typical variant of linear search, where the
---------------------- result of the search is supposed to be either the location of the list item where
the desired value was found or an invalid location to indicate that the desired
----------------------
element does not occur in the list.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
---------------------- Applications
---------------------- Linear search is usually very simple to implement and is practical when
the list has only a few elements or when performing a single search in an
---------------------- unordered list.
---------------------- When many values have to be searched in the same list, it often pays to pre-
process the list in order to use a faster method. For example, one may sort the
---------------------- list and use binary search or build any efficient search data structure from it.
Should the content of the list change frequently, repeated re-organization may
---------------------- be more trouble than it is worth.
---------------------- As a result, even though in theory other search algorithms may be faster
than linear search (for instance binary search), in practice, even on medium
----------------------
sized arrays (around 100 items or less), it might be infeasible to use anything
---------------------- else. On larger arrays, it only makes sense to use other, faster search methods
if the data is large enough, because the initial time to prepare (sort) the data is
---------------------- comparable to many linear searches.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
---------------------- Activity 1
----------------------
1. Create an array to store the following 10 elements in it: 23, 52, 9, 34,
---------------------- 77, 18, 10, 42, 55, 29
2. Write the pseudocode to find the position of 10 and display it as “The
----------------------
position of element 10 is _____” (Hint: Use Sequential search method.)
---------------------- 3. Using sequential search method, write a program to create an array
---------------------- to store any 5 numbers and display the position of all those numbers,
which are divisible by 5.
---------------------- 4. Write a pseudocode to store any 5 elements in an array and display the
---------------------- square of position of entered number.
5. Write a pseudocode to create an array to store any 5 elements and
---------------------- display the elements, which are present at even positions.
---------------------- 6. Suppose you are doing a sequential search of the list [15, 18, 2, 19,
18, 0, 8, 14, 19, 14]. How many comparisons would you need to do in
----------------------
order to find the key 18?
---------------------- 7. Suppose you are doing a sequential search of the ordered list [3, 5, 6,
8, 11, 12, 14, 15, 17, 18]. How many comparisons would you need to
----------------------
do in order to find the key 13?
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Initially, we begin with the entire array LIST; i.e. we begin with BEG =
---------------------- 1 and END = n, If ITEM is not in LIST, then eventually we obtain END< BEG
---------------------- This condition signals that the search is unsuccessful and in this case, we
assign LOC: =
----------------------
NULL. Here NULL is a value that lies outside the set of indices of LIST.
---------------------- We now formally state the binary search algorithm.
Binary Search Function
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Activity 2
----------------------
1. Store the following elements in an array: 10, 25, 36, 48, 62, 100 ----------------------
Using Binary search method, write the pseudocode to find the position ----------------------
of 62.
2. Store the following elements in an array: 87, 52, 41, 26, 19, 12, 8, 5, ----------------------
3, 1 ----------------------
3. Using the Binary search method, write the pseudocode to find the
position of 52. ----------------------
----------------------
Summary ----------------------
----------------------
Keywords
----------------------
• Searching: Finding particular element
----------------------
• Linear Search: Sequential searching
• Binary Search: Searching in sorted array ----------------------
----------------------
----------------------
8
Structure:
8.1 Introduction
8.2 Types of Sorting Algorithms
8.3 Selection Sort
8.4 Bubble Sort
8.5 Merge Sort
8.6 Quick Sort
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
----------------------
8.1 INTRODUCTION
----------------------
Sorting is the technique of arranging the elements/records in a
----------------------
particular order or sequence. The arrangement is most often made as ascending
---------------------- or descending if there is numerical data and alphabetical if there is character
data. In an ascending order, the elements are arranged in increasing order. In
---------------------- descending, the elements are arranged in decreasing order. The commonly
used order is numerical or alphabetical. The process of sorting holds a major
----------------------
importance in computer science as it helps in speeding up the process of
---------------------- searching an element or a record.
Sorting helps in faster and efficient search in a database. The reverse of
----------------------
sorting is shuffling which means arranging the elements in random or unordered
---------------------- way.
The advantage of sorting is that it allows to arrange the data in a meaningful
----------------------
order, but it also is a time-consuming process.
---------------------- Let A be a list of N elements A1, A2, A3......, AN in memory. Sorting of A
---------------------- means arranging the elements of A numerically or alphabetically so that they
are either in ascending or descending order
---------------------- i.e.,
---------------------- A1< = A2 <= A3<= ….... <= AN
---------------------- or
A1 >= A2 >= A3 >= …..... >= AN
----------------------
----------------------
---------------------- Activity 1
----------------------
1. For the given alphabets in the word “COMPUTER”, arrange the
---------------------- elements in ascending and descending order.
2. Suppose S is the following list of 14 alphabetic characters:
----------------------
“DATASTRUCTURE”.
----------------------
Suppose the characters in S are to be sorted alphabetically. Sort the
---------------------- elements in ascending and descending order.
This process is continued till the last element in the list. The elements ----------------------
underlined shows the elements which are swapped. The number of iterations is
directly proportional to the number of elements in the list. In the above example, ----------------------
the number of elements are 10 and hence require 9 iterations to get a sorted list. ----------------------
This method also does not require additional storage.
----------------------
If the size of the array is n, then the number of comparisons to find the
largest element in each sub-array is n+(n-1)+(n-2)+....+2+1 comparisons, which ----------------------
is equal to n(n-1)/2 comparisons.
----------------------
At each iteration, a swapping is performed. So if the number of elements
is n, then in all (n-1), comparisons are required. ----------------------
Algorithm ----------------------
1. for I=1 to N-1
----------------------
2. min=A [I]
----------------------
3. for K=I+1 to N
4. if (min>A [I]) ----------------------
5. min=A [K], Loc=K ----------------------
---------------------- Disadvantages
1. It works better in smaller lists.
----------------------
2. The performance is also affected by the initial ordering of the elements.
----------------------
3. It gives poor efficiency when applied on a large list.
---------------------- 4. There is an extra overhead involved in finding the largest element in each
iteration.
----------------------
----------------------
Activity 2
----------------------
Data 32 11 41 45 27 34 12 56 48 63 ----------------------
11 32 41 45 27 34 12 56 48 63
11 32 41 45 27 34 12 56 48 63 ----------------------
11 32 41 45 27 34 12 56 48 63 ----------------------
11 32 41 27 45 34 12 56 48 63
11 32 41 27 34 45 12 56 48 63 ----------------------
11 32 41 27 34 12 45 56 48 63
11 32 41 27 34 12 45 56 48 63 ----------------------
11 32 41 27 34 12 45 48 56 63
----------------------
3rd Iteration
----------------------
Data 11 32 41 27 34 12 45 48 56 63
11 32 41 45 27 34 12 56 48 63 ----------------------
11 32 41 45 27 34 12 56 48 63
11 32 41 45 27 34 12 56 48 63 ----------------------
11 32 41 27 45 34 12 56 48 63
11 32 41 27 34 45 12 56 48 63 ----------------------
11 32 41 27 34 12 45 56 48 63 ----------------------
11 32 41 27 34 12 45 56 48 63
4th Iteration ----------------------
Data 11 32 41 27 34 12 45 56 48 63 ----------------------
11 32 41 45 27 34 12 56 48 63
11 32 41 45 27 34 12 56 48 63 ----------------------
11 32 41 45 27 34 12 56 48 63 ----------------------
11 32 41 27 45 34 12 56 48 63
11 32 41 27 34 45 12 56 48 63 ----------------------
11 32 41 27 34 12 45 56 48 63
----------------------
As can be seen from the above example, each iteration requires a set of
comparisons to be made. After the first iteration, the number that is the largest ----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Activity 3 ----------------------
----------------------
Here is an array of ten integers:
----------------------
5389170264
----------------------
Draw this array after the FIRST iteration of bubble sort (sorting from
smallest to largest). ----------------------
----------------------
8.5 MERGE SORT
----------------------
Merge sort is based on the concept of divide and conquer. In this approach,
----------------------
a larger problem set is divided into smaller sub-lists and the solution is applied
on the smaller sub-lists. Initially, the entire list is divided into two smaller sub- ----------------------
lists, which in turn is divided into two smaller sub-lists, and so on till a sub-list
is contains two numbers. The two numbers are sorted. The smaller sub-lists are ----------------------
combined together to get a sub-list of four numbers. This process is repeated
----------------------
till the entire list is combined together. Merge sort is an example of external
sorting. The entire process of dividing the list and combining the smaller sub- ----------------------
lists is a recursive process. It is a recursive sorting procedure.
----------------------
To sort an array of n elements, merge sort process goes through the
following steps: ----------------------
----------------------
---------------------- }
while (i <= q) B[k++] = A[i++] // copy any leftover to B
----------------------
while (j <= r) B[k++] = A[j++]
----------------------
for i = p to r do A[i] = B[i] // copy B back to A
---------------------- }
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
Advantages ----------------------
1. Works well for very large list. ----------------------
2. Stable algorithm. ----------------------
3. It is a fast recursive sorting process.
----------------------
4. Useful for both internal and external sorting.
----------------------
5. It requires a temporary storage that is as large as the original array to be
sorted. ----------------------
Disadvantages
----------------------
1. The process is time-consuming.
----------------------
Check your Progress 4 ----------------------
1. Merge sort makes two recursive calls. Which statement is true after ----------------------
these recursive calls finish, but before the merge step?
----------------------
i. The array elements form a heap.
----------------------
ii. Elements in each half of the array are sorted amongst themselves.
iii. Elements in the first half of the array are less than or equal to ----------------------
elements in the second half of the array. ----------------------
iv. None of the above.
----------------------
----------------------
Activity 4
----------------------
Here is an array of ten integers: ----------------------
5389170264
----------------------
Draw this array after two recursive calls of merge sort are completed, and
before the final merge step has occurred. ----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
---------------------- 1. Suppose we are sorting an array of eight integers using quicksort, and
we have just finished the first partitioning with the array looking like
---------------------- this:
---------------------- 2 5 1 7 9 12 11 10
Which statement is correct?
----------------------
i. The pivot could be either 7 or 9.
----------------------
ii. The pivot could be 7, but it is not 9.
---------------------- iii. The pivot is not 7, but it could be 9.
---------------------- iv. Neither 7 nor 9 is the pivot.
---------------------- Fill in the blanks.
1. Quick Sort is based on the divide and _____________ strategy.
----------------------
2. Quick Sort was invented by _____________________.
----------------------
State True or False.
---------------------- 1. The sub-lists are generated till the smaller sub-lists are of size smaller
---------------------- than 2.
----------------------
Activity 5
----------------------
---------------------- Here is an array which has just been partitioned by the first step of quick sort:
---------------------- 3, 0, 2, 4, 5, 8, 7, 6, 9
Which of these elements could be the pivot? (There may be more than one
----------------------
possibility!)
----------------------
●● Sorting is a very important process and has many applications in various ----------------------
fields.
----------------------
●● Sorting helps in finding a record or data easily in a set of data.
----------------------
●● he selection of sorting algorithm is dependent on various factors
T
including the type of data, etc. ----------------------
●● Merge sort is a typical example of external sorting.
----------------------
Keywords ----------------------
----------------------
Self-Assessment Questions
----------------------
1. Suppose the following numbers are stored in an array A.
----------------------
32, 51, 27, 85, 66, 23, 13, 57.
----------------------
Sort the array using bubble sort.
2. Explain selection sort with the data of 10 numbers. ----------------------
----------------------
Answers to Check your Progress
----------------------
Check your Progress 1
----------------------
Multiple Choice Single Response.
1. The operation of processing each element in a list is called: ----------------------
----------------------
----------------------
---------------------- ii. 5
Check your Progress 4
----------------------
Multiple Choice Single Response.
----------------------
1. Merge sort makes two recursive calls. Which statement is true after these
---------------------- recursive calls finish, but before the merge step?
---------------------- iii. Elements in the first half of the array are less than or equal to
elements in the second half of the array.
----------------------
----------------------
----------------------
----------------------
----------------------
1. Lipschutz. Data Structures with C. New Delhi: Tata McGraw-Hill.
2. Karumanchi, Narasimha. Data Structures and Algorithms Made Easy. ----------------------
Careermonk Publications.
----------------------
3. Tanenbaum, A. M., Yedidyah Langsam and Moshe J. Augenstein. Data
Structures using C and C++. Prentice Hall. ----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
9
Structure:
9.1 Introduction
9.2 Divide and Conquer Algorithms
9.3 Dynamic Programming
9.4 Greedy Algorithms
9.5 P and NP Complete Problems
Summary
Keywords
Self-Assessment Questions
Answers to Check your Progress
Suggested Reading
----------------------
The steps can be broken down into three stages as follows: ----------------------
a) Substructure: Once the problem definition is done, decompose the ----------------------
given problem into smaller and simpler sub-problems. Represent the
solution in reference to the sub-problems. The significance of Dynamic ----------------------
Programming allows many de-compositions of the solutions depending
----------------------
on the final output.
b) Table-Structure: After the decomposition and there-after, the solutions ----------------------
or the inter-mitten results of the sub-problems are stored in tables. This is
----------------------
done because the results of the sub-problems can be reused again. Saving
the results in tables saves time and optimizes the execution. We need not ----------------------
take efforts to repeatedly solve the same problem.
----------------------
c) Computation: The computation is done using a bottom-up approach.
Using a table or the stored result sets of the smaller sub-problems are ----------------------
merged. The combined or merged result is used to derive the final solution
for the complete problem. The bottom-up concept is used as follows: ----------------------
This says that the value of the solution to i items ----------------------
either a) include ith item: Here it is vi plus a sub-problem solution for (i - 1)
items and the weight excluding wi or does not include ith item. Here it is a sub- ----------------------
problem›s solution for (i - 1) items and the same weight. ----------------------
That is, if the thief picks item i, having vi value, and he can choose from
items w - wi, and get c[i - 1, w - wi] additional value. On other hand, if thief ----------------------
decides not to take item i, He can choose from item 1,2, . . . , i- 1 up-to the ----------------------
weight limit w, and get c[i - 1, w] value.
----------------------
The algorithm suggests that the better of these two choices should be
made. ----------------------
The algorithm takes as input the maximum weight W, the number of items
----------------------
n, and the two sequences v = <v1, v2, . . . , vn> and w = <w1, w2, . . . , wn>. These
two sequences are stored in a two-dimensional array like A[i, j]values in the ----------------------
table. We can represent the array as follows: i.e., array A[0 . . n, 0 . . w].
----------------------
----------------------
9.4 GREEDY ALGORITHMS
----------------------
Greedy algorithms are simple, easy and straightforward. They are
shortsighted in their approach which means that they take choices based on ----------------------
available information and by not fretting about the outcomes of these choices
that may be forthcoming. These are comfortable in development, easy to ----------------------
employ and greatly economical. Though not all problems can be solved using
----------------------
the greedy method they are useful to decipher optimization problems.
Characteristics and Features of Problems solved by Greedy Algorithms ----------------------
Algorithms manage with two sets in order to develop optimized solutions. ----------------------
One of these includes selected items while the other has rejected items. Greedy
Algorithm have four procedures: ----------------------
i. A procedure that inspects if the selected set of items give a solution ----------------------
ii. A procedure that inspects the viability of a set ----------------------
iii. A selection procedure that tells which of the candidates is the most
----------------------
conforming.
iv. An objective procedure, which inexplicitly provides the value of a ----------------------
solution.
----------------------
Organization of Greedy Algorithm
----------------------
●● At start, the answer set is empty.
●● At each stage ----------------------
An element is added to the answer set by the selection procedure ----------------------
If the set is not feasible, the elements are rejected.(and generally not ----------------------
considered at all)
Else if the answer set is feasible then the elements are added. ----------------------
---------------------- Fixed-length code requires 300,000 bits while variable code requires
224,000 bits for compression.
---------------------- => Saving of approximately 25%.
---------------------- c) Prefix Codes: In which no code word is a prefix of other codeword.
The reason prefix codes are desirable is that they simplify the complete
----------------------
process of encoding and decoding i.e. coding.
---------------------- d) Spanning Trees: A spanning tree of a graph is any tree that includes
every vertex in the graph. It can be also termed as a sub graph of a graph
----------------------
which is a tree and contains all the vertices. An edge of a spanning tree
---------------------- is called a branch; an edge in the graph that is not in the spanning tree is
called a chord. Spanning trees are used to find a simple, cheap and yet
---------------------- efficient way to connect a set of terminals (computers, cites, factories,
etc.).
----------------------
Spanning trees are useful for the following reasons:
----------------------
They can construct a sparse sub graph that provides information
---------------------- about the original graph.
----------------------
----------------------
NP
----------------------
NP- Complete
----------------------
----------------------
----------------------
P ----------------------
Fig. 9.1: Relationship between P, NP, NP-complete, NP Hard ----------------------
The relationship between P, NP, NP C can be represented mathematically as:
----------------------
●● P NP
----------------------
●● NPC NP
----------------------
●● P = NP
●● NPC = NP ----------------------
----------------------
----------------------
---------------------- iii. A selection procedure that tells which of the candidates is the
most confirming.
---------------------- iv. An objective procedure, which inexplicitly provides the value
---------------------- of a solution.
v. All of the above
----------------------
2. A problem x that is in NP is also in NP-Complete if and only if?
----------------------
i. x is in NP
---------------------- ii. Every problem in NP is reducible to x
---------------------- iii. Both
---------------------- Fill in the blanks.
1. ______ is a technique used for compressing data.
----------------------
2. ______ is the set of all decision problems which can be solved in
---------------------- polynomial time by a deterministic Turing machine.
---------------------- 3. ______ problems are also NP-hard.
----------------------
---------------------- Activity 2
---------------------- Understand the Travelling Salesman Problem and solve the same using NP-
---------------------- Complete.
----------------------
Summary
----------------------
●● Divide and Conquer uses a top-down approach in its algorithms. The
---------------------- divide and conquer algorithms divide the question or problem into small
---------------------- sub-questions or sub-problems.
●● ynamic programming is an approach which uses divide-and-Conquer
D
---------------------- technique with a table.
---------------------- ●● Dynamic programming is more strong and refined design technique
----------------------
Keywords
----------------------
●● Algorithm: Sequence of steps to perform the desired task
●● ivide and Conquer: It works by recursively breaking down a problem
D ----------------------
into two or more sub-problems of the same (or related) type ----------------------
●● ynamic Programming: It is a method for solving complex problems
D
by breaking them down into simpler sub problems ----------------------
●● reedy Algorithm: An algorithm that follows the problem
G ----------------------
solving heuristic of making the locally optimal choice at each stage
----------------------
●● Sorting Algorithms: Algorithms used to sort lists
----------------------
Self-Assessment Questions ----------------------
1. Explain Divide and Conquer algorithm in detail with examples. ----------------------
2. Differentiate between P, NP-Complete, P and NP Hard.
----------------------
3. Write an algorithm for Insertion Sort using Divide and Conquer.
----------------------
4. What is Greedy Algorithm? Explain with an example.
----------------------
Answers to Check your Progress
----------------------
Check your Progress 1
----------------------
Fill in the blanks.
----------------------
1. Divide and conquer uses top – down approach in its algorithms.
3. Substructure, Table-structure and Bottom - up are the steps involved in ----------------------
dynamic programming. ----------------------
3. In dynamic programming, substructure involves decomposing a problem
into smaller and simpler sub-problems. ----------------------
----------------------
----------------------
Suggested Reading
----------------------
1. Horowitz, Ellis, et al. Fundamentals of Computer Algorithms. Galgotia
---------------------- Publications.
---------------------- 2. Huang, Chung-Yang (Ric), Chao-Yue Lai and Kwang-Ting (Tim) Cheng.
“Fundamentals of algorithms”. Electronic Design Automation. Morgan
---------------------- Kaufmann Publishers.
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------
----------------------