SlideShare a Scribd company logo
1 of 98
Data Structures
Unit 1
Introduction
Mrs. Nisha Robin Rohit
Assistant Professor
AMET
Before studying about Data Structures, we should make ourselves aware of the
various terms used in the subject.
 Data
 Entity
 Information
 Data type
 Built-in data type
 Abstract data type
Data
The term data means value or set of values.
Example of data:
a) 34
b) 12/01/1980
c) ISBN 81-203-0000-0
d) |||
e) Pascal
f) 21,25,28,56,90
Entity
 An entity is one that has certain attributes, and which may be assigned values.
 For example, an employee in an organization is an entity.
 The possible attributes and their corresponding values for an entity in the present
example are:
Entity : EMPLOYEE
Attributes: NAME DOB SEX DESIGNATION
Values : RAVI ANAND 30/12/92 M DIRECTOR
 All of the employees in an organization constitute an entity set.
 Each attribute of an entity set has a range of values, and this range is called the
domain of the attribute.
 For example, in EMPLOYEE entity, the attribute SEX has the domain {M,F}.
Entity (ANOTHER EXAMPLE)
Entity : HUMAN
Attributes: SEX SKIN COLOUR EYE COLOUR
Values : M/F DARK/FAIR BLACK/BLUE/BROWN
 Each attribute of an entity set has a range of values, and this range is called
the domain of the attribute.
 For example, in HUMAN entity, the attribute SKIN COLOUR has the domain
{DARK,FAIR,WHEATISH}.
Information
 The term information is used for data with its attributes.
 In other words, information can be meaningful data or processed data.
Data Meaning
34 Age of the person
12/01/1980 Date of Birth of a person
ISBN 81-203-0000-0 Book number, recently published by the person
||| Number of awards equal to the tally marks
achieved by the person
Pascal Nickname of the person
21,25,28,56,90 Important ages of the person
Difference between data and information
Data
Procedure to
process data
Information 1
Information 2
.
.
.
Information I
.
.
Information n
As an example, suppose there is a set of data consisting of the amount of milk
consumed by a person in a month.
From this given set of data, information can be retrieved as follows:
What was the total amount of milk consumed in a month?
On which day was the maximum amount of milk consumed?
On which day was the minimum amount of milk consumed?
What was the average amount of milk consumption per day?
Data Type
A data type is a term refers to the kind of data that may appear in a computation.
The following are few well known data types.
Data Data type
34 Numeric(integer)
12/01/1980 Date
ISBN 81-203-0000-0 Alphanumeric
||| Graphics
Pascal String
21,25,28,56,90 Array of Integers
Real, Boolean, character, complex, etc. are some more frequently used data types.
Built-in Data Type
In every programming language, there is a set of data types called built-in data
types. For example, in C, Java and Python the data types that are available as built-
in are listed below:
Programming Language Built-in Data types
C int, float, char, double, Enum, etc.
Java integer, string, time
Python numeric, sequence, set, binary, string, etc.
Built-in data type provide users with lot of advantages like,
 How to store a value for that variable
 What are all the different operations possible on that data
 What amount of memory is required to store that data
All these things taken care by the compiler or the run time system manager.
Abstract Data type
• When an application requires special kind of data which is not available as a
built-in data type, then it is programmer’s responsibility to implement his own
kind of data.
• Here the programmer must decide all these following things and must
implement them.
 How to store a value for that variable
 What are all the different operations possible on that data
 What amount of memory is required to store that data
Abstract data type is termed as User-defined data.
Concept of Data Structures:
 A digital computer can manipulate only primitive data, that is, data in terms of 0’s
and 1’s.
 But in our real-life applications, various kinds of data other than the primitive data
are involved.
 Manipulation of these real-life data (Or User defined data) requires the following
essential tasks:
 Storage representation of data: User data should be stored in such a way
that computer can understand it.
 Retrieval of stored data: Data stored in computer should be retrieved in
such a way that the user can understand it.
 Transformation of User data: Various operations which require to be
performed on user data so that it can be transformed from one form to
another.
Overview of Data Structures
What is an Algorithm? Algorithm
Basics
 Implementation of Data Structures need algorithms.
 The word Algorithm means ” A set of finite rules or instructions to be
followed in calculations or other problem-solving operations ” .
 Therefore Algorithm refers to a sequence of finite steps to solve a particular
problem.
 Algorithms can be simple and complex depending on what you want to
 It can be understood by taking the example of cooking a new recipe: To cook a
new recipe, one reads the instructions and steps and executes them one by
one, in the given sequence.
 The result thus obtained is the new dish cooked perfectly.
 The Algorithm designed are language-independent, i.e. they are just plain
instructions that can be implemented in any language, and yet the output will
be the same, as expected.
What are the Characteristics of an Algorithm?
As one would not follow any written instructions to cook the recipe, but only the
standard one. Similarly, not all written instructions for programming is an
algorithms. In order for some instructions to be an algorithm, it must have the
following characteristics:
•Clear and Unambiguous: The algorithm should be clear and unambiguous.
Each of its steps should be clear in all aspects and must lead to only one
meaning.
•Well-Defined Inputs: If an algorithm says to take inputs, it should be well-
defined inputs. It may or may not take input.
•Well-Defined Outputs: The algorithm must clearly define what output will be
yielded and it should be well-defined as well. It should take at least 1 output.
•Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite
time.
•Feasible: The algorithm must be simple, generic, and practical, such that it can
be executed with the available resources. It must not contain some future
technology or anything.
•Language Independent: The Algorithm designed must be language-
independent, i.e. it must be just plain instructions that can be implemented in
Properties of Algorithm:
•It should terminate after a finite time.
•It should produce at least one output.
•It should take zero or more input.
•It should be deterministic means giving the same output for the same input
case.
•Every step in the algorithm must be effective i.e. every step should do some
Advantages of Algorithms:
•It is easy to understand.
•An algorithm is a step-wise representation of a solution to a given problem.
•In Algorithm the problem is broken down into smaller pieces or steps hence, it is
easier for the programmer to convert it into an actual program.
Disadvantages of Algorithms:
•Writing an algorithm takes a long time so it is time-consuming.
•Understanding complex logic through algorithms can be very difficult.
•Branching and Looping statements are difficult to show in Algorithms(imp).
How to Design an Algorithm?
In order to write an algorithm, the following things are needed as a pre-requisite:
1.The problem that is to be solved by this algorithm i.e. clear problem definition.
2.The constraints of the problem must be considered while solving the problem.
3.The input to be taken to solve the problem.
4.The output to be expected when the problem is solved.
5.The solution to this problem, is within the given constraints.
Then the algorithm is written with the help of the above parameters such that it
solves the problem.
Example: Consider the example to add three numbers and print the sum.
Step 1: Fulfilling the pre-requisites
As discussed above, in order to write an algorithm, its pre-requisites must be
fulfilled.
• The problem that is to be solved by this algorithm: Add 3 numbers and
print their sum.
• The constraints of the problem that must be considered while solving
the problem: The numbers must contain only digits and no other characters.
• The input to be taken to solve the problem: The three numbers to be
added.
• The output to be expected when the problem is solved: The sum of the
three numbers taken as the input i.e. a single integer value.
• The solution to this problem, in the given constraints: The solution
Step 2: Designing the algorithm
Now let’s design the algorithm with the help of the above pre-requisites:
Algorithm to add 3 numbers and print their sum:
• START
• Declare 3 integer variables num1, num2 and num3.
• Take the three numbers, to be added, as inputs in variables num1, num2,
and num3 respectively.
• Declare an integer variable sum to store the resultant sum of the 3 numbers.
• Add the 3 numbers and store the result in the variable sum.
• Print the value of the variable sum
• END
Step 3: Testing the algorithm by implementing it.
In order to test the algorithm, let’s implement it in C language.
// C++ program to add three numbers
// with the help of above designed
// algorithm
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Variables to take the input of
// the 3 numbers
int num1, num2, num3;
// Variable to store the resultant sum
int sum;
// Take the 3 numbers as input
cout << "Enter the 1st number: " ;
cin >> num1;
cout << " " << num1 << endl;
cout << "Enter the 2nd number: ";
cin >> num2;
cout << " " << num2 << endl;
cout << "Enter the 3rd number: ";
cin >> num3;
cout << " " << num3;
// Calculate the sum using + operator
// and store it in variable sum
sum = num1 + num2 + num3;
// Print the sum
cout << "nSum of the 3 numbers is: " << sum;
return 0;
}
Python3 program to add three numbers
# with the help of above designed
# algorithm
if __name__ == "__main__":
# Variables to take the input of
# the 3 numbers
num1 = num2 = num3 = 0
# Variable to store the resultant sum
sum = 0
# Take the 3 numbers as input
num1 = int(input("Enter the 1st number: "))
num2 = int(input("Enter the 2nd number: "))
num3 = int(input("Enter the 3rd number: "))
# Calculate the sum using + operator
# and store it in variable sum
sum = num1 + num2 + num3
# Print the sum
print("nSum of the 3 numbers is:", sum)
Output
Enter the 1st number: 0
Enter the 2nd number: 0
Enter the 3rd number: -1577141152
Sum of the 3 numbers is: -1577141152
What is meant by Algorithm Analysis?
Algorithm analysis is an important part of computational complexity theory,
which provides theoretical estimation for the required resources of an
algorithm to solve a specific computational problem.
Analysis of algorithms is the determination of the amount of time and space
resources required to execute it.
 In the analysis of the algorithm, it generally focused on CPU (time) usage,
Memory usage, Disk usage, and Network usage.
 All are important, but the most concern is about the CPU time. Be careful to
differentiate between:
Performance: How much time/memory/disk/etc. is used when a program is
run. This depends on the machine, compiler, etc. as well as the code we write.
Complexity: How do the resource requirements of a program or algorithm
scale, i.e. what happens as the size of the problem being solved by the code
gets larger.
Why Analysis of Algorithms is important?
 To predict the behaviour of an algorithm without implementing it on a specific
computer.
 It is much more convenient to have simple measures for the efficiency of an
algorithm than to implement the algorithm and test the efficiency every time a
certain parameter in the underlying computer system changes.
 It is impossible to predict the exact behaviour of an algorithm. There are too
many influencing factors.
 The analysis is thus only an approximation; it is not perfect.
 More importantly, by analysing different algorithms, we can compare them to
determine the best one for our purpose.
How to analyze an Algorithm?
For a standard algorithm to be good, it must be efficient. Hence the efficiency of an
algorithm must be checked and maintained. It can be in two stages:
1.Priori Analysis:
 “Priori” means “before”. Hence Priori analysis means checking the algorithm
before its implementation.
 In this, the algorithm is checked when it is written in the form of theoretical
steps.
 This Efficiency of an algorithm is measured by assuming that all other factors,
for example, processor speed, are constant and have no effect on the
implementation.
 This is done usually by the algorithm designer.
2. Posterior Analysis:
“Posterior” means “after”. Hence Posterior analysis means checking the
algorithm after its implementation.
In this, the algorithm is checked by implementing it in any programming
language and executing it.
This analysis helps to get the actual and real analysis report about
correctness(for every possible input/s if it shows/returns correct output or not),
space required, time consumed etc.
That is, it is dependent on the language of the compiler and the type of
hardware used.
Types of Algorithm Analysis:
1.Best case
2.Worst case
3.Average case
•Best case:
Define the input for which algorithm takes less time or minimum time.
In the best case calculate the lower bound of an algorithm.
Example: In the linear search when search data is present at the first
location of large data then the best case occurs.
•Worst Case:
Define the input for which algorithm takes a long time or maximum time.
In the worst calculate the upper bound of an algorithm.
Example: In the linear search when search data is not present at all then the
worst case occurs.
•Average case:
In the average case take all random inputs and calculate the computation
time for all inputs.
And then we divide it by the total number of inputs.
Average case = all random case time / total no of case
Popular Notations in Complexity Analysis of Algorithms
1. Big-O Notation
 We define an algorithm’s worst-case time complexity by using the Big-O
notation.
 It explains the maximum amount of time an algorithm requires to consider
all input values.
2. Omega Notation
 It defines the best case of an algorithm’s time complexity
 It explains the minimum amount of time an algorithm requires to consider
all input values.
3. Theta Notation
 It defines the average case of an algorithm’s time complexity.
 Both O(expression) and Omega(expression), then Theta notation is
Arrays
Array Definition:
An array is a finite, ordered and collection of homogeneous data elements.
Finite : It contains only a limited number of elements.
Ordered : All the elements are stored one by one in contiguous locations
of the computer memory in a linear ordered fashion.
Homogeneous : All the elements in the array are of same data type.
Example : 1. An array of integers to store the age of all students in a class.
2. An array of strings (of characters) to store the names
of all villagers in a village.
If we want to store a group of data together in one place, then an array is the data
structure we should be looking for.
All the elements are stored in
contiguous locations of the memory.
Figure shows an array of data stored in
a memory block starting at location
5000.
Applications of Arrays in Real Life:
1. Arrangement of the leader-board of a game can be done simply through arrays to store the
score and arrange them in descending order to clearly make out the rank of each player in
the game.
2. A simple question Paper is an array of numbered questions with each of them assigned
some marks.
3. Your viewing screen is also a multidimensional array of pixels.
4. Book titles in a Library Management Systems.
5. Online ticket booking.
6. Contacts on a cell phone.
7. To store the possible moves of chess on a chessboard.
Terminology:
Size : The number of elements in an array.
Also called length or dimension.
Type : The kind of data type of elements.
Base : The base of an array is the address of the memory location
where the first element of the array is located.
Index : All the elements in the array can be referenced by
a subscript like Ai or A[i]. This subscript is known as index.
Range of indices : Indices of Array may range from lower bound to Upper bound, and
theses bounds are called the boundaries of an array.
Word : Word denotes the size of an element. In each memory location, a
computer can store an element of word size w. This word size
varies from 1 byte to 8 bytes.
Arrays
One-Dimensional
Arrays Multidimensional Arrays
Two-Dimensional
Arrays
Sparse Matrices
Three-dimensional(3D)
Arrays
One- Dimensional Array:
If only one subscript/index is required to reference all the elements in an array, then the array
is termed as one-dimensional array or simply an array.
M 1
2
3
100
.
.
.
An array A[100] is to be stored in a memory
as in Figure. Let the memory location where
the first element stored be M.
Operations on Arrays:
Traversing : To visit all elements in an array.
Sorting : To sort in a specified order (ascending/descending)
Searching : To search an element of interest in an array.
Insertion : To insert an element into an array provided that the array is not full.
Deletion : To delete a particular element from an array.
Merging : Merging is important when we need to compact the elements from two
different arrays into a single array.
Application of Arrays:
If we want to store records of all students in a class. It can be done by using 6 arrays.
STUDENTS
ROLL NO. MARK1 MARK2 MARK3 TOTAL GRADE
Alphanumeric Numeric Numeric Numeric Numeric Character
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Multidimensional Arrays
Two-Dimensional Arrays:
 They are (alternatively termed us matrices) a collection of homogeneous elements where
the elements are ordered in a number of rows and columns.
 An example of an mxn matrix, where m denotes the number of rows and n denotes the
number of columns, is as follows:
a11 a12 a13 a14 ……………. a1n
a21 a22 a23 a24 ……………. a2n
. . . . .
. . . . .
. . . . .
am1 am2 am3 am4 ……………. amn
Let us now suppose that we wish to express the information of possession of pens and pencils by Ram
and his two friends Rohan and Yash which is as follows:
Ram has 20 pens and 7 pencils,
Rohan has 15 pens and 5 pencils,
Yash has 12 pens and 3 pencils.
Now, this could be arranged in tabular form as follows,
Pens Pencils
Ram 20 7
Rohan 15 5
Yash 12 3
Example of Matrix
and this can be expressed as,
In the above arrangement,
 The entries in the first column represent the number of pens possessed by Ram, Rohan, and Yash
 The entries in the second column represents the number of pencils possessed by Ram, Rohan, and
Yash, respectively.
Sparse Matrices:
A sparse matrix is a two-
dimensional array where
most of the elements have
the value null.
Why to use Sparse Matrix instead of simple matrix ?
 Storage: There are lesser non-zero elements than zeros and thus lesser memory can
be used to store only those elements.
 Computing time: Computing time can be saved by logically designing a data structure
traversing only non-zero elements..
Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the
matrix are of no use in most of the cases.
So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This
means storing non-zero elements with triples- (Row, Column, value).
Sparse Matrix Representations can be done in many ways following are two common
representations:
1.Array representation
2.Linked list representation
Method 1: Using Arrays:
2D array is used to represent a sparse matrix in which there are three rows named as
 Row: Index of row, where non-zero element is located
 Column: Index of column, where non-zero element is located
 Value: Value of the non zero element located at index – (row, column)
0 4
2 3
1
0
1
2
3
Method 2: Using Linked Lists
In linked list, each node has four fields. These four fields are defined as:
 Row : Index of row, where non-zero element is located
 Column : Index of column, where non-zero element is located
 Value : Value of the non zero element located at index – (row,column)
 Next node : Address of the next node
0
1
2
3
0 1 2 3 4
Stack
It is a linear data structure that follows a particular order in which the operations are performed.
LIFO( Last In First Out ):
This strategy states that the element that is inserted last will come out first.
Examples:
 Plates on a tray.
 Shunting of trains in a railway yard.
 Shipment in a cargo.
Application of Stacks in Real Life:
1. Converting infix to postfix expressions.
2. Undo/Redo button/operation in word processors.
3. Syntaxes in languages are parsed using stacks.
4. It is used in many virtual machines like JVM.
5. Forward-backward surfing in the browser.
6. History of visited websites.
7. Message logs and all messages you get are arranged in a stack.
8. Call logs, E-mails, Google photos’ any gallery, YouTube downloads, Notifications ( latest appears
first ).
1. Scratch card’s earned after Google pay transaction.
2. Wearing/Removing Bangles, Pile of Dinner Plates, Stacked chairs.
3. Changing wearables on a cold evening, first in, comes out at last.
4. Last Hired, First Fired-which is typically utilized when a company reduces its workforce in an
economic recession.
5. Loading bullets into the magazine of a gun. The last one to go in is fired first. Bam!
6. Media playlist. T o play previous and next song
Basic Operations on Stack
In order to make
manipulations in a stack, there
are certain operations
provided to us.
 push() to insert an
element into the stack
 pop() to remove an
element from the stack
 top() Returns the top
element of the stack.
 isEmpty() returns true is
stack is empty else false.
 size() returns the size of
stack.
Push:
Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition.
Algorithm for push:
Begin
if stack is full
return
endif
else
increment top
stack[top] assign value
end else
end procedure
Pop:
Removes an item from the stack. The items are popped in the reversed order in which they are
pushed. If the stack is empty, then it is said to be an Underflow condition.
Algorithm for pop:
Begin
if stack is empty
return
endif
else
store value of stack[top]
decrement top
return value
end else
end procedure
Top:
Returns the top element of the stack.
Algorithm for Top:
begin
return stack[top]
end procedure
isEmpty:
Returns true if the stack is empty, else false.
Algorithm for isEmpty:
begin
if top < 1
return true
else
return false
end procedure
What is an Expression?
An expression is a set of numbers or variables combined using the operations A+B, A-B, A*B, A/B.
Infix expression: The expression of the form (a + b). When an operator is in-between every pair of
operands.
Postfix expression: The expression of the form (ab+). When an operands is followed by every pair of
operators.
Prefix expression: The expression of the form (+ab). When an operator is followed by every pair of
operands.
Application of Stack
Examples:
Input: A + B * C + D Input: ((A + B) – C * (D / E)) + F
Output: ABC*+D+ Output: AB+CDE/*-F+
Why postfix representation of the expression?
1. The compiler scans the expression either from left to right or from right to left.
Consider the expression: a + b * c + d
2. The compiler first scans the expression to evaluate the expression b * c, then
again scans the expression to add a to it.
3. The result is then added to d after another scan.
4. The repeated scanning makes it very inefficient and Infix expressions are easily
readable and solvable by humans whereas the computer cannot differentiate
the operators and parenthesis easily so, it is better to convert the expression to
postfix(or prefix) form before evaluation.
5. The corresponding expression in postfix form is abc*+d+.
6. The postfix expressions can be evaluated easily using a stack.
Infix to Postfix Conversion Using Stack:
Operands: A, B, X, Y, P, Q……………
Operators: +, -, /, *, (, ),…………….
Infix : A + B
Postfix : AB+
Prefix :+ AB
Rules:
1. Priorities of Operators:
^ :Highest Priority
*, / :Next and same priority
+, - :Lowest and same priority
2) No two operators of same priority can
stay together in a stack column.
3) Lowest priority cannot be placed
before highest priority.
4) Any operator (+) : pop that element
Operand : postfix
Operator: Stack
Example: Convert this Infix expression into Postfix expression. (A+B/C*(D+E)-F)
SYMBOL STACK POSTFIX
Convert the following Infix into
postfix form:
1. A + B * C + D
2. (A + B) * (C + D)
3. A * B + C * D
4. A + B + C + D
SYMBO
L
STACK POSTFIX
SYMBOL STACK POSTFIX
Evaluation of Postfix Expression:
Postfix : 5, 6, 2, +, *, 12, 4, /, -
Symbol Scanned Stack
1) 10 22 + 8 / 6 * 5 +
2) 2 3 * 4 5 + *
3) 2 3 1 * + 9 –
4) 100 200 + 2 / 5 * 7 +
Evaluate the following Postfix expressions:
What is Queue?
o A queue is defined as a linear data structure that is open at both ends and the operations are
performed in First In First Out (FIFO) order.
o We define a queue to be a list in which all additions to the list are made at one end, and all deletions
from the list are made at the other end.
o The element which is first pushed into the order, the operation is first performed on that.
FIFO Principle of Queue:
 A Queue is like a line waiting to purchase tickets, where the first person in line is the first person
served. (i.e. First come first serve).
 Position of the entry in a queue ready to be served, that is,
 the first entry that will be removed from the queue, is called the front of the
queue(sometimes,head of the queue),
 similarly, the position of the last entry in the queue, that is, the one most recently added,
is called the rear (or the tail) of the queue. See the below figure.
Characteristics of Queue:
 Queue can handle multiple data.
 We can access both ends.
 They are fast and flexible.
Queue Representation:
Like stacks, Queues can also be represented in an array: In this representation, the Queue
is implemented using the array. Variables used in this case are
 Queue: the name of the array storing queue elements.
 Front: the index where the first element is stored in the array representing the queue.
 Rear: the index where the last element is stored in an array representing the queue.
Types of Queue
There are four different types of
queue that are listed as follows
-
 Simple Queue or Linear Queue
 Circular Queue
 Priority Queue
 Double Ended Queue (or Deque)
Simple Queue or Linear Queue
 In Linear Queue, an insertion takes place from one end while the deletion
occurs from another end.
 The end at which the insertion takes place is known as the rear end, and the
end at which the deletion takes place is known as front end.
 It strictly follows the FIFO rule.
Circular Queue
 In Circular Queue, all the nodes are represented as circular.
 It is similar to the linear Queue except that the last element of the queue is connected to the first
element.
 It is also known as Ring Buffer, as all the ends are connected to another end.
 The representation of circular queue is shown in the above image.
Application of circular queue: Insertion of days in a week.
Priority Queue
 It is a special type of queue in
which the elements are
arranged based on the priority.
 It is a special type of queue
data structure in which every
element has a priority
associated with it.
 Suppose some elements occur
with the same priority, they will
be arranged according to the
FIFO principle.
 The representation of priority
queue is shown in the image.
There are two types of priority queue that are discussed as follows -
•Ascending priority queue - In ascending priority queue, elements can be inserted
in arbitrary order, but only smallest can be deleted first. Suppose an array with
elements 7, 5, and 3 in the same order, so, insertion can be done with the same
sequence, but the order of deleting the elements is 3, 5, 7.
•Descending priority queue - In descending priority queue, elements can be
inserted in arbitrary order, but only the largest element can be deleted first. Suppose
an array with elements 7, 3, and 5 in the same order, so, insertion can be done with
the same sequence, but the order of deleting the elements is 7, 5, 3.
Deque (or, Double Ended Queue)
 In Deque or Double Ended Queue, insertion and deletion can be done from both ends of the
queue either from the front or rear.
 It means that we can insert and delete elements from both front and rear ends of the queue.
 Deque can be used as a palindrome checker means that if we read the string from both ends,
then the string would be the same.
Input restricted deque -
As the name implies, in input restricted queue, insertion operation can be performed at only one end,
while deletion can be performed from both ends.
Output restricted deque -
As the name implies, in output restricted queue, deletion operation can be performed at only one
end, while insertion can be performed from both ends.
Different operations in Queue Data Structure:
The various operations that are supported by a queue data structure that helps the
user to modify and manipulate the data present in the queue are:
 Enqueue operation: The term "enqueue" refers to the act of adding a new element
to a queue. Where does a new individual go and wait in a standard queue at a
ticket counter to join the queue? The individual walks to the back of the room and
takes a seat. A new element in a queue is similarly added at the end of the queue.
 Dequeue operation: Dequeue is the process of deleting an item from a queue. We
must delete the queue member that was put first since the queue follows the FIFO
principle. We'll delete the front element and make the element behind it the new
front element because the element added initially will naturally be at the head of the
queue.
 Front Operation: This works similarly to the peek operation in stacks in that it
returns the value of the first element without deleting it.
 isEmpty Operation: The isEmpty() function is used to check if the Queue is empty
or not.
Enqueue Operation
Below are the steps to enqueue (insert) data into
a queue
• Check whether the queue is full or not.
• If the queue is full – print the overflow
error and exit the program.
• If the queue is not full – increment the rear
pointer to point to the next empty space.
• Else add the element in the position
pointed by Rear.
• Return success.
Algorithm for Enqueue Operation
procedure enqueuer (data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
Dequeue Operation
Below are the steps to perform dequeue operation
 Check whether the queue is full or not.
 If the queue is empty – print the underflow
error and exit the program.
 If the queue is not empty – access the data
where the front is pointing.
 Else increment the front pointer to point to
the next available data element.
 Return success.
Algorithm for Dequeue Operation
procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front ← front + 1
return true
end procedure
Application of Queue in Data Structure
A queue data structure is generally used in scenarios where the FIFO approach
(First In First Out) has to be implemented.
The following are some of the most common applications of the queue in data
structure:
 Managing requests on a single shared resource such as CPU scheduling
and disk scheduling
 Handling hardware or real-time systems interrupts
 Handling website traffic
 Routers and switches in networking
 Maintaining the playlist in media players
Data Structure - Multiple Stack
A single stack is sometimes not sufficient to store a large amount of data.
To overcome this problem, we can use multiple stack.
For this, we have used a single array having more than one stack.
The array is divided for multiple stacks.
Suppose there is an array STACK[n] divided into two stack STACK
A and STACK B, where n = 10.
STACK A expands from the left to the right, i.e., from 0th element.
STACK B expands from the right to the left, i.e., from 10th element.
The combined size of both STACK A and STACK B never exceeds 10.
End of Unit 1

More Related Content

Similar to Unit 1 Introduction Part 3.pptx

Introduction to Data Structure and algorithm.pptx
Introduction to Data Structure and algorithm.pptxIntroduction to Data Structure and algorithm.pptx
Introduction to Data Structure and algorithm.pptxesuEthopi
 
Chapter 1 Data structure.pptx
Chapter 1 Data structure.pptxChapter 1 Data structure.pptx
Chapter 1 Data structure.pptxwondmhunegn
 
Program concep sequential statements
Program concep sequential statementsProgram concep sequential statements
Program concep sequential statementsankurkhanna
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing TechniquesAppili Vamsi Krishna
 
Unit 1 python (2021 r)
Unit 1 python (2021 r)Unit 1 python (2021 r)
Unit 1 python (2021 r)praveena p
 
Algorithm Analysis.pdf
Algorithm Analysis.pdfAlgorithm Analysis.pdf
Algorithm Analysis.pdfNayanChandak1
 
Algorithms and Data Structures
Algorithms and Data StructuresAlgorithms and Data Structures
Algorithms and Data Structuressonykhan3
 
Data Structures and Algorithms Unit 01
Data Structures and Algorithms Unit 01Data Structures and Algorithms Unit 01
Data Structures and Algorithms Unit 01Prashanth Shivakumar
 
Intro to Data Structure & Algorithms
Intro to Data Structure & AlgorithmsIntro to Data Structure & Algorithms
Intro to Data Structure & AlgorithmsAkhil Kaushik
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDeepikaV81
 
Unit 1, ADA.pptx
Unit 1, ADA.pptxUnit 1, ADA.pptx
Unit 1, ADA.pptxjinkhatima
 
ALGO VS FLOW.pptx
ALGO VS FLOW.pptxALGO VS FLOW.pptx
ALGO VS FLOW.pptxNagendraK18
 
Introduction to Data Structure & algorithm
Introduction to Data Structure & algorithmIntroduction to Data Structure & algorithm
Introduction to Data Structure & algorithmSunita Bhosale
 

Similar to Unit 1 Introduction Part 3.pptx (20)

RAJAT PROJECT.pptx
RAJAT PROJECT.pptxRAJAT PROJECT.pptx
RAJAT PROJECT.pptx
 
Introduction to Data Structure and algorithm.pptx
Introduction to Data Structure and algorithm.pptxIntroduction to Data Structure and algorithm.pptx
Introduction to Data Structure and algorithm.pptx
 
Chapter 1 Data structure.pptx
Chapter 1 Data structure.pptxChapter 1 Data structure.pptx
Chapter 1 Data structure.pptx
 
Program concep sequential statements
Program concep sequential statementsProgram concep sequential statements
Program concep sequential statements
 
8.unit-1-fds-2022-23.pptx
8.unit-1-fds-2022-23.pptx8.unit-1-fds-2022-23.pptx
8.unit-1-fds-2022-23.pptx
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing Techniques
 
Unit 1 python (2021 r)
Unit 1 python (2021 r)Unit 1 python (2021 r)
Unit 1 python (2021 r)
 
Module 1 python.pptx
Module 1 python.pptxModule 1 python.pptx
Module 1 python.pptx
 
Algorithm Analysis.pdf
Algorithm Analysis.pdfAlgorithm Analysis.pdf
Algorithm Analysis.pdf
 
Algorithms and Data Structures
Algorithms and Data StructuresAlgorithms and Data Structures
Algorithms and Data Structures
 
Data Structures and Algorithms Unit 01
Data Structures and Algorithms Unit 01Data Structures and Algorithms Unit 01
Data Structures and Algorithms Unit 01
 
Intro to Data Structure & Algorithms
Intro to Data Structure & AlgorithmsIntro to Data Structure & Algorithms
Intro to Data Structure & Algorithms
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Unit 1, ADA.pptx
Unit 1, ADA.pptxUnit 1, ADA.pptx
Unit 1, ADA.pptx
 
ALGO VS FLOW.pptx
ALGO VS FLOW.pptxALGO VS FLOW.pptx
ALGO VS FLOW.pptx
 
Lecture 1 and 2
Lecture 1 and 2Lecture 1 and 2
Lecture 1 and 2
 
Introduction to Data Structure & algorithm
Introduction to Data Structure & algorithmIntroduction to Data Structure & algorithm
Introduction to Data Structure & algorithm
 
Lec1
Lec1Lec1
Lec1
 
Lec1
Lec1Lec1
Lec1
 
C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
 

Recently uploaded

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Recently uploaded (20)

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

Unit 1 Introduction Part 3.pptx

  • 1. Data Structures Unit 1 Introduction Mrs. Nisha Robin Rohit Assistant Professor AMET
  • 2. Before studying about Data Structures, we should make ourselves aware of the various terms used in the subject.  Data  Entity  Information  Data type  Built-in data type  Abstract data type
  • 3. Data The term data means value or set of values. Example of data: a) 34 b) 12/01/1980 c) ISBN 81-203-0000-0 d) ||| e) Pascal f) 21,25,28,56,90
  • 4. Entity  An entity is one that has certain attributes, and which may be assigned values.  For example, an employee in an organization is an entity.  The possible attributes and their corresponding values for an entity in the present example are: Entity : EMPLOYEE Attributes: NAME DOB SEX DESIGNATION Values : RAVI ANAND 30/12/92 M DIRECTOR  All of the employees in an organization constitute an entity set.  Each attribute of an entity set has a range of values, and this range is called the domain of the attribute.  For example, in EMPLOYEE entity, the attribute SEX has the domain {M,F}.
  • 5. Entity (ANOTHER EXAMPLE) Entity : HUMAN Attributes: SEX SKIN COLOUR EYE COLOUR Values : M/F DARK/FAIR BLACK/BLUE/BROWN  Each attribute of an entity set has a range of values, and this range is called the domain of the attribute.  For example, in HUMAN entity, the attribute SKIN COLOUR has the domain {DARK,FAIR,WHEATISH}.
  • 6. Information  The term information is used for data with its attributes.  In other words, information can be meaningful data or processed data. Data Meaning 34 Age of the person 12/01/1980 Date of Birth of a person ISBN 81-203-0000-0 Book number, recently published by the person ||| Number of awards equal to the tally marks achieved by the person Pascal Nickname of the person 21,25,28,56,90 Important ages of the person
  • 7. Difference between data and information Data Procedure to process data Information 1 Information 2 . . . Information I . . Information n As an example, suppose there is a set of data consisting of the amount of milk consumed by a person in a month. From this given set of data, information can be retrieved as follows: What was the total amount of milk consumed in a month? On which day was the maximum amount of milk consumed? On which day was the minimum amount of milk consumed? What was the average amount of milk consumption per day?
  • 8. Data Type A data type is a term refers to the kind of data that may appear in a computation. The following are few well known data types. Data Data type 34 Numeric(integer) 12/01/1980 Date ISBN 81-203-0000-0 Alphanumeric ||| Graphics Pascal String 21,25,28,56,90 Array of Integers Real, Boolean, character, complex, etc. are some more frequently used data types.
  • 9. Built-in Data Type In every programming language, there is a set of data types called built-in data types. For example, in C, Java and Python the data types that are available as built- in are listed below: Programming Language Built-in Data types C int, float, char, double, Enum, etc. Java integer, string, time Python numeric, sequence, set, binary, string, etc.
  • 10. Built-in data type provide users with lot of advantages like,  How to store a value for that variable  What are all the different operations possible on that data  What amount of memory is required to store that data All these things taken care by the compiler or the run time system manager.
  • 11. Abstract Data type • When an application requires special kind of data which is not available as a built-in data type, then it is programmer’s responsibility to implement his own kind of data. • Here the programmer must decide all these following things and must implement them.  How to store a value for that variable  What are all the different operations possible on that data  What amount of memory is required to store that data Abstract data type is termed as User-defined data.
  • 12. Concept of Data Structures:  A digital computer can manipulate only primitive data, that is, data in terms of 0’s and 1’s.  But in our real-life applications, various kinds of data other than the primitive data are involved.  Manipulation of these real-life data (Or User defined data) requires the following essential tasks:  Storage representation of data: User data should be stored in such a way that computer can understand it.  Retrieval of stored data: Data stored in computer should be retrieved in such a way that the user can understand it.  Transformation of User data: Various operations which require to be performed on user data so that it can be transformed from one form to another.
  • 13. Overview of Data Structures
  • 14.
  • 15.
  • 16. What is an Algorithm? Algorithm Basics  Implementation of Data Structures need algorithms.  The word Algorithm means ” A set of finite rules or instructions to be followed in calculations or other problem-solving operations ” .  Therefore Algorithm refers to a sequence of finite steps to solve a particular problem.  Algorithms can be simple and complex depending on what you want to
  • 17.
  • 18.  It can be understood by taking the example of cooking a new recipe: To cook a new recipe, one reads the instructions and steps and executes them one by one, in the given sequence.  The result thus obtained is the new dish cooked perfectly.  The Algorithm designed are language-independent, i.e. they are just plain instructions that can be implemented in any language, and yet the output will be the same, as expected.
  • 19. What are the Characteristics of an Algorithm?
  • 20. As one would not follow any written instructions to cook the recipe, but only the standard one. Similarly, not all written instructions for programming is an algorithms. In order for some instructions to be an algorithm, it must have the following characteristics: •Clear and Unambiguous: The algorithm should be clear and unambiguous. Each of its steps should be clear in all aspects and must lead to only one meaning. •Well-Defined Inputs: If an algorithm says to take inputs, it should be well- defined inputs. It may or may not take input. •Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it should be well-defined as well. It should take at least 1 output.
  • 21. •Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time. •Feasible: The algorithm must be simple, generic, and practical, such that it can be executed with the available resources. It must not contain some future technology or anything. •Language Independent: The Algorithm designed must be language- independent, i.e. it must be just plain instructions that can be implemented in
  • 22. Properties of Algorithm: •It should terminate after a finite time. •It should produce at least one output. •It should take zero or more input. •It should be deterministic means giving the same output for the same input case. •Every step in the algorithm must be effective i.e. every step should do some
  • 23. Advantages of Algorithms: •It is easy to understand. •An algorithm is a step-wise representation of a solution to a given problem. •In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the programmer to convert it into an actual program. Disadvantages of Algorithms: •Writing an algorithm takes a long time so it is time-consuming. •Understanding complex logic through algorithms can be very difficult. •Branching and Looping statements are difficult to show in Algorithms(imp).
  • 24. How to Design an Algorithm? In order to write an algorithm, the following things are needed as a pre-requisite: 1.The problem that is to be solved by this algorithm i.e. clear problem definition. 2.The constraints of the problem must be considered while solving the problem. 3.The input to be taken to solve the problem. 4.The output to be expected when the problem is solved. 5.The solution to this problem, is within the given constraints. Then the algorithm is written with the help of the above parameters such that it solves the problem. Example: Consider the example to add three numbers and print the sum.
  • 25. Step 1: Fulfilling the pre-requisites As discussed above, in order to write an algorithm, its pre-requisites must be fulfilled. • The problem that is to be solved by this algorithm: Add 3 numbers and print their sum. • The constraints of the problem that must be considered while solving the problem: The numbers must contain only digits and no other characters. • The input to be taken to solve the problem: The three numbers to be added. • The output to be expected when the problem is solved: The sum of the three numbers taken as the input i.e. a single integer value. • The solution to this problem, in the given constraints: The solution
  • 26. Step 2: Designing the algorithm Now let’s design the algorithm with the help of the above pre-requisites: Algorithm to add 3 numbers and print their sum: • START • Declare 3 integer variables num1, num2 and num3. • Take the three numbers, to be added, as inputs in variables num1, num2, and num3 respectively. • Declare an integer variable sum to store the resultant sum of the 3 numbers. • Add the 3 numbers and store the result in the variable sum. • Print the value of the variable sum • END
  • 27. Step 3: Testing the algorithm by implementing it. In order to test the algorithm, let’s implement it in C language. // C++ program to add three numbers // with the help of above designed // algorithm #include <bits/stdc++.h> using namespace std; int main() { // Variables to take the input of // the 3 numbers int num1, num2, num3;
  • 28. // Variable to store the resultant sum int sum; // Take the 3 numbers as input cout << "Enter the 1st number: " ; cin >> num1; cout << " " << num1 << endl; cout << "Enter the 2nd number: "; cin >> num2; cout << " " << num2 << endl; cout << "Enter the 3rd number: "; cin >> num3; cout << " " << num3;
  • 29. // Calculate the sum using + operator // and store it in variable sum sum = num1 + num2 + num3; // Print the sum cout << "nSum of the 3 numbers is: " << sum; return 0; }
  • 30. Python3 program to add three numbers # with the help of above designed # algorithm if __name__ == "__main__": # Variables to take the input of # the 3 numbers num1 = num2 = num3 = 0 # Variable to store the resultant sum sum = 0
  • 31. # Take the 3 numbers as input num1 = int(input("Enter the 1st number: ")) num2 = int(input("Enter the 2nd number: ")) num3 = int(input("Enter the 3rd number: ")) # Calculate the sum using + operator # and store it in variable sum sum = num1 + num2 + num3 # Print the sum print("nSum of the 3 numbers is:", sum) Output Enter the 1st number: 0 Enter the 2nd number: 0 Enter the 3rd number: -1577141152 Sum of the 3 numbers is: -1577141152
  • 32. What is meant by Algorithm Analysis? Algorithm analysis is an important part of computational complexity theory, which provides theoretical estimation for the required resources of an algorithm to solve a specific computational problem. Analysis of algorithms is the determination of the amount of time and space resources required to execute it.
  • 33.  In the analysis of the algorithm, it generally focused on CPU (time) usage, Memory usage, Disk usage, and Network usage.  All are important, but the most concern is about the CPU time. Be careful to differentiate between: Performance: How much time/memory/disk/etc. is used when a program is run. This depends on the machine, compiler, etc. as well as the code we write. Complexity: How do the resource requirements of a program or algorithm scale, i.e. what happens as the size of the problem being solved by the code gets larger.
  • 34. Why Analysis of Algorithms is important?  To predict the behaviour of an algorithm without implementing it on a specific computer.  It is much more convenient to have simple measures for the efficiency of an algorithm than to implement the algorithm and test the efficiency every time a certain parameter in the underlying computer system changes.  It is impossible to predict the exact behaviour of an algorithm. There are too many influencing factors.  The analysis is thus only an approximation; it is not perfect.  More importantly, by analysing different algorithms, we can compare them to determine the best one for our purpose.
  • 35. How to analyze an Algorithm? For a standard algorithm to be good, it must be efficient. Hence the efficiency of an algorithm must be checked and maintained. It can be in two stages: 1.Priori Analysis:  “Priori” means “before”. Hence Priori analysis means checking the algorithm before its implementation.  In this, the algorithm is checked when it is written in the form of theoretical steps.  This Efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation.  This is done usually by the algorithm designer.
  • 36. 2. Posterior Analysis: “Posterior” means “after”. Hence Posterior analysis means checking the algorithm after its implementation. In this, the algorithm is checked by implementing it in any programming language and executing it. This analysis helps to get the actual and real analysis report about correctness(for every possible input/s if it shows/returns correct output or not), space required, time consumed etc. That is, it is dependent on the language of the compiler and the type of hardware used.
  • 37. Types of Algorithm Analysis: 1.Best case 2.Worst case 3.Average case •Best case: Define the input for which algorithm takes less time or minimum time. In the best case calculate the lower bound of an algorithm. Example: In the linear search when search data is present at the first location of large data then the best case occurs.
  • 38. •Worst Case: Define the input for which algorithm takes a long time or maximum time. In the worst calculate the upper bound of an algorithm. Example: In the linear search when search data is not present at all then the worst case occurs. •Average case: In the average case take all random inputs and calculate the computation time for all inputs. And then we divide it by the total number of inputs. Average case = all random case time / total no of case
  • 39. Popular Notations in Complexity Analysis of Algorithms 1. Big-O Notation  We define an algorithm’s worst-case time complexity by using the Big-O notation.  It explains the maximum amount of time an algorithm requires to consider all input values.
  • 40. 2. Omega Notation  It defines the best case of an algorithm’s time complexity  It explains the minimum amount of time an algorithm requires to consider all input values. 3. Theta Notation  It defines the average case of an algorithm’s time complexity.  Both O(expression) and Omega(expression), then Theta notation is
  • 42. Array Definition: An array is a finite, ordered and collection of homogeneous data elements. Finite : It contains only a limited number of elements. Ordered : All the elements are stored one by one in contiguous locations of the computer memory in a linear ordered fashion. Homogeneous : All the elements in the array are of same data type. Example : 1. An array of integers to store the age of all students in a class. 2. An array of strings (of characters) to store the names of all villagers in a village.
  • 43. If we want to store a group of data together in one place, then an array is the data structure we should be looking for. All the elements are stored in contiguous locations of the memory. Figure shows an array of data stored in a memory block starting at location 5000.
  • 44. Applications of Arrays in Real Life: 1. Arrangement of the leader-board of a game can be done simply through arrays to store the score and arrange them in descending order to clearly make out the rank of each player in the game. 2. A simple question Paper is an array of numbered questions with each of them assigned some marks. 3. Your viewing screen is also a multidimensional array of pixels. 4. Book titles in a Library Management Systems. 5. Online ticket booking. 6. Contacts on a cell phone. 7. To store the possible moves of chess on a chessboard.
  • 45. Terminology: Size : The number of elements in an array. Also called length or dimension. Type : The kind of data type of elements. Base : The base of an array is the address of the memory location where the first element of the array is located. Index : All the elements in the array can be referenced by a subscript like Ai or A[i]. This subscript is known as index.
  • 46. Range of indices : Indices of Array may range from lower bound to Upper bound, and theses bounds are called the boundaries of an array. Word : Word denotes the size of an element. In each memory location, a computer can store an element of word size w. This word size varies from 1 byte to 8 bytes.
  • 48. One- Dimensional Array: If only one subscript/index is required to reference all the elements in an array, then the array is termed as one-dimensional array or simply an array. M 1 2 3 100 . . . An array A[100] is to be stored in a memory as in Figure. Let the memory location where the first element stored be M.
  • 49. Operations on Arrays: Traversing : To visit all elements in an array. Sorting : To sort in a specified order (ascending/descending) Searching : To search an element of interest in an array. Insertion : To insert an element into an array provided that the array is not full. Deletion : To delete a particular element from an array. Merging : Merging is important when we need to compact the elements from two different arrays into a single array.
  • 50. Application of Arrays: If we want to store records of all students in a class. It can be done by using 6 arrays. STUDENTS ROLL NO. MARK1 MARK2 MARK3 TOTAL GRADE Alphanumeric Numeric Numeric Numeric Numeric Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  • 51. Multidimensional Arrays Two-Dimensional Arrays:  They are (alternatively termed us matrices) a collection of homogeneous elements where the elements are ordered in a number of rows and columns.  An example of an mxn matrix, where m denotes the number of rows and n denotes the number of columns, is as follows: a11 a12 a13 a14 ……………. a1n a21 a22 a23 a24 ……………. a2n . . . . . . . . . . . . . . . am1 am2 am3 am4 ……………. amn
  • 52. Let us now suppose that we wish to express the information of possession of pens and pencils by Ram and his two friends Rohan and Yash which is as follows: Ram has 20 pens and 7 pencils, Rohan has 15 pens and 5 pencils, Yash has 12 pens and 3 pencils. Now, this could be arranged in tabular form as follows, Pens Pencils Ram 20 7 Rohan 15 5 Yash 12 3 Example of Matrix
  • 53. and this can be expressed as, In the above arrangement,  The entries in the first column represent the number of pens possessed by Ram, Rohan, and Yash  The entries in the second column represents the number of pencils possessed by Ram, Rohan, and Yash, respectively.
  • 54. Sparse Matrices: A sparse matrix is a two- dimensional array where most of the elements have the value null.
  • 55. Why to use Sparse Matrix instead of simple matrix ?  Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those elements.  Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero elements..
  • 56. Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means storing non-zero elements with triples- (Row, Column, value). Sparse Matrix Representations can be done in many ways following are two common representations: 1.Array representation 2.Linked list representation
  • 57. Method 1: Using Arrays: 2D array is used to represent a sparse matrix in which there are three rows named as  Row: Index of row, where non-zero element is located  Column: Index of column, where non-zero element is located  Value: Value of the non zero element located at index – (row, column)
  • 59. Method 2: Using Linked Lists In linked list, each node has four fields. These four fields are defined as:  Row : Index of row, where non-zero element is located  Column : Index of column, where non-zero element is located  Value : Value of the non zero element located at index – (row,column)  Next node : Address of the next node
  • 61. Stack It is a linear data structure that follows a particular order in which the operations are performed. LIFO( Last In First Out ): This strategy states that the element that is inserted last will come out first. Examples:  Plates on a tray.  Shunting of trains in a railway yard.  Shipment in a cargo.
  • 62. Application of Stacks in Real Life: 1. Converting infix to postfix expressions. 2. Undo/Redo button/operation in word processors. 3. Syntaxes in languages are parsed using stacks. 4. It is used in many virtual machines like JVM. 5. Forward-backward surfing in the browser. 6. History of visited websites. 7. Message logs and all messages you get are arranged in a stack. 8. Call logs, E-mails, Google photos’ any gallery, YouTube downloads, Notifications ( latest appears first ).
  • 63. 1. Scratch card’s earned after Google pay transaction. 2. Wearing/Removing Bangles, Pile of Dinner Plates, Stacked chairs. 3. Changing wearables on a cold evening, first in, comes out at last. 4. Last Hired, First Fired-which is typically utilized when a company reduces its workforce in an economic recession. 5. Loading bullets into the magazine of a gun. The last one to go in is fired first. Bam! 6. Media playlist. T o play previous and next song
  • 64. Basic Operations on Stack In order to make manipulations in a stack, there are certain operations provided to us.  push() to insert an element into the stack  pop() to remove an element from the stack  top() Returns the top element of the stack.  isEmpty() returns true is stack is empty else false.  size() returns the size of stack.
  • 65. Push: Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition. Algorithm for push: Begin if stack is full return endif else increment top stack[top] assign value end else end procedure
  • 66. Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition. Algorithm for pop: Begin if stack is empty return endif else store value of stack[top] decrement top return value end else end procedure
  • 67. Top: Returns the top element of the stack. Algorithm for Top: begin return stack[top] end procedure isEmpty: Returns true if the stack is empty, else false. Algorithm for isEmpty: begin if top < 1 return true else return false end procedure
  • 68. What is an Expression? An expression is a set of numbers or variables combined using the operations A+B, A-B, A*B, A/B. Infix expression: The expression of the form (a + b). When an operator is in-between every pair of operands. Postfix expression: The expression of the form (ab+). When an operands is followed by every pair of operators. Prefix expression: The expression of the form (+ab). When an operator is followed by every pair of operands. Application of Stack
  • 69. Examples: Input: A + B * C + D Input: ((A + B) – C * (D / E)) + F Output: ABC*+D+ Output: AB+CDE/*-F+ Why postfix representation of the expression? 1. The compiler scans the expression either from left to right or from right to left. Consider the expression: a + b * c + d 2. The compiler first scans the expression to evaluate the expression b * c, then again scans the expression to add a to it. 3. The result is then added to d after another scan.
  • 70. 4. The repeated scanning makes it very inefficient and Infix expressions are easily readable and solvable by humans whereas the computer cannot differentiate the operators and parenthesis easily so, it is better to convert the expression to postfix(or prefix) form before evaluation. 5. The corresponding expression in postfix form is abc*+d+. 6. The postfix expressions can be evaluated easily using a stack.
  • 71. Infix to Postfix Conversion Using Stack: Operands: A, B, X, Y, P, Q…………… Operators: +, -, /, *, (, ),……………. Infix : A + B Postfix : AB+ Prefix :+ AB Rules: 1. Priorities of Operators: ^ :Highest Priority *, / :Next and same priority +, - :Lowest and same priority 2) No two operators of same priority can stay together in a stack column. 3) Lowest priority cannot be placed before highest priority. 4) Any operator (+) : pop that element
  • 72. Operand : postfix Operator: Stack Example: Convert this Infix expression into Postfix expression. (A+B/C*(D+E)-F) SYMBOL STACK POSTFIX
  • 73. Convert the following Infix into postfix form: 1. A + B * C + D 2. (A + B) * (C + D) 3. A * B + C * D 4. A + B + C + D SYMBO L STACK POSTFIX
  • 75. Evaluation of Postfix Expression: Postfix : 5, 6, 2, +, *, 12, 4, /, - Symbol Scanned Stack
  • 76. 1) 10 22 + 8 / 6 * 5 + 2) 2 3 * 4 5 + * 3) 2 3 1 * + 9 – 4) 100 200 + 2 / 5 * 7 + Evaluate the following Postfix expressions:
  • 77. What is Queue? o A queue is defined as a linear data structure that is open at both ends and the operations are performed in First In First Out (FIFO) order. o We define a queue to be a list in which all additions to the list are made at one end, and all deletions from the list are made at the other end. o The element which is first pushed into the order, the operation is first performed on that.
  • 78. FIFO Principle of Queue:  A Queue is like a line waiting to purchase tickets, where the first person in line is the first person served. (i.e. First come first serve).  Position of the entry in a queue ready to be served, that is,  the first entry that will be removed from the queue, is called the front of the queue(sometimes,head of the queue),  similarly, the position of the last entry in the queue, that is, the one most recently added, is called the rear (or the tail) of the queue. See the below figure.
  • 79. Characteristics of Queue:  Queue can handle multiple data.  We can access both ends.  They are fast and flexible. Queue Representation: Like stacks, Queues can also be represented in an array: In this representation, the Queue is implemented using the array. Variables used in this case are  Queue: the name of the array storing queue elements.  Front: the index where the first element is stored in the array representing the queue.  Rear: the index where the last element is stored in an array representing the queue.
  • 80.
  • 81. Types of Queue There are four different types of queue that are listed as follows -  Simple Queue or Linear Queue  Circular Queue  Priority Queue  Double Ended Queue (or Deque)
  • 82. Simple Queue or Linear Queue  In Linear Queue, an insertion takes place from one end while the deletion occurs from another end.  The end at which the insertion takes place is known as the rear end, and the end at which the deletion takes place is known as front end.  It strictly follows the FIFO rule.
  • 83. Circular Queue  In Circular Queue, all the nodes are represented as circular.  It is similar to the linear Queue except that the last element of the queue is connected to the first element.  It is also known as Ring Buffer, as all the ends are connected to another end.  The representation of circular queue is shown in the above image.
  • 84. Application of circular queue: Insertion of days in a week.
  • 85. Priority Queue  It is a special type of queue in which the elements are arranged based on the priority.  It is a special type of queue data structure in which every element has a priority associated with it.  Suppose some elements occur with the same priority, they will be arranged according to the FIFO principle.  The representation of priority queue is shown in the image.
  • 86.
  • 87.
  • 88. There are two types of priority queue that are discussed as follows - •Ascending priority queue - In ascending priority queue, elements can be inserted in arbitrary order, but only smallest can be deleted first. Suppose an array with elements 7, 5, and 3 in the same order, so, insertion can be done with the same sequence, but the order of deleting the elements is 3, 5, 7. •Descending priority queue - In descending priority queue, elements can be inserted in arbitrary order, but only the largest element can be deleted first. Suppose an array with elements 7, 3, and 5 in the same order, so, insertion can be done with the same sequence, but the order of deleting the elements is 7, 5, 3.
  • 89. Deque (or, Double Ended Queue)  In Deque or Double Ended Queue, insertion and deletion can be done from both ends of the queue either from the front or rear.  It means that we can insert and delete elements from both front and rear ends of the queue.  Deque can be used as a palindrome checker means that if we read the string from both ends, then the string would be the same.
  • 90. Input restricted deque - As the name implies, in input restricted queue, insertion operation can be performed at only one end, while deletion can be performed from both ends. Output restricted deque - As the name implies, in output restricted queue, deletion operation can be performed at only one end, while insertion can be performed from both ends.
  • 91. Different operations in Queue Data Structure: The various operations that are supported by a queue data structure that helps the user to modify and manipulate the data present in the queue are:  Enqueue operation: The term "enqueue" refers to the act of adding a new element to a queue. Where does a new individual go and wait in a standard queue at a ticket counter to join the queue? The individual walks to the back of the room and takes a seat. A new element in a queue is similarly added at the end of the queue.
  • 92.  Dequeue operation: Dequeue is the process of deleting an item from a queue. We must delete the queue member that was put first since the queue follows the FIFO principle. We'll delete the front element and make the element behind it the new front element because the element added initially will naturally be at the head of the queue.  Front Operation: This works similarly to the peek operation in stacks in that it returns the value of the first element without deleting it.  isEmpty Operation: The isEmpty() function is used to check if the Queue is empty or not.
  • 93. Enqueue Operation Below are the steps to enqueue (insert) data into a queue • Check whether the queue is full or not. • If the queue is full – print the overflow error and exit the program. • If the queue is not full – increment the rear pointer to point to the next empty space. • Else add the element in the position pointed by Rear. • Return success. Algorithm for Enqueue Operation procedure enqueuer (data) if queue is full return overflow endif rear ← rear + 1 queue[rear] ← data return true end procedure
  • 94. Dequeue Operation Below are the steps to perform dequeue operation  Check whether the queue is full or not.  If the queue is empty – print the underflow error and exit the program.  If the queue is not empty – access the data where the front is pointing.  Else increment the front pointer to point to the next available data element.  Return success. Algorithm for Dequeue Operation procedure dequeue if queue is empty return underflow end if data = queue[front] front ← front + 1 return true end procedure
  • 95. Application of Queue in Data Structure A queue data structure is generally used in scenarios where the FIFO approach (First In First Out) has to be implemented. The following are some of the most common applications of the queue in data structure:  Managing requests on a single shared resource such as CPU scheduling and disk scheduling  Handling hardware or real-time systems interrupts  Handling website traffic  Routers and switches in networking  Maintaining the playlist in media players
  • 96. Data Structure - Multiple Stack A single stack is sometimes not sufficient to store a large amount of data. To overcome this problem, we can use multiple stack. For this, we have used a single array having more than one stack. The array is divided for multiple stacks. Suppose there is an array STACK[n] divided into two stack STACK A and STACK B, where n = 10. STACK A expands from the left to the right, i.e., from 0th element. STACK B expands from the right to the left, i.e., from 10th element. The combined size of both STACK A and STACK B never exceeds 10.
  • 97.