Professional Documents
Culture Documents
DS. Unit I
DS. Unit I
DS. Unit I
RREEVVIISSEED
D SSYYLLLLA
ABBU
USS O
OFF B
B..SScc.. ((C
COOM
MPPU
UTTEER
R SSC
CIIEEN
NCCEE// IIN
NFFO
ORRMMA
ATTIIO
ON N
TTEEC
CHNOLOGY) UNDER CBCS FRAMEWORK WITH EFFECT FROM 2020-2002211
H N O L O G Y ) U ND ER C B C S F R A M E WO R K W IT H E FFE C T FR O M 202 0- 2
Hrs.
PAPER
YEAR SEM. SUBJECT per Credits IA ES Total
CODE
Week
I C1 Problem Solving in C 4 3 25 75 100
Unit I
Introduction to Data Structures : Introduction to the Theory of Data Structures, Data
Representation, Abstract Data Types, Data Types, Primitive Data Types, Data Structure and
Structured Type, Atomic Type, Difference between Abstract Data Types, Data Types and Data
Structures, Refinement Stages.
Unit II
Linked Lists : Introduction to Lists and Linked Lists, Basic Linked List Operations, Doubly Linked List,
Circular Linked List, Linked List versus Arrays.
Unit III
Stacks: Introduction to Stacks, Stack as an Abstract Data Type, Representation of Stacks through
Array, Representation of Stacks through Linked Lists, Stacks and Recursion.
Queues: Introduction, Queue as an Abstract data Type, Representation of Queues, Circular Queues,
Double Ended Queues- Deques, Priority Queues, Application of Queues.
UNIT - IV
Binary Trees: Introduction to Non- Linear Data Structures, introduction Binary Trees, Types of Trees, Basic Definition
of Binary Trees, Properties of Binary Trees, Representation of Binary Trees, Operations on a Binary Search Tree,
Binary Tree Traversal, Counting Number of Binary Trees, Applications of Binary Tree
UNIT - V
Searching and sorting: Sorting - An Introduction, Bubble Sort, Insertion Sort, merge Sort, Searching - An
Introduction, Linear or Sequential Search, Binary Search, Indexed Sequential Search.
Graphs: Introduction to Graphs, Terms Associated with Graphs, Sequential Representation of Graphs, Linked
Representation of Graphs, Traversal of Graphs, Spanning Trees, Shortest Path, Application of Graphs.
Text 8ooks:
1. “Data Structures using C", ISRD group Second Edition, TPH
2. “Data Structures through C”, Yashavant Kanetkar, BPB Publications
2
DEPARTMENT OF COMPUTER SCIENCE
Dr.L.Bullayya college : Visakhapatnam
Semester Course Code Course Title Hours Credits
II C2-P DATA STRUCTURES USING C LAB 30 2
LAB LIST
1. Write a program to read N numbers into an array and perform the following on an array
15. Write a program to implement Breadth First Search graph traversals algorithm
3
UNIT I
Introduction to Data Structures : Introduction to the Theory of Data Structures, Data
Representation, Abstract Data Types, Data Types, Primitive Data Types, Data Structure and
Structured Type, Atomic Type, Difference between Abstract Data Types, Data Types and Data
Structures, Refinement Stages.
DATA STRUCTURES
Data Structure is a way of organizing the data, not only stored items and also stores its
relationship.
(or)
A data may be organized in many ways such as the Logical (or) mathematical
representation of given data is called as "data structure".
(or)
The method to store the information and computes the memory is collectively known as
Data structure.
Data Structure can be defined as the group of data elements which provides an efficient
way of storing and organizing data in the computer, so that it can be used efficiently.
Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc.
Data Structure plays a very important role in various algorithms, it allows the
programmer to handle the data efficiently.
4
OPERATIONS ON DATA STRUCTURES
The operations involve in data structure are as follows.
1. Create
Used to allocate/reserve memory for the data element(s).
2. Destroy
This operation deallocate/destroy the memory space assigned to the specified data
structure.
3. Selection
Accessing a particular data within a data structure.
4. Update
For Updation (insertion or deletion) of data in the data structure.
5. Searching
Used to find out the presence of the specified data item in the list of data
6. Sorting
Process of arranging all data items either in ascending or in descending order.
7. Merging
Process of combining data items of two different sorted lists of data items into a
single list.
8. Traversing
Traversing the data structure means visiting each element of the data structure in
order to perform some specific operation like searching or sorting.
Example: If we need to calculate the average of the marks obtained by a student in 6
different subject, we need to traverse the complete array of marks and calculate the total
sum, then we will divide that sum by the number of subjects i.e. 6, in order to find the
average.
9. Insertion
Insertion can be defined as the process of adding the elements to the data structure at
any location. If the size of data structure is n then we can only insert n-1 data
elements into it.
10. Deletion
The process of removing an element from the data structure is called Deletion. We can
delete an element from the data structure at any random location.
1. Data Organization:
We need a proper way of organizing the data so that it can accessed efficiently when we
need that particular data. DS provides different ways of data organization so we have
options to store the data in different data structures based on the requirement.
2. Efficiency
The main reason we organize the data is to improve the efficiency. We can store the
data in arrays then why do we need linked lists and other data structures? because
when we need to perform several operations such as add, delete update and search on
arrays, it takes more time in arrays than some of the other data structures. So, the fact
that we are interested in other data structures is because of the efficiency.
5
3. Reusability
Data structure can be reused. Once we have implemented a data structure, the same
data structure can be used later.
4. Abstraction
Data structure hides (abstracts) the implementation details from the user. The user
access the data through an interface and enjoys the benefits of data structures, the
important complex implementation details are hidden from the user.
DATA REPRESENTATION
Data Representation refers to the form in which data is stored, processed, and
transmitted. Devices such as smart phones, iPods, and computers store data in digital
formats that can be handled by electronic circuitry.
Integer Representation
An integer is the basic data type which is commonly used for storing negative as
well as non-negative integer numbers. The non-negative data is represented using
binary number system. In this, each bit position represents the power of 2. The
rightmost bit position represents 20 which is 1, the next represents 21 which is 2,
then 22 which is 4 and so on.
Character Representation
The information in computers is not always interpreted numerically. For example,
to store the salary of an employee we use the integer representation of the data
but with salary we also need to store the name of the employee which requires a
different data representation. Such information is usually represented in character
string form. There are different codes available to store data in character form such
as BCD, EBCDIC and ASCII.
EBCDIC
EBCDIC stands for Extended Binary Coded Decimal Interchange Code. EBCDIC is an eight –
bit code that defines 256 symbols. It is still used in IBM mainframe and midrange systems.
6
ASCII
ASCII (pronounced As-key) stands for the American Standard Code for Information
Interchange. Today, the ASCII character set is by far the most commonly used in computers of
all types. ASCII is an eight-bit code that specifies characters for values from 0 to 127.
Extended ASCII
Extended ASCII is an eight-bit code that specifies the characters for values form 128 to 255.
The first 40 symbols represent pronunciation and special punctuation. The remaining symbols
are graphic symbols.
Unicode
The Unicode worldwide character standard provides up to four bytes – 32 bits – to represent
each letter, number, or symbol, with four bytes, enough Unicode codes can be created to
represent more than 4 billion different characters or symbols.
This total is enough for every unique character and symbol in the world, including the
vast Chinese, .Korean, and Japanese character sets. One major advantage of Unicode over
other text codes is its compatibility with ASCII codes.
7
4. Hexa Decimal Number System
This Number System is used the Numbers from 0 to 15, i.e. totally 16 digits, here we used to
represent the numbers from 0 to 9, and 10-A, 11-B, 12-C, 13-D, 14-E, 15-F. So, the numbers
0-F are used. These numbers having the base 16, and can be represented as
(789)16, (90876)16, (A98F)16
Byte →
8 bits
Unit Equals
4 bits 1 Nibble
8 bits 1 Byte
1024 Bytes 1 Kilo Byte
1024 Kilo Bytes 1 Mega Byte
1024 Mega Bytes 1 Giga Byte
1024 Giga Bytes 1 Terra Byte
1024 Terra Bytes 1 Peta Byte
1024 Peta Bytes 1 Exa Byte
1024 Exa Bytes 1 Zetta Byte
1024 Zetta Bytes 1 Yotta Byte
1024 Yotta Bytes 1 Bronto Byte
1024 Bonto Bytes 1 Geop Byte ( to be continued..)
8
ADT – ABSTRACT DATA TYPE
In computer science, an abstract data type is a mathematical model for data types. An
abstract data type is defined by its behavior from the point of view of a user, of the data,
specifically in terms of possible values, possible operations on data of this type, and the
behavior of these operations.
Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by
a set of value and a set of operations. ... Think of ADT as a black box which hides the inner
structure and design of the data type. Now we'll define three ADTs namely List ADT, Stack
ADT, Queue ADT.
An Abstract Data Type (ADT) is an abstract concept defined by axioms which
represent some data and operations on that data. Abstract Data Types are focused on what,
not how (they're framed declaratively, and do not specify algorithms or data structures).
Common examples include lists, stacks, sets, etc.
There are two parts to each ADT- Public and Private
1. The public or external part, which consists of:
• The conceptual picture (the user's view of what the object looks like, how the
structure is organized)
• The conceptual operations (what the user can do to the ADT)
2. The private or internal part, which consists of:
• The representation (how the structure is actually stored)
• The implementation of the operations (the actual code)
ADVANTAGES OF ADT
• ADT is reusable and ensures robust data structure .
• It reduces coding efforts.
• Encapsulation ensures that data cannot be corrupted.
• ADT is based on principles of Object Oriented Programming (OOP) and software
Engineering (SE).
• It specific error conditions associated with operation.
9
DATA TYPE
A data type is a set of data values having predefined characteristics. You will have
encountered data types during computer programming. In sense, it describes which type of
data is stored in the variable.
Ex: integer, float, character and Boolean.
Generally in all programming languages we have a limited number of such data types. The
range of values that can be stored in each of these data types is defined by the languages and
the computer hardware that the high level language is used.
Integer -
Type Size (in bytes) Min. value Max. value
byte 1 -128 127
short 2 -32,768 32,767
int 4 -2,147,483,648 2,147,483,647
-
long 8 9,223,372,036,854,775,8 9,223,372,036,854,775,80
08 8
C. Character type
Java provide a character data type called char to store character constants .The char type
assumes a size of 2 bytes but it can hold only a single characters.
D. Boolean type
Boolean type is used when we want to test a particular condition during the execution of
the program. There are only 2 values that Boolean type can take: true or false. Only one
bit is required to store Boolean values.
10
II. Structured or non- primitive data types
Non - primitive data types hold a collection of data values. This collection will generally
consists of the primitive data types.
Example of this would include
ARRAYS,
RECORDS (STRUCTURES),
CLASSES AND
FILES.
These data types, which are created by programmers, are extremely important and are the
building block of data structures.
Non-primitive data types in java languages are arrays, classes, interface etc. These are
also examples of reference data types.
TYPES OF STRUCTURES
There are mainly two types of structures, they are
1. Storage structure: It is the representation of the data structure in the computer
memory.
2. File structure : It is the representation of the storage structure in the auxiliary
memory.
1. STORAGE STRUCTURES
The memory that is allocated to a variable or a constant is stored in the main memory
of the computer that is RAM which gets deleted as soon as the function ends. This
representation of allocating the memory is called Storage Structure.
1. several types of data storage exist in most of the computer systems. They vary in
speed of access, cost per unit of data and reliability.
a) Cache
Most costly and fastest form of storage. Usually very small, and managed by the
operation system. It is placed between CPU and Main Memory.
b) Main Memory
The storage area for data available to be operated on General –purpose
machine instruction operate on main memory.
Contents of main memory are usually lost in a power failure or ”crash”.
Usually too small (even with megabytes) and too expensive.
c) Flash memory
EEPROM ( Electrically Erasable programmable read –only memory)
Data in flash memory survive from power failure.
· Reading data from flash memory takes about 10 nano –sec s (roughly as fast
as from main memory), and writing data into flash memory is more
complicated :write –once takes about 4-10 micro secs.
It has found its popularity as replacement for disks for storing small volumes of
data (5-10 megabyte)
d) Tape storage
It is used primarily for backup and archival data. Cheaper, but much slower
access, since tape must be read sequentially from the beginning.
Used as protection from disk failures!
e) Magnetic disk storage
Typically the entire database is stored on disk
11
Data must be moved from disk to main memory in order for the data to be
operated on.
After operations are performed, data must be copied back to disk if any changes
were made.
Disk storage is called direct access storage as it possible to read data on the
disk in any order (unlike sequential access).
Disk storage usually survives power failure and system crashes
f) Optical storage
CD-Rom (compact disk - read only memory), WORM(write-once read many) disk
(for archival storage of data), and juke box (containing as few drives and
numerous disks loaded on demand).
3. Volatility of storage, volatile storage loses its contents when the power is removed
without power back up, data in the volatile storage (the part of the hierarchy from main
memory up) must be written to non-volatile storage for safekeeping.
2. FILE STRUCTURES
A file can be defined as a collection of data or information.
There are two types of files. They are Program files and Data Files.
Program files can be described as files containing software instructions.
A file structure allows applications to read, write and modify data. It might also
support finding the data that matches some search criteria or reading though the data
in some particular order.
13
The storage structure of these data structure are
A. Integer
B. Float
C. character
D. Boolean
B. Real Number or Float: In the several languages real numbers are implemented as
floating point numbers and double precision floating point numbers.
A real number consists of two parts, mantissa and characteristic. A real number
data type is generally denoted with the term float. There are many varieties of floating
point notation and each has individual characteristic .
A real number is represented using the following expression : m x n r, where m is
the mantissa and n is the base (which is fixed 10) and r is the exponent.
A floating point notation facilitates storage of number with extremely large and
extremely small values. The range of values that can be represented in a float data
types are from -3.4 e -38 to 3.4 +38
C. Characters: A character data type relates to the representation of alpha numeric data.
Traditionally the coding system is ASCII .These are all 8-bit system. Most of the
computers use eight bits to represent a character. That is 256 character can be
represented. In java language 16-bit Unicode system as implemented character data
type represents 2 bytes in java.
D. Boolean: Boolean data type allows for two possible values: true or false. Only one bit
is required to store Boolean values.
Definition: “An array is defined as a set of homogeneous (same data type) data items.
They can have a common name and stored in continues locations of the memory.”
The individual values of array are called as elements. Array can be any valid data type
item.
Int A[n] =
A[0] A[1] A[2] A[3] …… A[n-1]
14
Declaration:
Array will be declared in a program like other variables. The declaration of the array has
the following
Syntax: datatype array_name [ ];
datatype [ ] array_name;
In this datatype is any one of the java supported data types, which indicates the type of
elements of array. array_name is a valid identifier, Size indicates the number of
elements of the array.
It should be a positive integer. Every array must have a subscript.
Arrays can be classified into
1. Single Dimensional Array (or ) Linear Array
2. Multi Dimensional Array. (or) Non Linear Array
15
Operations on Arrays:
1. Creation of array
2. Initialization of array
3. Accepting data into array
4. Displaying contents of array
5. Insertions
6. Deletions
7. Search
8. Sort
Advantages of arrays:
1. As arrays store all the elements in continuous locations, it becomes easy to access all
the elements.
2. Arrays allow the user to store elements of same type in sequential manner.
3. Array elements can be accessed randomly (need not to follow any order).
4. Arrays avoid no. of variables & their naming.
Disadvantages of arrays:
1. Array size is fixed. The user cannot grew or shrink the size dynamically.
2. Optimum utilization of memory may not be achieved (i.e., there is a scope for wasting
the memory).
3. Arrays allow only similar kind of items as data.
b) Linked Lists
Linked list is a linear collection of data elements called nodes, and a node consist of two
parts : data Info and Link Info gives information and Link is an reference of next node.
DATA LINK
Here data/info and link/address pointer both are stored. `So, extra space is needed to
store the pointer associated with each element and that access is take more time.
16
2. DOUBLE LINKED LIST
In a double linked list all nodes are linked together by multiple links, which help in
accessing the both next node and previous node for any item with in the list. Therefore
each node in a double linked list links to the left node and the right node. This helps to
travel the list in forward direction and in backward direction.
Contains Left Link, Data, Right Link
L LINK DATA R LINK
NULL
LINK DATA LINK LINK DATA LINK LINK DATA LINK
c) Stacks
Stack is a list of elements. In stack, an element may be inserted or deleted at one end
which is known as Top of the stack. It performs two operations. Push and Pop. Push
means adding an element into stack. Pop means delete an element from the stack.
Here, both insertion and deletion can takes place at the top of the stack. When we
are taking the operations like insertion and deletion, the last inserted element will be the
first element to delete from the stack.
So, It is also called Last-in-First –out (LIFO) type of list.
Advantages : It provides Last in, First out access can be made easy of operations
Disadvantage : Slow in access to other elements
Operations on Stack:
Push: Adds an item onto the stack. PUSH (s, i); Adds the item i to the top of stack.
Pop: Removes the most-recently-pushed item from the stack. POP (s); Removes the top
element and returns it as a function value.
17
d) Queues
Queue is linear list of element. It can permit insertion of an element at one end, and
deletion of an element in another end. The end at which the element is deleted or removed
from the queue is called as front, and the end at which insertion of an element into the
queue is called rear. So, the insertion and deletion can takes place at front and rear ends
only.
In queue, elements are added at one end called rear and the existing element are
deleted from other and called front.
The first element that is inserted into the queue, is the first one to get deleted from it.
Hence, It is also called as First-in-First- out(FIFO) list.
In general, Queue means a sequential process to follow the order.
Advantages : It provides First in, First out process of data operations
Disadvantage : Slow in access to other elements
Operations on Queue:
Enqueue: Adds an item onto the end of the queue ENQUEUE(Q, i); Adds the item i
onto the end ofqueue.
Dequeue: Removes the item from the front of the queue. DEQUEUE (Q); Removes
the firstelement and returns it as a function value.
a) Trees
A TREE can be defined as a finite set of data elements. A Tree is a flexible, versatile and
powerful non– linear data structures. It is used to represent data items processing
hierarchical relationship between the grandfather and his children & Grand children.
It is an ideal data structures for representing hierarchical data.
A tree is a set of one or more nodes, such that
1) There is a specially designed node called root.
2) The remaining nodes are portioned into disjoints sets, T1, , Tn. These sets of T1,
-----, Tn are called the sub trees of the root.
18
Advantages: It provides quick search, insert and delete operations
Disadvantages : Complicated deletion algorithms
b) Graphs
Graph is a non-linear data structure mainly used in the applications for finding shortest
path root. This data structure consists of number of non-empty set of vertices as well as
edges.
A graph ‘G’ consists of a set of ‘V’ vertices (nodes) and set of ‘E’ edges (arcs)
To represent a graph G= {V, E}, here V is a non-empty set of vertices.
E is a set of pairs of vertices, these pairs are called edges.
Generally, graphs are two types, they are
1. undirected graphs
2. directed graphs.
ATOMIC TYPE
Generally, a data structure is represented by a memory block, which has two
parts:
• Data storage
• Address storage
This facilitates in storing the data and also stores pointers in the address part.
An atomic type data is a data structure that contains only the data items and not
the pointers. Thus, for a list of data items, several atomic type nodes may exist
each with a single data item corresponding to one of the legal data types. The list
is maintained using a list node which contains pointers to these atomic nodes and a
type indicator indicating the type of atomic node to which it points. Whenever a test
node is inserted in the list, its address is stored in the next free element of the list
of pointers.
a list of atomic nodes maintained using list of nodes. In each node, type
represents the type of data stored in the atomic node to which the list node points.
19
Here, I stands for integer type, 2 for real number and 3 for character type or
any different assumption can be made at implementation level to indicate different
data types.
REFINEMENT STAGES
The best approach to solve a complex problem is to divide it into smaller parts
such that each part becomes an independent module which is easy to manage.
An example of this approach is the System Development Life Cycle (SDLC)
methodology. This helps in understanding the problem, analyzing solutions, and
handling the problems efficiently.
The principle underlying writing large programs is the top-down refinement. While
writing the main program, we decide exactly how the work will be divided into various
functions and then, in the refinement process, it is further decided what will be the
task of each function, and what inputs are to be given and results to be
obtained. The data and actions of the functions are specified precisely. Similarly,
the purpose of studying Abstract data types is to find out some general principles that
will help in designing efficient programs. There exists a similarity between the
process of top down refinement of algorithms and the top-down specification of the
data structures. In algorithm design, we begin with the problem and slowly specify
more details until we develop a complete program. In data specification, we begin
with the selection of mathematical concepts and abstract data types required for our
problem, and slowly specify more details until finally we can describe our data
structures in terms of programming language.
The application or the nature of problem determines the number of refinement
stages required in the specification process. Different problems have different
number of refinement stages, but in general, there are four levels of refinement
processes:
• Conceptual or abstract level
• Algorithmic or data structures
• Programming or implementation
• Applications
Conceptual Level
At this level we decide how the data is related to each other, and what operations are
needed. Details about how to store data and how various operations are performed
on that data are not decided at this level
20
retrieving any element, whereas for the evaluation of any expression into prefix or
postfix, stacks will be used.
Programming or Implementation Level
At implementation level, we decide the details of how the data structures will be
represented in the computer memory. For example, we decide whether the linked
lists will be implemented with pointers or with the cursors in an array.
Application Level
This level settles all details required for particular application such as names for
variables or special requirements for the operations imposed by applications
The first two levels are often called conceptual. The middle two levels can be called
algorithmic as they are concerned with representing data and the operations
performed on the same. Last level is basically concerned with programming at the
conceptual level, the queue has been selected as an abstract data type and
further at the next level circular queue has been selected, as this could provide
the best solution. Last level shows the operations which can be performed on the
data, for the Airport simulation,
21
UNIT I
IMPORTANT QUESTIONS
22
Syllabus: Principles of programming and Analysis of algorithms: software engineering,
program design, algorithms, different approaches to designing an algorithm, complexity,
big ‘o’ notation, algorithm analysis, structured approaches to programming, recursion,
tips and techniques for writing c programming
1.What is software engineering?
Software Engineering is a systematic, disciplined, quantifiable study and approach to the
design, development, operation, and maintenance of a software system.
Developing good software is a tedious process which keeps on going i.e. under development for
a long time before the software or the program takes the final shape. This process is often
termed as Software Development Life Cycle (SDLC). Here, the output of one stage becomes the
input of next stage.
What is SDLC?
Developing good software is a tedious process which keeps on going i.e. under development for
a long time before the software or the program takes the final shape. This process is often
termed as Software Development Life Cycle (SDLC). Here, the output of one stage becomes the
input of next stage.
The various steps involved in the Software Development Life Cycle are as follows:
Planning, Analysis, Design, Development, Testing, Implementation and Maintenance
23
• Design an algorithm for the task using the tools of the data structure
• Verify the algorithmic steps
• Analyse the algorithm for checking its requirements
• Code the algorithm to any suitable programming language
• Test and evaluate the code
• Refine and repeat the preceding steps until the software is complete
• Optimize the code to improve performance
• Maintain the application that you have designed so that it meets the upcoming client's and users
need
Program Design
Program design is an important stage of software development. This phase takes the help of
algorithms and different concepts of data structures to solve the problem(s) that is proposed.
Modularity enhances design clarity, which in turn eases implementation and readability.
Debugging, testing, documenting and maintenance of product also increase due to modularity.
• Time Complexity
• Space Complexity
Time Complexity of a program can be defined as the amount of time the computer takes to run a
program to its completion. On the other hand, the space complexity of an algorithm can be
defined as the memory that it needs to run that algorithm to its completion.
Top-down approach
The top-down approach starts by identifying the major components of the system or program
decomposing them into their lower-level components and iterating until the desired level of
modular complexity is achieved. The top-down method takes the form of stepwise working and
refinement of instructions. Thus, the top-down approach starts from an abstract design, and each
step is refined into more concrete level until the final refined stage is not reached.
Bottom –up approach
The bottom-up design starts with designing the most basic or primitive components and proceeds
to the higher-level component. It works with layers of abstraction. Starting from below, the
operation that provides a layer of abstraction is implemented. These operations are further used
to implement more powerful operations and still higher layers of abstraction until the final stage is
reached.
When resolving a computer-related problem, there will frequently be more than just one solution.
These individual solutions will often be in the shape of different algorithms or instructions having
different logic, and you will normally want to compare the algorithms to see which one is more
proficient. So, this is where Big O analysis helps program developers to give programmers some
basis for computing and measuring the efficiency of a specific algorithm.
If f(n) represents the computing time of some algorithm and g(n) represents a known standard
function like n, n2, n log n, then to write:
f(n) is O g(n)
which means that f(n) of n equals to the biggest order of the function, i.e., the g(n).
So what Big - O does? It helps to determine the time as well as space complexity of the
algorithm. Using Big - O notation, the time taken by the algorithm and the space required to run
the algorithm can be ascertained. Some of the lists of common computing times of algorithms in
order of performance are as follows:
• O (1)
• O (log n)
• O (n)
• O (nlog n)
• O (n2)
• O (n3)
25
• O (2n)
Thus, algorithm with their computational complexity can be rated as per the mentioned order of
performance.
Algorithm Analysis
This complexity is used to analyse the algorithm in the data structure. There are various ways of
solving a problem and there exists different algorithms which can be designed to solve the
problem.
Consequently, analysis of algorithms focuses on the computation of space and time complexity.
Here are various types of time complexities which can be analysed for the algorithm:
• Best case time complexity: The best-case time complexity of an algorithm is a measure of the
minimum time that the algorithm will require for an input of size 'n.' The running time of many
algorithms varies not only for the inputs of different sizes but also for the different inputs of the
same size.
• Worst case time Complexity: The worst-case time complexity of an algorithm is a measure of
the minimum time that the algorithm will require for an input of size 'n.' Therefore, if various
• algorithms for sorting are taken into account and say 'n,' input data items are supplied in reverse
order for a sorting algorithm, then the algorithm will require n2 operations to perform the sort
which will correspond to the worst-case time complexity of the algorithm.
• Average Time complexity Algorithm: This is the time that the algorithm will require to execute
a typical input data of size 'n' is known as the average case time complexity.
Structured programming is a paradigm that aims to make programs easier to comprehend from a
reader’s point of view. It does this by linearising the flow of control through a program. In
structured programming, execution follows the writing order of the code.
Structured programming caught favour with programming languages for its iconic opposition to
the keyword goto, aiming to reduce the prevalence of spaghetti code. Some other controversial
features that most languages have not adopted are avoiding early exit and opposition to
exceptions for control flow.
• Block: It is a command or a set of commands that the program executes linearly. The
sequence has a single point of entry (first line) and exit (last line).
• Selection: It is the branching of the flow of control based on the outcome of a condition.
Two sequences are specified: the ‘if’ block when the condition is true and the ‘else’ block
when it is false. The ‘else’ block is optional and can be a no-op.
• Iteration: It is the repetition of a block as long as it meets a specific condition. The
evaluation of the condition happens at the start or the end of the block. When the condition
results in false, the loop terminates and moves on to the next block.
26
• Nesting: The above building blocks can be nested because conditions and iterations,
when encapsulated, have singular entry-exit points and behave just like any other block.
• Subroutines: Since entire programs now have singular entry-exit points, encapsulating
them into subroutines allows us to invoke blocks by one identifier.
What is recursion?
• Recursion is one of the most powerful tools in a programming language, but one of the
most threatening topics-as most of the beginners and not surprising to even experienced
students feel.
• When function is called within the same function, it is known as recursion in C. The
function which calls the same function, is known as recursive function.
• Recursion is defined as defining anything in terms of itself. Recursion is used to solve
problems involving iterations, in reverse order.
Types of Recursions
There are two types of Recursions
• Direct recursion
• Indirect recursion
Direct Recursion
When in the body of a method there is a call to the same method, we say that the method
is directly recursive.
There are three types of Direct Recursion
• Linear Recursion
• Binary Recursion
• Multiple Recursion
Linear Recursion
• Linear recursion begins by testing for a set of base cases there should be at least one.
27
In Linear recursion we follow as under:
• Perform a single recursive call. This recursive step may involve a test that decides which
of several possible recursive calls to make, but it should ultimately choose to make just
one of these calls each time we perform this step.
• Define each possible recursion call, so that it makes progress towards a base case.
Binary Recursion
• Binary recursion occurs whenever there are two recursive calls for each non base case.
Multiple Recursion
• In multiple recursion we make not just one or two but many recursive calls.
Disadvantages of Recursion
• It consumes more storage space the recursive calls along with automatic variables are
stored on the stack.
• The computer may run out of memory if the recursive calls are not checked.
• It is not more efficient in terms of speed and execution time.
• According to some computer professionals, recursion does not offer any concrete
advantage over non-recursive procedures/functions.
• Recursive solution is always logical and it is very difficult to trace. (Debug and
understand).
• In recursive we must have an if statement somewhere to force the function to return
without the recursive call being executed, otherwise the function will never return.
• Recursion takes a lot of stack space, usually not considerable when the program is small
and running on a PC.
• Recursion uses more processor time.
28
• Recursion is not advocated when the problem can be through iteration.
• Recursion may be treated as a software tool to be applied carefully and selectively.
29