Data Structure and Algorithms
Data Structure and Algorithms
Data Structure and Algorithms
Code: ITDC0203
by
Dr Mohit Kumar
4.Understand and apply various data structure such as stacks, queues, trees and graphs to solve various computing
problems using C-programming language.
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CSPC-205
1. M L H L
1. H M M L M M
1. M M
Department of IT 2
1. M H L L
TOPICS COVERED
Unit 2: Array and Linked lists: Arrays: Definition, Single and Multidimensional Arrays,
Representation of Arrays: Row Major Order, and Column Major Order, Application of
arrays, Sparse Matrices and their representations Singly Linked Lists, Doubly Linked
List, Circularly Linked List, Operations on a Linked List. Insertion, Deletion, Traversal,
Applications.
Unit 3: Stack and Queues: Stacks: Introduction, Stack operations: Push & Pop, Prefix and
Postfix Expressions, Applications, Operations on Queue: Create, Add, Delete, Full and
Empty, Circular queues, Dequeue, Priority Queue, Applications.
Department of IT 3
Unit 4: Trees: Basic Terminology, Binary Trees, Binary Tree Representation, Complete
Binary Tree, Tree Traversal algorithms, Huffman algorithm. Search Trees: Binary Search
Trees (BST), Insertion and Deletion in BST, Complexity of Search Algorithm, AVL trees,
Introduction to m-way Search Trees, B Trees & B+ Trees, Graphs: Terminology,
Representations of Graphs, Graph Traversal: Depth First Search and Breadth First Search,
Connected Component, Spanning Trees, Minimum Cost Spanning Trees: Prims and
Kruskals algorithm.
Unit 5: Searching and Sorting: Sequential Search, Binary Search, Comparison and
Analysis, Insertion Sort, Selection Sort, Bubble Sort, Quick Sort, Heap Sort, Radix Sort.
Hash Tables: Basic Hash Tables and Collision Resolution Techniques.
Department of IT 4
TEXT BOOKS, AND/OR REFERENCE MATERIAL
Department of IT 5
What is Data Structure?
A data structure is a particular way of storing and organizing data
in a computer so that it can be used efficiently.
They provide a means to manage large amounts of data efficiently,
such as large databases.
Data are simply values or set of values and Database is organized
collection of data.
Department of IT
6
What is Data Structure? (…contd)
A data structure is a logical and mathematical model of a particular
organization of data.
The choice of particular data structure depends upon following
consideration:
Department of IT
7
THE STUDY OF DATA STRUCTURE
INCLUDE:
Logical description of data structure
Implementation of data structure
Quantitative analysis of data structure, this include
amount of memory, processing time
Department of IT
8
Classification of Data Structure
Data Structures
Department of IT
9
Classification (contd..)
A data structure can be broadly classified into
Primitive data structure
Non-primitive data structure
Primitive data structure :-The data structures, that are directly
operated upon by machine level instructions i.e. the
fundamental data types such as int, float in case of ‘c’ are
known as primitive data structures.
Non- Primitive data structure :-These are more complex data
structures. These data structures are derived from the primitive
data structures.
Department of IT
10
Classification (contd..)
Non-Primitive Data Structures can be further divided into two
categories:
Linear Data Structures
Non-Linear Data Structures.
Linear Data Structures:-In linear data structures, data elements
are organized sequentially and therefore they are easy to
implement in the computer’s memory. E.g. Arrays.
Non-Linear Data Structures:-In nonlinear data structures, a
data element can be attached to several other data elements to
represent specific relationships that exist among them. E.g.
Graphs
Department of IT
11
Linear Data Structure Non-linear Data Structure
In a linear data structure, data elements are In a non-linear data structure, data elements
arranged in a linear order where each and are attached in hierarchically manner.
every element is attached to its previous and
next adjacent.
In linear data structure, single level is Whereas in non-linear data structure,
involved. multiple levels are involved.
Its implementation is easy in comparison to While its implementation is complex in
non-linear data structure. comparison to linear data structure.
In a linear data structure, memory is not While in a non-linear data structure, memory
utilized in an efficient way. is utilized in an efficient way.
Its examples are: array, stack, queue, linked Examples are: trees and graphs.
list, etc.
Applications of linear data structures are Applications of non-linear data structures are
mainly in application software development. in Artificial Intelligence and image
processing.
Performance is usually good for simple Performance can vary depending on the
operations like adding or removing at the structure and the operation, but can be
ends, but slower for operations like searching optimized for specific operations.
or removing elements in the middle. Department of IT 12
Array & Linked List
node
linked
Linked list A B C
Department of IT
13
Stack
Stack
• New nodes can be added and removed only at the top
• Similar to a pile of dishes
• Last-in, first-out (LIFO)
push
• Adds a new node to the top of the stack
pop
• Removes a node from the top
Department of IT
14
Stack
A stack is a list in which insertion and deletion take place at the
same end
• This end is called top
• The other end is called bottom.
Department of IT
15
Queue
Queue
• Similar to a supermarket checkout line
• First-in, first-out (FIFO)
• Nodes are removed only from the front.
• Nodes are inserted only at the rear.
Insert and remove operations
• Enqueue (insert) and dequeue (remove)
Department of IT
16
The Queue Operations
A queue is like a line of people waiting for a bank
teller. The queue has a front and a rear.
$ $
Walking out
Rear(insertion) Front(Removal)
Department of IT
17
Tree
A tree T is a finite non empty set of elements. One of these
elements is called the root, and the remaining elements, if any, are
portioned into trees, which are called the sub trees of T.
Department of IT
18
Tree (example)
node
d ge
e
Department of IT
19
Graph
A graph is defined as:
“Graph G is a ordered set (V,E), where V(G) represent the
set of elements, called vertices, and E(G) represents the
edges between these vertices.”
Graphs can be
• Undirected
• Directed
Department of IT
20
Graph
Figure shows a sample graph
V(G)={v1,v2,v3,v4,v5}
E(G)={e1,e2,e3,e4,e5}
e2
v5
v1 e3
e5 v4
e1
v2 v3
e4
e2
v5
v1 e3
e5 v4
e1
v2 v3
e4
Department of IT
22
Data Structure Operations
Five major operations are associated with all data structures.
i. Creation:- Initialization of the beginning.
ii.Insertion: - Insertion means adding new details or new node
into the data structure.
iii.Deletion: - Deletion means removing a node from the data
structure.
iv.Traversal: - Traversing means accessing each node exactly
once so that the nodes of a data structure can be processed.
Traversing is also called as visiting.
v.Searching: - Searching means finding the location of node for
a given key value.
Department of IT
23
Data Structure Operations(contd..)
Apart from the four operations mentioned above, there
are two more operations occasionally performed on data
structures. They are:
(a) Sorting: -Sorting means arranging the data in a
particular order.
(b) Merging: - Merging means joining two lists.
Department of IT
24
A first look on ADTs
Solving a problem involves processing data, and an
important part of the solution is the efficient
organization of the data
Department of IT 25
Abstract Data Type (ADT)
The word “abstract” refers to the user define data type where data
and the basic operations defined on it are being studied
independently of how they are implemented
We think about what can be done with the data, not how it is done
Department of IT 26
Some ADT’s
Some user defined ADT’s are
Stacks
Queues
Department of IT
27
Stack ADT
We define a stack as an ADT as shown below:
Department of IT
28
Queue ADT
We define a queue as an ADT as shown below:
Department of IT
29
Algorithm
We are surrounded with many real life problems for
which we are searching and implementing solutions or
optimal solutions.
Algorithm is a tool to design the solutions for such
problems.
Even, we can easily analyse solutions represented as
algorithmic form in order to find the optimal one.
Department of IT 30
Algorithm: Formal Definition
A sequence of finite, precise and unambiguous instructions which are
applied either to perform a computation or to solve a computational
problem.
A finite set of instructions that specify a sequence of operations to be
carried out in order to solve a specific problem or class of problems.
T(n)
n 4
• Algorithm vs Program????
Department of IT 31
Expressing Algorithm
Can be represented in different ways using some sort of language, such as
pseudo code or the flowcharts.
Example: Algorithm for searching the largest element from the list of given
elements
Max_Array(A,N)
Input: An array ‘A’ with ‘N’ elements
is given
Output: Display the minimum element
1.Set Largest=A[0]
2.for(i=1 to N-1)
if (A[i]>Largest) then
Set Largest=A[i]
3. Print (Largest)
Department of IT 32
(Pseudo code) (Flowchart)
Pseudo code
Pseudo code is a combination of English and programming construct.
It is the most preferred notation to describe algorithm
It is less detailed than a programming solution because it focuses only
on fundamental operations instead of features of a programming
language i.e. it is independent from any programming language.
Easy to analyse the maximum number of primitive operations in an
algorithm.
To describe an algorithm, the pseudo code uses various basic
programming primitives, such as sequence, conditionals and looping
syntaxes.
Department of IT 33
What is Pseudo-Code ?
A mixture of natural language and high-level programming concepts that
describes the main ideas behind a generic implementation of a data
structure or algorithm.
-Expressions: use standard mathematical symbols to describe
numeric and boolean expressions -use for assignment (“=” in Java)
-use = for the equality relationship (“==” in Java)
-Method Declarations: -Algorithm name(param1, param2)
-Programming Constructs: - decision structures: if ... then ... [else ... ]
- while-loops: while ... do
- repeat-loops: repeat ... until ...
- for-loop: for ... do
- array indexing: A[i]
Department of IT 34
Properties of Algorithms
Algorithm generally share a set of properties
Input. An algorithm has zero or more inputs, i.e, quantities which are given to it
initially before the algorithm begins.
Output. An algorithm has one or more outputs i.e, quantities which have a specified
relation to the inputs.
Finiteness. An algorithm must always terminate after a finite number of steps.
Definiteness. Each step of an algorithm must be clear and unambiguous so that the
action can be carried out without any ambiguity
Effectiveness. An algorithm is also generally expected to be effective. This means
that all of the operations to be performed in the algorithm must be sufficiently basic
that they can in principle be done exactly and in a finite length of time.
Correctness. An algorithm must produce the correct output values for all legal input
instances of the problem.
Department of IT 35
Performance Analysis
Measurement of the resources consumed by the algorithm
during its execution.
In case of computing problems, the main resources are
the CPU time and RAM
The algorithms that require less space and time are said to
be more efficient.
Thus, analysis is divided into two categories:
1. Space Complexity
2. Time Complexity
Department of IT 36
Space Complexity
S(A)=S(C)+S(R)
Where,
S(A): Space required to run the algorithm (for formal parameters,
local variables, return address, variables, constants and identifiers)
Department of IT 37
Measuring the Running Time
How should we measure the running time of an algorithm?
Approach 1: Experimental Study
• Write a program that implements the algorithm
• Run the program with data sets of varying size and composition.
• Use a method like System.currentTimeMillis() to get an accurate
measure of the actual running time.
t (ms)
60
50
40
30
20
10
Department of IT n 38
0 50 100
Beyond Experimental Studies
Experimental studies have several limitations:
• It is necessary to implement and test the algorithm in order to
determine its running time.
• Experiments can be done only on a limited set of inputs, and may
not be indicative of the running time on other inputs not included
in the experiment.
• In order to compare two algorithms, the same hardware and
software environments should be used.
Department of IT 39
Beyond Experimental Studies
We will now develop a general methodology for analyzing the
running time of algorithms. In contrast to the "experimental
approach", this methodology:
• Uses a high-level description of the algorithm instead of testing
one of its implementations.
• Takes into account all possible inputs.
• Allows one to evaluate the efficiency of any algorithm in a way
that is independent from the hardware and software
environment.
Department of IT 40
Time Complexity: Simpler Way
• It is the time required to execute an algorithm
• Not physical time over a machine but related to the number
of instructions executed.
• Is the estimate of the number of basic operations executed by
an algorithm.
Department of IT 41
Process to measure running time
1. Identify basic operations (instructions).
2. Compute the total time taken by these basic operations as follows:
Total cost of basic operation= Cost of basic operation perform
once* Number of times the basic operations are performed
3. Total time T(n)= Sum of total cost of all the basic operations
obtained in step 2.
1.Set Largest=A[0]-------------------------C1
2.for(i=0 to N-1)----------------------------C2*n
if (A[i]==num)---------------------C3*n
print i----------------------------C4
break;----------------------------C5
T(n)=C1+C2*n+C3*n+C4+C5
Department of IT 42
Best Case vs Worst Case vs
Average Case Running Time
An algorithm may run faster on certain data sets than on others.
Finding the average case can be very difficult, so typically
algorithms are measured by the worst-case time complexity.
Also, in certain application domains (e.g., air traffic control,
surgery, IP lookup) knowing the worst-case time complexity is of
crucial importance.
5 ms worst-case
4 ms
3 ms
}
average-case?
best-case
2 ms
1 ms
A B Department
C D of ITE F G 43
Input
The Sorting Problem
Expected
Output: The permutation of the input [26, 31, 41, 41, 58 , 59].
Department of IT 44
Insertion Sort
Insertion sort is
efficient algorithm for
sorting a small number
of elements.
Department of IT 45
Insertion Sort (cont.)
Department of IT 46
Insertion Sort (cont.)
Department of IT 47
Insertion Sort (cont.)
Algorithm of insertion sort
Department of IT 48
Example of insertion sort
8 2 4 9 3 6
Department
L1.49 of IT
Example of insertion sort
8 2 4 9 3 6
Department
L1.50 of IT
Example of insertion sort
8 2 4 9 3 6
2 8 4 9 3 6
Department
L1.51 of IT
Example of insertion sort
8 2 4 9 3 6
2 8 4 9 3 6
Department
L1.52 of IT
Example of insertion sort
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
Department
L1.53 of IT
Example of insertion sort
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
Department
L1.54 of IT
Example of insertion sort
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
2 4 8 9 3 6
Department
L1.55 of IT
Example of insertion sort
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
2 4 8 9 3 6
Department
L1.56 of IT
Example of insertion sort
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
2 4 8 9 3 6
2 3 4 8 9 6
Department
L1.57 of IT
Example of insertion sort
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
2 4 8 9 3 6
2 3 4 8 9 6
Department
L1.58 of IT
Example of insertion sort
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
2 4 8 9 3 6
2 3 4 8 9 6
2 3 4 6 8 9 done
Department
L1.59 of IT
Analysis of Insertion Sort
Time efficiency analysis …
Department of IT 60
Time Complexity
The running time of the algorithm is the sum of
running times for each statement executed;
Department of IT
61
Best Case Analysis
The best case occurs if the array is already sorted. For each
j=2,3,4…..n. we then find that A[i]<= key in line 5 when i has
its initial value of j-1.
Thus tj=1for j=2,3,4…..n. and the best-case running time is
This running time can be expressed as an+b for constants a and b that depend on
the statement costs ci; it is thus a linear function of n.
Department of IT
62
Worst Case Analysis
If the array is in reverse sorted—the worst case results.
We must compare each element A[j] with each element in the entire sorted
subarray A[1… j-1] and so tj=j for j=2,3,4….n
Then,
and
We can express this result as an2+bn+c for constants a,b,c which depends
upon statement costs. Thus the complexity is ITa quadratic function of n
Department of 63
Growth of Functions
Department of IT 64
Growth of Functions
For the large value of the input n only the higher order terms
matter.
In order to compare solutions based on complexity it is better
to compare their complexity function order.
O(1)<O(logn)<O(n)<O(nlogn)<O(n2)<O(n3)….…O(nk)<O(2n)
Department of IT 65
Asymptotic Notation
Special Symbols for comparing the growth rate of functions: ,
O, ,
Running time of an algorithm is computed as a function of input
size n for large n.
Expressed using only the highest-order term in the expression
for the exact running time.
• Instead of exact running time, say (n2).
Describes behavior of function in the limit.
Written using Asymptotic Notation.
Department of IT 66
Big-oh, O-notation
It is a formal method of expressing the upper
bound of an algorithm’s running time i.e. longest
time taken by an algorithm.
More formally, for non-negative functions f(n)
and g(n), if there exist an integer n0 and a
constant c>0 such that for all integer n n0
or
f(n) =O (g(n))
Department of IT 67
Examples
Prove that f(n)=O(g(n)) where f(n)=3n+2 and g(n)=n
For n0>=1 and c=5
Any linear function an + b is in O(n2). How?
Show that 3n3=O(n4) for appropriate c and n0.
Department of IT 68
-notation
For non-negative functions f(n)
and g(n), if there exist an integer
n0 and a constant c>0 such that for
all integer n n0
0 cg(n) f(n)
f(n) = (g(n))
Department of IT 70
-notation
The lower and upper bound for the
function f(n) is provided by the
notation.
For non negative functions f(n) and
g(n), if there exist an integer an integer
n0 and positive constants c1, c2 >0 such
that for all integer n n0
0 c1g(n) f(n) c2g(n)
Then
f(n) =(g(n))
Department of IT 72
Asymptotic Notation in Equations
Can use asymptotic notation in equations to replace
expressions containing lower-order terms.
For example,
4n3 + 3n2 + 2n + 1 = 4n3 + 3n2 + (n)
= 4n3 + (n2) = (n3). How to interpret?
In equations, (f(n)) always stands for an
anonymous function g(n) (f(n))
• In the example above, (n2) stands for
3n2 + 2n + 1.
Department of IT 73
Some example to find Complexity
A()
{ Complexity is
int i,j;
for(i=1 to n) O(n2)
{
for(j=1 to n)
{
printf("RAM");
}
}
}
Department of IT 74
Some example to find Complexity
A(){ i= 1, 2, 3, 4, 5,.......n
int i,j,k,n; j= 1, 2, 3, 4, 5,.......n
for(i=1;i<=n;i++)
k= 1*10, 2*10, 3*10,......n*10 times
{
for(j=1;j<=i;j++)
{ t(n)=(1+2+3+4+5.....n)10
for(k=1;k<=10;k++) t(n)=n(n+1)/2*10
{ =O(n2)
printf("kps");
}
}
}
}
Department of IT 75
Some example to find Complexity
A() T(n)=log(n)
{
int a=1;
for(int i=1;i2<=n;i++)
print(“Ram”);
}
Department of IT 76
ARRAYS
An array is a collection of elements of the same type
that are referenced by a common name.
Department of IT
77
Why ARRAYS?
"We have a list of 1000 students' marks of an
integer type. If using the basic data type (int),
we will declare something like the following…"
int main()
{
int studMark1, studMark2, studMark3,…………
studMark1000;
…………
return 0;
Department of IT
} 78
ARRAYS
By using an array, we just declare like this,
int studMark[1000];
This will reserve 1000 contiguous memory locations for storing the
students’ marks.
Graphically, this can be depicted as in the following figure.
Department of IT
79
Arrays in Memory
Assuming integer takes 2 bytes of storage
Department of IT
80
Arrays
One Dimensional Array: Declaration
A single or one dimensional array declaration has the
following form,
array_data_type array_name[array_size];
Department of IT
81
Arrays
For example, to declare an array of 30 characters, that
construct a people name, we could declare,
char cName[30];
Which can be depicted as follows,
In this statement, the array character can store
up to 30 characters with the first character
occupying location cName[0] and the last
character occupying cName[29].
Note that the index runs from 0 to 29. In C, an
index always starts from 0 and ends with array's
(size-1).
Department of IT
82
Arrays
Array Initialization
Department of IT
83
Array Initialization
Examples
int num[6] = { 2, 4, 12, 5, 45, 5 } ;
int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
float press[ ] = { 12.3, 34.2 -23.4, -11.3 } ;
Till the array elements are not given any specific values, they are supposed to
contain garbage values.
int B[20] = {2, 4, 8, 16, 32};
•Unspecified elements are guaranteed to be zero
int C[4] = {2, 4, 8, 16, 32};
•Error — compiler detects too many initial values
int E[5] = {1};
•Dynamically allocated array (automatic only). Zeroth element initialized to 1; all
other elements initialized to 0.
int E[5] = {0};
All elements initialize to zero
Department of IT 84
1-D Array
Homogeneous data:
a) Elements are represented through indexes.
b) Elements are saved in sequential in memory locations.
Number of elements, N –> length or size of an array.
If:
UB : upper bound ( the largest index)
LB : lower bound (the smallest index)
Then: N = UB – LB + 1
Length = N = UB when LB = 1
Department of IT
85
Address Calculation in 1-D Array
The process to determine the address in a memory:
a) First address –> base address.
b) Relative address to base address through index function.
Department of IT
86
Address Calculation in 1-D Array(..contd)
In general, index function:
Loc (X[i]) = Loc(X[LB]) + w*(i-LB);
Example:
If LB = 5, Loc(X[LB]) = 1200, and w = 4, find Loc(X[8]) ?
Department of IT
87
Address Calculation in 1-D Array(..contd)
Q1 Consider the linear arrays AAA[5:50], BBB [-5:10] and
CCC[1:18].
(a) Find the number of elements in each array
(b) Suppose Base(AAA) = 300 and w=4 words per memory cell for
AAA. Find the address of AAA[35] ,AAA[15], and AAA[55]
Department of IT 88
(a) Length = Upper Bound – Lower Bound +1
Length(AAA) = 50-5+1 = 46
Length(BBB) = 10-(-5)+1 = 16
Length(CCC) = 18-1+1 = 18
Department of IT 89
2-D Array
Imagine now we want to keep 10 test scores for 30 students.
• How would we represent this in a program with what we’ve learned?
• Answer: You would need either 30 10-element arrays or
10 30-element arrays.
What we have been working with so far are considered one
dimensional arrays, because they only extend along one
dimension (one set of data).
“C” allows for higher dimensional arrays, for example, two
dimensional arrays.
• Two dimensional arrays can be though of having a table of rows and
columns in memory.
So, a better solution to the above question is what?
• Answer: Have a 30 x 10 or a 10 x 30 two dimensional array!
Department of IT
90
Department of IT 91
Department of IT 92
Department of IT 93
Storage Order
Row-major order: the array is stored as a sequence of arrays
consisting of rows
(0,0)
0 1 2 3 4 5 6 (0,1)
(0,2)
0
Department of IT 94
Storage Order
Column-major order: The array is stored as a sequence of arrays
consisting of columns instead of rows
(0,0)
4 5 (1,0)
0 1 2 3 6
(0,1)
0
Department of IT 95
Address Calculation in 2-D Array
When lower bound is not given.
The computer keeps track of Base (BA),:-
the address of the first element A[0][0] of A[M][N],
and computes address i.e. Loc (A[I][J]) of A[M][N] using
the formula
Loc(A[I][J])=Base (BA)+W[M*J + I] [Column Major]
Loc(A[I][J])=Base (BA)+W[N*I + J] {Row- Major}
W denotes the size, i.e; number of bytes per data element of the
array A,
M is total numbers of rows, and N is total number of columns in
the array.
Department of IT
96
Address Calculation in 2-D
Array(..contd)
When lower bound is given
Loc(A[I][J])=Base (BA)+W[M*(J-LBC) + (I-LBR)] [Column Major]
Department of IT
97
Example
Suppose element of array A[4][5] occupies 4 bytes, and the address
of the 1st element is 49. Find the address of the
element A(4,3) when the storage is row major.
= BA + [N * (I - LBR) + (J - LBC)] * W
= 49 + [5 * (4 – 0) + (3 - 0)] * 4
= 49 + [23] * 4
= 49 + 92
= 141
Department of IT
98
Sparse Matrix
A matrix is sparse if many of its elements are zero
A matrix that is not sparse is dense
Two possible representations
• array
• linked list
Department of IT
99
Array Representation of Sparse Matrix
The nonzero entries may be mapped into a 1D array in row-major
order
To reconstruct the matrix structure, need to record the row and
column each nonzero comes from
Department of IT
100
Basic Operations
Following are the basic operations supported by an array.
Traverse − print all the array elements one by one.
Insertion − Adds an element at the given index.
Deletion − Deletes an element at the given index.
Search − Searches an element using the given index or by the
value.
Department of IT
101
Traversal
Description: Here A is a linear array with lower
bound LB and upper bound UB. This algorithm
traverses array A and applies the operation
PROCESS to each element of the array.
1. Repeat For I = LB to UB
2. Apply PROCESS to A[I]
[End of For Loop]
3. Exit
Department of IT
102
Deletion algorithm
DELETE (LA, N, K, ITEM)
Here LA is a Linear Array with N elements and K is the positive
integer such that K<=N. This algorithm deletes the Kth element from
LA.
2. Repeat for J = K to N – 1.
4. EXIT
Department of IT
103
Insertion algorithm
INSERT (LA, N, K, ITEM)
1. [Initialize counter] Set J: = N.
7. EXIT.
Department of IT
104
Linear Search
Linear Search ( Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
Department of IT
105
Introduction to Array (CO1)
In the best case, the target value is in the first element of the
array.
So the search takes some tiny, and constant, amount of time.
In the worst case, the target value is in the last element of the
array.
So the search takes an amount of time proportional to the
length of the array. O(n)
Department of IT
106
Introduction to Array (CO1)
Department of IT
107
Introduction to Array (CO1)
Binary Search
The general term for a smart search through sorted data is a binary
search.
1. The initial search region is the whole array.
2. Look at the data value in the middle of the search region.
3. If you’ve found your target, stop.
4. If your target is less than the middle data value, the new search
region is the lower half of the data.
5. If your target is greater than the middle data value, the new
search region is the higher half of the data.
6. Continue from Step 2.
Department of IT
108
Introduction to Array (CO1)
Department of IT
109
Introduction to Array(CO1)
Department of IT
110
Introduction to Array (CO1)
Department of IT
111
Binary Search
Department of IT
112
Introduction to Array (CO1)
Example
Insert element in array
Input
Department of IT
115
Introduction to Array (CO1)
Department of IT
116
Introduction to Array(CO1)
Department of IT
117
Introduction to Array(CO1)
arr[pos - 1] = num;
Department of IT
118
Introduction to Array(CO1)
Example
Delete element from an array
Input
Department of IT
120
Introduction to Array(CO1)
else
{
for(i=pos; i<=size-1; i++)
{
arr[i-1] = arr[i];
}
size--;
}
printf("\nElements of array after delete are : ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}
return 0;
}
Department of IT
123
Introduction to Array (CO1)
Multi-dimensional Arrays in C
Multidimensional array declaration
type name[size1][size2]...[sizeN];
Department of IT
124
Introduction to Array(CO1)
Department of IT
125
Introduction to Array (CO1)
The nested braces, which indicate the intended row, are optional. The
following initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Department of IT 126
Introduction to Array(CO1)
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }
Department of IT
127
Introduction to Array(CO1)
Department of IT
130
Introduction to Array(CO1)
Department of IT
131
Introduction to Array(CO1)
Where,
B = Base address
I1 = Row subscript of element whose address is to be found
I2 = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
L1 = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
L2 = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
N1 = Number of row of the given matrix
Department of IT
132
N = Number of column of the given matrix
Introduction to Array(CO1)
Address of A [ I1 ][ I2 ] =B + W * [( I1 – L1 )* N2 + ( I2 – L2 )]
A [ I1 ] = B + W * [E1 ]
Department of135
IT
Introduction to Array(CO1)
Department of IT 137
Introduction to Array(CO1)
Three-Dimensional Array
Department of IT
138
Introduction to Array(CO1)
Rows - wise :
Location (A[I1, I2, I3]) = B + W*[(E1N2+E2)*N3+E3]
= B + W*[((I1-L1)*N2+(I2-
L2))*N3+(I3-L3)]
Method 2:
int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
For (i=0;i<n;i++0
{
For(j=0;j<n;j++)
{
For(k=0;k<n;k++)
{
scanf(“%d”,&a[i][j][k])
Department of IT
140
Introduction to Array(CO1)
Applications of Arrays in C
● Arrays are used to Store List of values
● Arrays are used to Perform Matrix Operations
● Arrays are used to implement Search Algorithms
Linear Search Binary Search
● Arrays are used to implement Sorting Algorithms.
Insertion Sort Bubble Sort
Selection Sort Quick Sort Merge Sort, etc.,
● Arrays are used to implement Data structures.
Stack Using Arrays Queue Using Arrays
● Arrays are also used to implement CPU Scheduling Algorithms.
Department of IT
141
Pointer Notation
Consider the declaration,
int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
Department of IT 142
What are Pointers?
• A pointer is a variable whose value is the address of another variable,
i.e., direct address of the memory location.
• Like any variable or constant, you must declare a pointer before using it
to store any variable address.
Pointer variable declaration:
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and
varname is the name of the pointer variable. The asterisk * used to
declare a pointer is the same asterisk used for multiplication.
Examples: some of the valid pointer declarations:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */of IT
Department 143
How to Use Pointers?
Three things need to do
(1) We define a pointer variable,
(2) Assign the address of a variable to a pointer, and
(3) Finally access the value at the address available in the pointer variable.
This is done by using unary operator *. Which says the value at the address.
main( ) output:
{
int i = 3 ; Address of i = 65524
printf ( "\nAddress of i = %u", &i ) ; Value of i = 3
printf ( "\nValue of i = %d", i ) ;
}
main( ) output
{
int i = 3 ; Address of i = 65524
printf ( "\nAddress of i = %u", &i ) ; Value of i = 3
printf ( "\nValue of i = %d", i ) ; Value of i = 3
printf ( "\nValue of i = %d", *( &i ) ) ;
Department of IT 144
}
How to Use Pointers?
The expression &i gives the address of the variable i. This address can be
collected in a variable, by saying,
j = &i ;
But remember that j is not an ordinary variable like any other integer variable.
It is a variable that contains the address of other variable (i in this case).
Department of IT 145
How to Use Pointers?
Department of IT 146
Pointer to Pointer or Double pointer
• A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
• When we define a pointer to a pointer, the first pointer contains the address of
the second pointer, which points to the location that contains the actual value as
shown below.
int i=3;
int *j=&i;
int **k=&j;
Department of IT 147
Operation do not work with pointer
Do not attempt the following operations on pointers... they
would never work out.
(a) Addition of two pointers
(b) Multiplication of a pointer with a constant
(c) Division of a pointer with a constant
Department of IT 148
Department of IT 149
Recursion
Recursion
• Recursion is a process by which a function calls itself repeatedly,
until some specified condition has been satisfied
Department of IT 15
0
Recursion
Recursion
• There is base condition, that stops further calling of the
function
Department of IT 15
1
Recursion
Calculate Factorial of the number using
Recursion.
factorial of n (n!) = n * n-1 – n-2* ………*2*1
Department of IT 15
2
Recursion
• Cons
• Recursive functions are generally slower than non-
recursive functions.
• May require a lot of memory to hold intermediate results
on the system stack.
• It is difficult to think recursively so one must be very
careful when writing recursive functions.
Department of IT
15
3
Recursion
Difference Between Recursion and Iteration
BASIS FOR
RECURSION ITERATION
COMPARISON
Basic The statement in a body of Allows the set of instructions
function calls the function to be repeatedly executed.
itself.
Format In recursive function, only Iteration includes
termination condition (base initialization, condition,
case) is specified. execution of statement within
loop and update (increments
and decrements) the control
variable.
Termination A conditional statement is The iteration statement is
included in the body of the repeatedly executed until a
function to force the function certain condition is reached.
to return without recursion call
being executed.
Department of IT 154
Recursion
Difference Between Recursion and Iteration
BASIS FOR COMPARISON RECURSION ITERATION
Condition If the function does not If the control condition in the
converge to some condition iteration statement never
called (base case), it leads to become false, it leads to
infinite recursion. infinite iteration.
Infinite Repetition Infinite recursion can crash the Infinite loop uses CPU cycles
system. repeatedly.
Applied Recursion is always applied to Iteration is applied to iteration
functions. statements or "loops".
Stack The stack is used to store the Does not uses stack.
set of new local variables and
parameters each time the
function is called.
Overhead Recursion possesses the No overhead of repeated
overhead of repeated function function call.
calls. Department of IT 155
Recursion
Difference Between Recursion and Iteration
BASIS FOR
RECURSION ITERATION
COMPARISON
Speed Slow in execution. Fast in execution.
Size of Code Recursion reduces the size of Iteration makes the code
the code. longer.
Department of IT 156
Introduction to Link List(CO1)
Department of IT 157
Introduction to Link List(CO1)
Linked List
Department of IT 158
Introduction to Link List(CO1)
Linked List
• In a linear or single-linked list, a node is connected to the next node
by a single link.
Department of IT 159
Introduction to Link List
Department of IT 160
Introduction to Link List(CO1)
Linked List
• The structure defined for a single linked list is implemented as
follows:
struct node
{
int data;
struct node *next;
};
}The structure declared for linear linked list holds two members
• An integer type variable ‘data’ which holds the elements and
• Another type ‘node’, which has next, which stores the address of the next
node in the list.
Department of IT 161
Introduction to Link List(CO1)
Figurative
Representation
Department of IT 162
Introduction to Link List(CO1)
Department of IT 163
Introduction to Link List(CO1)
Department of IT 164
Link List(CO1)
Insertions and Deletions are inefficient: Insertions and Deletions are efficient: No
Elements are usually shifted shifting
No memory waste if the array is full or almost Since memory is allocated dynamically(acc. to
full; otherwise may result in much memory our need) there is no waste of memory.
waste.
Sequential access is faster [Reason: Elements in Sequential access is slow [Reason: Elements not
contiguous memory locations] in contiguous memory locations]
Department of IT 165
Introduction to Link List(CO1)
Department of IT 166
Introduction to Link List(CO1)
• In this type of linked list each node contains two fields one is data
field which is used to store the data items and another is next field
that is used to point the next node in the list.
5 3 8 null
Department of IT 167
Introduction to Link List(CO1)
struct node
{ int data; // Data part of the node
struct node* next; // Pointer to the next node
};
Initialize the Head Pointer: The head pointer points to the first node in the
linked list. Initially, it is set to NULL because the list is empty.
• The above statement obtains memory to store a node and assigns its address to
head which is a pointer variable.
Department of IT 168
Introduction to Link List(CO1)
Creating a Node
• To create a new node, we use the malloc function to dynamically
allocate memory for the new node.
• After creating the node, we can store the new item in the node using a
pointer to that node.
Nodetype *p;
p=(NodeType *) malloc (sizeof( NodeType ) ); p->info=50;
p->next = NULL;
Department of IT 169
Introduction to Link List(CO1)
OR SIMPLY
Department of IT 170
Introduction to Link List(CO1)
Inserting an Element
• While inserting an element or a node in a linked list, we have to
do following things:
• Allocate a node
• Assign a data to info field of the node.
• Adjust a pointer
Department of IT 172
Introduction to Link List(CO1)
Department of IT 174
Introduction to Link List(CO1)
Department of IT 175
Introduction to Link List(CO1)
Department of IT 176
Introduction to Link List(CO1)
Department of IT 177
Introduction to Link List(CO1)
Department of IT 178
Introduction to Link List(CO1)
Deleting Nodes
Department of IT 180
Introduction to Link List(CO1)
Deleting Nodes
Department of IT 181
Introduction to Link List(CO1)
Department of IT 182
Introduction to Link List(CO1)
Department of IT 183
Department of IT 184
An algorithm to delete a node after the given
node in singly linked list
Let *head be pointer to the first node in the current list and p* be
pointer to the node after which we want to delete a new node
Department of IT 185
Introduction to Link List(CO1)
Department of IT 186
Introduction to Link List(CO1)
Department of IT 187
Introduction to Link List(CO1)
Department of IT 188
Introduction to Link List(CO1)
Department of IT 189
Introduction to Link List(CO1)
Fun
fact:
If you are worried about its implementation,
then stop doing that because instead of
placing NULL at the last node’s address field
you are placing the address of very first node!
Department of IT 192
Circular Link List(CO1)
Circular linked list vs. Linear
linked list
• A circularly linked list may be a natural option to represent
arrays
that are naturally circular, e.g. the corners of a polygon, a
pool
of buffers that are used and released in FIFO order, or a set
of processes that should be time-shared. In these
applications, a pointer to any node serves as a handle to
the whole list.
• With a circular list, a pointer to the last node gives easy
access also to the first node, by following one link. Thus, in
applications that require access to both ends of the list, a
circular structure allows one to handle the structure by a
single pointer, instead of two.
• The simplest representation for an empty circular list
(when such a thing makes sense) is a null pointer,
Department of IT 193
indicating that the list has no nodes. Without this choice,
Circular Link List(CO1)
Department of IT 194
Circular Link List(CO1)
Advantages of Circular
linked lists:
1. Any node can be a starting point. We can traverse
the whole list by starting from any point. We just
need to stop when the first visited node is visited
again.
Department of IT 196
Circular Link List(CO1)
Department of IT 197
Circular Link List(CO1)
Insertion :
• Insertion can be of three types.
▫Insert at first
▫Insert at last
▫Insert after constant
Department of IT 198
Circular Link List(CO1)
Insertion at first
Department of IT 199
Algorithm (Insertion)
Department of IT 200
Circular Link List(CO1)
Code
Void addfront(){
struct node *t=start;
struct node *n=(struct node*)malloc(sizeof(struct node));
printf(“\nenter the information”);
scanf(“%d”,&n->info);
if(start==NULL){
start=n;
start->next=start;}
else{
n->next=start;
while(t->next!=start)
t=t->next;
t->next=n;
start=n;
Department of IT 201
}
Circular Link List(CO1)
Insert at last
Department of IT 202
Algorithm to Insert at Last
• Start.
• Declare struct node *t.
• Set t:=start.
• Create a new node n by malloc function and enter the
information in info part.
• Check if start=NULL then,
set start:=n.
set start->next:=start.
else
• Set n->next:=start.
• Repeat step(a)
while(t!=NULL)
▫ (a) set t:=t->next.
• [end of loop]
• Set t->next=n.
• [end if] Department of IT 203
• Stop.
Circular Link List(CO1)
Program
Void addlast(){
struct node *t=start;
struct node *n=(struct node*)malloc(sizeof(struc
node));
printf(“\nenter the information”); scanf(“%d”,&n
>info);
if(start==NULL){
start=n;
start->next=start;}
else{
n->next=start;
while(t->next!=start)
Department of ITt=t->next; 204
t->next=n;
Circular Link List(CO1)
Deletion :
• Deletion can be of three types.
▫Delete from front
▫Delete from last
▫Deletion from mid
Department of IT 205
Circular Link List(CO1)
Department of IT 206
Circular Link List(CO1)
Algorithm Progra
start.
Check if (start=NULL) then,
m
Void delfront(){
struct node *t=start;
print “empty list” if (start==NULL)
Check if printf (“\nempty list”);
(start->next=start) then, else if (start->next==start){
declare free (t) free (t);
set start:=NULL otherwise start=NULL;}
Repeat step(a) while(t->next!=start)
else{
▫ (a) set t:=t->next
while(t->next!=start)
[end of loop] t=t->next;
start=start->next;
free(t->next);
t->next=start;
}
Department of IT 207
}
Circular Link List(CO1)
Algorithm
• set start:=start-
>next
• Declare free(t-
>next).
• Set t->next:=start.
• [end of if]
• stop
Department of IT 208
Circular Link List(CO1)
Department of IT 209
Circular Link List(CO1)
Algorithm Program
• start. Void dellast()
• Check if (start=NULL) {
then, print “empty list” struct node *t=start;
• Check if (start- if (start==NULL)
>next=start) printf(“\nempty list”);
then, else if (start-
declare free (t) set >next==start)
{
start:=NULL otherwise
• Repeat step(a) free (t); start=NULL ;
}
while(t->next->next! else
=start) {
▫ (a) set t:=t->next while(t->next->next!
• [end of loop] =start)
• Declare free(t->next). t=t->next; free(t->next);
• Set t->next:=start. t->next=start;
• [end if] }
• stop Department of IT } 210
Circular Link List(CO1)
Display
Department of IT 211
Circular Link List(CO1)
Algorithm Progra
• start. m
Void display()
• Set struct node {
struct node *t=start;
*t:=start. if(start=NULL)
• Check printf (“\nempty
if(start=NULL) list”); else
then, print “empty {
list” otherwise while(t->next!
• Repeat step a and b =start)
while(t->next! {
=start) printf(“%d”, t->info);
t=t->next;
▫ (a) print t->info }
▫ (b) set t:=t->next printf(“%d”, t->info);
• [end of loop] }
• Print t->info [end Department of}IT 212
Link List(CO1)
The two links help us to traverse the list in both backward and forward
direction. But storing an extra link requires some extra space.
Department of IT 213
Link List(CO1)
Department of IT 214
Link List(CO1)
Department of IT 215
Link List(CO1)
Department of IT 216
Link List(CO1)
Insertion
In a double linked list, the insertion operation can be performed in
three ways as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Department of IT 217
Link List(CO1)
Department of IT 218
Link List(CO1)
Inserting At End of the list
We can use the following steps to insert a new node at end of the double linked list...
• Step 1 - Create a newNode with given value and newNode → next as NULL.
• Step 2 - Check whether list is Empty (head == NULL)
• Step 3 - If it is Empty, then assign NULL to newNode → previous and newNode to
head.
• Step 4 - If it is not Empty, then, define a node pointer temp and initialize with head.
• Step 5 - Keep moving the temp to its next node until it reaches to the last node in the
list (until temp → next is equal to NULL).
• Step 6 - Assign newNode to temp → next and temp to newNode → previous.
Department of IT 219
Link List(CO1)
Department of IT 220
Department of IT 221
Link List(CO1)
Deletion
In a double linked list, the deletion operation can be performed in three
ways as follows...
Department of IT 222
Link List(CO1)
We can use the following steps to delete a node from end of the double
linked list...
• Step 1 - Check whether list is Empty (head == NULL)
• Step 2 - If it is Empty, then display 'List is Empty!!! Deletion is not
possible' and terminate the function.
• Step 3 - If it is not Empty then, define a Node pointer 'temp' and
initialize with head.
• Step 4 - Check whether list has only one Node (temp → previous
and temp → next both are NULL)
• Step 5 - If it is TRUE, then assign NULL to head and delete temp.
And terminate from the function. (Setting Empty list condition)
• Step 6 - If it is FALSE, then keep moving temp until it reaches to
the last node in the list. (until temp → next is equal to NULL)
• Step 7 - Assign NULL to temp → previous → next and delete
temp.
Department of IT 224
Link List(CO1)
Department of IT 225
Link List(CO1)
Step 7 - If list has only one node and that is the node which is to be
deleted then set head to NULL and delete temp (free(temp)).
• Step 8 - If list contains multiple nodes, then check whether temp is
the first node in the list (temp == head).
• Step 9 - If temp is the first node, then move the head to the next node
(head = head → next), set head of previous to NULL (head →
previous = NULL) and delete temp.
• Step 10 - If temp is not the first node, then check whether it is the last
node in the list (temp → next == NULL).
• Step 11 - If temp is the last node then set temp of previous of next
to NULL (temp → previous → next = NULL) and delete temp
(free(temp)).
• Step 12 - If temp is not the first node and not the last node, then set
temp of previous of next to temp of next (temp → previous → next
= temp → next), temp of next of previous to temp of previous
(temp → next → previous = temp → previous) and delete temp
(free(temp)).
Department of IT 226
Link List(CO1)
Circular Doubly Linked List has properties of both doubly linked list and
circular linked list in which two consecutive elements are linked or connected
by previous and next pointer and the last node points to first node by next
pointer and also the first node points to last node by previous pointer.
Department of IT 228
Link List(CO1)
Advantages:
List can be traversed from both the directions i.e. from head to tail or
from tail to head.
Jumping from head to tail or from tail to head is done in constant time
O(1).
Circular Doubly Linked Lists are used for implementation of advanced
data structures like Fibonacci Heap.
Disadvantages
It takes slightly extra memory in each node to accommodate previous
pointer.
Lots of pointers involved while implementing or doing operations on a list.
So, pointers should be handled carefully otherwise data of the list may
get lost.
Department of IT 229
Link List(CO1)
Department of IT 230
Link List(CO1)
Department of IT 231
Link List(CO1)
Department of IT 232
Link List(CO1)
Department of IT 233
Link List(CO1)
Department of IT 234
Link List(CO1)
Department of IT 236
Link List(CO1)
Department of IT 238
Link List(CO1)
Department of IT 242
APPLICATIONS OF LINKED LIST
Department of IT 243
APPLICATIONS OF LINKED LIST
Department of IT 244
Introduction to Link List(CO1)
Polynomial
sPolynomials are the algebraic expressions which consist
of variables and coefficients.
Example -
10x2 + 26x, here 10 and 26 are coefficients and 2, 1 is its exponential value.
Department of IT 245
Link List(CO1)
•Polynomia
ls
• Array Implementation:
• p1(x) = 8x3 + 3x2 + 2x + 6
• p2(x) = 23x4 + 18x - 3
p1(x) p2(x)
6 2 3 8 -3 18 0 0 23
0 2 0 2 4
Index
represents
exponents
Department of IT 246
Link List(CO1)
6 2 0 0 -3 0 ………… 0 16
WASTE OF
SPACE!
Department of IT 247
Link List(CO1)
add(A[0..m-1], B[0..n01])
1) Create a sum array sum[] of size equal to maximum of 'm' and 'n'
2) Copy A[] to sum[].
3) Traverse array B[] and do following for every element B[i]
sum[i] = sum[i] + B[i]
4) Return sum[].
Department of IT 248
Link List(CO1)
Department of IT 249
Link List(CO1)
•Polynomial
Representation
7 6
1 9 Next (contains
pointer)
4 10 12 8
P
4 1 0
2 6
Department of IT 251
Link List(CO1)
Polynomials em 1 em 2
A(x) am 1 x am e0
x
2
Representation
struct polynode {
...
int coef;
int exp;
struct polynode * next;
a0 x
};
typedef struct polynode *polyptr;
Department of IT 252
Link List(CO1)
Department of IT 253
Introduction to Array(CO1)
Sparse Matrix
Any matrix is called as Sparse Matrix in C, if it contains more number of zeros.
The mathematical formula behind this C Sparse Matrix is:
T >= (m * n )/2 where T is total number of zeros.
Department of IT 254
Introduction to Array(CO1)
Department of IT 255
C Program that will convert 2D-representation to Sparse representation.
#include <stdio.h>
int main() // Defining final matrix
{ int sparse_matrix[4][5] = int matrix[3][size];
{ int k=0;
{0 , 0 , 7 , 0 , 9 }, // Computing final matrix
{0 , 0 , 5 , 7 , 0 }, for(int i=0; i<4; i++)
{0 , 0 , 0 , 0 , 0 }, {
{0 , 2 , 3 , 0 , 0 } for(int j=0; j<5; j++)
}; {
// size of matrix if(sparse_matrix[i][j]!=0)
int size = 0; {
for(int i=0; i<4; i++) matrix[0][k] = i;
{ matrix[1][k] = j;
for(int j=0; j<5; j++) matrix[2][k] = sparse_matrix[i][j];
{ k++;
if(sparse_matrix[i][j]!=0) }
{ }
size++; }
}
}
} Department of IT 256
Introduction to Array(CO1)
Department of IT 257
Introduction to Link List(CO1)
Department of IT 258
Introduction to Stack
Stack
Department of IT 259
Introduction to Stack
Department of IT 260
Introduction to Stack
Stack Operations
Top: Open end of the stack is called Top, From this end item can
be inserted.
POP: To put-off, get or remove some item from top of the stack is
the pop operation, We can POP only only from top of the stack.
Department of IT 261
Introduction to Stack
Stack Operations
Department of IT 262
Introduction to Stack
Stack Abstract Data Type
ADT Stack {
Data/Attributes/Values:
int size; Top Type items;
Functions/Operations:
CreateStack (int size); --create stack of size Void
Push(int n); - - if stack is not full
Type Pop(); - - if stack is not empty return top item
Int isEmpty(); - - return true if empty otherwise false
Int isFull(); - - return true if full otherwise false }
Department of IT 263
Introduction to Stack
Stack Example
Department of IT 264
Introduction to Stack
Implementation of Stack
•Using Array
Department of IT 265
Introduction to Stack
Department of IT 266
Introduction to Stack
Department of IT 267
Introduction to Stack
Department of IT 268
Introduction to Stack
Stack Implementation using Array using array
A stack can be implemented using array as follows...
Step 1 - Include all the header files which are used in the program
and define a constant 'SIZE' with specific value.
Step 2 - Declare all the functions used in stack implementation.
Step 3 - Create a one dimensional array with fixed size (int
stack[SIZE])
Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top
= -1)
Step 5 - In main method, display menu with list of operations and
make suitable function calls to perform operation selected by the
user on the stack. Department of IT 269
Introduction to Stack
push(value) - Inserting value into the stack using array
In a stack, push() is a function used to insert an element into the
stack. In a stack, the new element is always inserted
at top position. Push function takes one integer value as
parameter and inserts that value into the stack. We can use the
following steps to push an element on to the stack...
Step 2 - If it is EMPTY, then display "Stack is EMPTY!!! Deletion
is not possible!!!" and terminate the function.
Department of IT 271
Introduction to Stack
Step 2 - If it is EMPTY, then display "Stack is EMPTY!!!" and
terminate the function.
with top. Display stack[i] value and decrement i value by one (i--).
The major problem with the stack implemented using an array is, it
works only for a fixed number of data values.
Stack implemented using linked list works for the variable size of
data.
Department of IT 273
Introduction to Stack
Stack Implementation using Link List
In linked list implementation of a stack, every new element is inserted as 'top' element.
That means every newly inserted element is pointed by 'top’.
Whenever we want to remove an element from the stack, simply remove the node which
is pointed by 'top' by moving 'top' to its previous node in the list. The next field of the
first element must be always NULL.
Department of IT 274
Introduction to Stack
Stack Implementation using Link List
Step 1 - Include all the header files which are used in the program.
Step 2 - Define a 'Node' structure with two members data and next.
Department of IT 275
Introduction to Stack
We can use the following steps to insert a new node into the
stack...
Step 1 - Create a newNode with given value.
Step 3 - If it is Empty, then set newNode → next = NULL
.
Step 4 - If it is Not Empty, then set newNode → next = top.
Department of IT 276
Introduction to Stack
pop() - Deleting an Element from a Stack using
Link List
We can use the following steps to delete a node from the stack...
Department of IT 278
Introduction to Stack
Stack Application
Reversing a string: To reverse a string we can use following
algorithm.
1.Given the sting and a stack
2.While there is not end of string, do the following.
3.Read a character form the string
4.Push it on the stack
5.End while
6.Re-initialize string position
7.While stack is not Empty, do the following.
8.Pop a character from the stack
9.Insert the character popped into next position in string.
10.End While
Department of IT
Introduction to Stack
Reverse String...
Reverse String...
What is an Expression?
In any programming language, if we want to perform any calculation or to frame
a condition etc., we use a set of symbols to perform the task. These set of symbols
makes an expression.
An expression can be defined as follows...
Operands are the values on which the operators can perform the task. Here
operand can be a direct value or variable or address of memory location
Department of IT 282
Introduction to Stack
Expression Types
Based on the operator position, expressions are divided into THREE
types. They are as follows...
1.Infix Expression
2.Postfix Expression
3.Prefix Expression
Department of IT 283
Introduction to Stack
+AB
Postfix Expression: An expression in
operator follows its two operands is called a postfix expression.
which
AB+
Department of IT 284
Introduction to Stack
Department of IT 285
Introduction to Stack
C language operators Precedence and Associativity
Department of IT 286
Introduction to Stack
Department of IT 287
Introduction to Stack
Q1. Convert the given infix expression 2*3/(2-1)+5*(4-1) to postfix
expression
Sol.
a. 2*3/(2-1)+5*(4-1)
b. (2*3)/(2-1)+5*(4-1)
c. ((2*3)/(2-1))+(5*(4-1))
d. ((2*3)/(2-1))+(5*(4-1))
e. ((2*3)/(2-1))+(5*(4-1))
f. (((2*3)/(2-1))+(5*(4-1)))
Department of IT 288
Introduction to Stack
2. Convert each bracket in postfix expression one by one
a. (((2*3)/(2-1))+(5*(4-1)))
b. (((23*)/(2-1))+(5*(4-1)))
c. (((23*)/(21-))+(5*(4-1)))
d. (((23*)/(21-))+(5*(41-)))
e. (((23*)(21-)/)+(5*(41-)))
f. (((23*)(21-)/)+(5(41-)*))
f. (((23*)(21-)/)(5(41-)*)+)
Ans. 23*21-/541-*+
H.W
1. A+B*C-D^E^F
Department of IT 289
Introduction to Stack
Department of IT 290
291 Introduction to Stack
Exercise:
1. Infix ( (A * B) + (C / D) ) to Prefix
2.Infix ((A * (B + C) ) / D) to Prefix
3.Infix (A * (B + (C / D) ) ) to Prefix
Department of IT
Introduction to Stack
Infix to Postfix using Stack (Convert in Reverse Polish Notation)
1. Examine the given Input Sequence.
2. If it is operand output it.
3. If it is ‘(‘ push it on the stack.
4. If it is an operator and
a) If the stack is empty push it on the stack.
b) If the top of the stack is ‘(‘ then push it on to the stack.
c) If it has higher priority than top of the stack, push it on to the
stack.
d) Otherwise pop operator from the stack and output it. And go
to step 4.
5. If it is ‘)’ then pop of the operators from the stack and output
them until ‘(‘ is encountered.
6. If there are more input sequence then go to step 1.
7. If there are no more input sequence, pop of remaining
elements from the stack and output them.
Department of IT 292
Introduction to Stack
Department of IT 293
Introduction to Stack
Department of IT 294
Introduction to Stack
Infix to Prefix using Stack (Convert in Polish Notation)
1.First, reverse the given infix expression.
2.Scan the characters one by one.
3.If the character is an operand, print it .
4.If the character is a closing parenthesis, then push it to the stack.
5.If the character is an opening parenthesis, pop the elements in the
stack until we find the corresponding closing parenthesis.
6.If the character scanned is an operator
•If the operator has precedence greater than or equal to the top of the
stack, push the operator to the stack.
•If the operator has precedence lesser than the top of the stack, pop the
operator and output it to the prefix notation output and then check the
above condition again with the new top of the stack.
7. After all the characters are scanned, reverse the prefix notation
output
Department of IT 295
Introduction to Stack
Department of IT 296
Introduction to Stack
Algorithm for Prefix
•Step 1: Reverse the infix string. Note that while reversing the string
you must interchange left and right parentheses.
•Step 2: Obtain the postfix expression of the infix expression Step 1.
•Step 3: Reverse the postfix expression to get the prefix expression
This is how you convert manually for theory question in the exam
Input String - Infix – ((a/b)+c)-(d+(e*f))
1.String after reversal – ))f*e(+d(-)c+)b/a((
2.String after interchanging right and left parenthesis – ((f*e)+d)-
(c+(b/a))
3.Apply postfix
4.Reverse Postfix Expression (Given After the table below)
Department of IT 297
Introduction to Stack
Infix – ((a/b)+c)-(d+(e*f)) ))f*e(+d(-)c+)b/a(( ((f*e)+d)-(c+(b/a))
Department of IT 299
Introduction to Stack
Department of IT 300
Introduction to Stack
Department of IT 301
Introduction to Stack
Tower of Hanoi Problem
Department of IT 30
2
Introduction to Stack
Tower of Hanoi Problem
The objective of the puzzle is to move the entire stack to another rod,
obeying the following simple rules:
2) Each move consists of taking the upper disk from one of the stacks
and placing it on top of another stack i.e. a disk can only be moved if it
is the uppermost disk on a stack.
Department of IT 30
3
Introduction to Stack
Department of IT 30
4
Introduction to Stack
Department of IT 30
5
Introduction to Stack
Department of IT 30
6
Introduction to Stack
Department of IT 307
Queue
Queue
Department of IT 308
Queue
Implementation of Queue
1. Using Array
2. Using Link List
Application of Queue
•Queue is used to implement many algorithms like Breadth First Search (BFS), etc.
•It can be also used by an operating system when it has to schedule jobs with equal priority
•Customers calling a call center are kept in queues when they wait for someone to pick up the
calls
Department of IT 309
Queue
Insertion in Queue using Array
10
A[0] A[1] A[2] A[3] A[4]
F=R=0
10 20
A[0] A[1] A[2] A[3] A[4]
F=0 R=1
Department of IT 310
Queue
Department of IT 311
Queue
Operations on Queue
Insertion:
Algorithm:
Department of IT 312
Queue
10 20
A[0] A[1] A[2] A[3] A[4]
F=0 R=1
20
A[0] A[1] A[2] A[3] A[4]
F=R=1
Department of IT 313
Queue
10 20
A[0] A[1] A[2] A[3] A[4]
F=0 R=1
20
A[0] A[1] A[2] A[3] A[4]
F=R=1
Department of IT 314
Queue
Operations on Queue
Deletion:
Algorithm:
Department of IT 315
Queue
Department of IT 316
Queue using Linked List
Department of IT 317
Queue Operation (Insertion)
Insertion Operation
Step 1: Allocate the space for the new node PTR
Step 2: SET PTR -> DATA = VAL
Step 3: IF FRONT = NULL
SET FRONT = REAR = PTR
SET FRONT -> NEXT = REAR -> NEXT = NULL
ELSE
SET REAR -> NEXT = PTR
SET REAR = PTR
SET REAR -> NEXT = NULL
[END OF IF]
Step 4: END
Department of IT 318
C Function
void insert(struct node *ptr, int item; ) {
Department of IT 320
C Function
void delete (struct node *ptr)
{
if(front == NULL)
{
printf("\nUNDERFLOW\n");
return;
}
else
{
ptr = front;
front = front -> next;
free(ptr);
}
}
Department of IT 321
Queue
Types Of Queue
1. Circular Queue
2. Priority Queue
3. Deque
4. Multiple Queue
Department of IT 322
Queue
• Problem:
– Wastage of memory in standard queue in DEQUEUE
operation
Department of IT 323
Queue
Department of IT 325
Queue
Insertion in circular queue
Step 1 - Check whether Circular queue is FULL. Front ==
(Rear+1)%Max
Department of IT 326
Queue
Deletion in circular queue
Step 1 - Check whether queue is EMPTY. (front == -1)
Department of IT 327
Queue
Application of Circular Queue
Traffic light functioning is the best example for circular queues. The colors
in the traffic light follow a circular pattern.
Department of IT 328
Queue
We can use the following steps to display the elements of a circular queue...
Department of IT 329
Queue
Types of Deque
Department of IT 331
Queue
Department of IT 332
Queue
Department of IT 333
Operations on Deque
The following are the operations applied on deque:
• Insert at front
• Delete from end
• insert at rear
• delete from rear
Other than insertion and deletion, we can also perform peek operation in deque.
Through peek operation, we can get the front and the rear element of the
dequeue.
The deque can be implemented using two data structures, i.e., circular array,
and doubly linked list.
Department of IT 334
Deque Using Circular Array
Insert At Right
void insert_right()
{
int added_item;
if((left == 0 && right == MAX-1) || (left == right+1))
{ printf("Queue Overflow\n");
return;}
if (left == -1) /* if queue is initially empty */
{ left = 0;
right = 0;}
else
if(right == MAX-1) /*right is at last position of queue */
right = 0;
else
right = right+1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[right] = added_item ;
}
Department of IT 335
Deque Using Circular Array
Insert At Left
void insert_left()
{
int added_item;
if((left == 0 && right == MAX-1) || (left == right+1))
{ printf("Queue Overflow \n");
return; }
if (left == -1)/*If queue is initially empty*/
{
left = 0;
right = 0; }
else
if(left== 0)
left=MAX-1;
else
left=left-1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[left] = added_item ;
} Department of IT 336
Deque Using Circular Array
Delete from Left
void delete_left()
{
if (left == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",deque_arr[left]);
if(left == right) /*Queue has only one element */
{ left = -1;
right=-1;
}
else
if(left == MAX-1)
left = 0;
else
left = left+1;
} Department of IT 337
Deque Using Circular Array
Delete from right
void delete_right()
{
if (left == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",deque_arr[right]);
if(left == right) /*queue has only one element*/
{ left = -1;
right=-1; }
else
if(right == 0)
right=MAX-1;
else
right=right-1;
}
Department of IT 338
Deque Using Doubly Link List
Department of IT 339
Deque Using Doubly Link List
Operations
insertFront() : Adds an item at the front of Deque.
insertRear() : Adds an item at the rear of Deque.
deleteFront() : Deletes an item from front of Deque.
deleteRear() : Deletes an item from rear of Deque.
getFront() : Gets the front item from queue.
getRear() : Gets the last item from queue.
isEmpty() : Checks whether Deque is empty or not.
size() : Gets number of elements in Deque.
erase() : Deletes all the elements from Deque.
Department of IT 340
Insertion at Front end
Working :
Declare two pointers front and rear of type Node,
where Node represents the structure of a node of a doubly linked
list. Initialize both of them with value NULL.
Insertion at Front end :
1. Allocate space for a newNode of doubly linked list.
2. IF newNode == NULL, then
3. print "Overflow"
4. ELSE
5. IF front == NULL, then
6. rear = front = newNode
7. ELSE
8. newNode->next = front
9. front->prev = newNode
10. front = newNode Department of IT 341
Insertion at Rear end
1. Allocate space for a newNode of doubly linked list.
2. IF newNode == NULL, then
3. print "Overflow"
4. ELSE
5. IF rear == NULL, then
6. front = rear = newNode
7. ELSE
8. newNode->prev = rear
9. rear->next = newNode
10. rear = newNode
Department of IT 342
Deletion from Front end :
1. IF front == NULL
2. print "Underflow"
3. ELSE
4. Initialize temp = front
5. front = front->next
6. IF front == NULL
7. rear = NULL
8. ELSE
9. front->prev = NULL
10 Deallocate space for temp
Department of IT 343
Deletion from Rear end
1. IF front == NULL
2. print "Underflow"
3. ELSE
4. Initialize temp = rear
5. rear = rear->prev
6. IF rear == NULL
7. front = NULL
8. ELSE
9. rear->next = NULL
10 Deallocate space for temp
Department of IT 344
Queue
Application of Deque –
Deque is a Double Ended Queue where operations(Add/Remove) can
be made on both ends of the queue.
1.A web browser's history. Recently visited URLs are added to the
front of the deque, and the URL at the back of the deque is removed
after some specified number of insertions at the front.
3.Have you see moneyControl App, it will show the stocks you last
visited, it will remove the stocks after some time and will add the
latest ones.
Department of IT 345
Queue
Priority Queue
Department of IT 346
Priority Queue
Consider an Example
We have a priority queue that contains the following values:
1, 3, 4, 8, 14, 22
All the values are arranged in ascending order of their priority. Now, we will
observe how the priority queue will look after performing the following
operations:
poll(): This function will remove the highest priority element from the priority
queue. In the above priority queue, the '1' element has the highest priority, so it
will be removed from the priority queue.
add(2): This function will insert '2' element in a priority queue. As 2 is the
smallest element among all the numbers so it will obtain the highest priority.
poll(): It will remove '2' element from the priority queue as it has the highest
priority queue.
add(5): It will insert 5 element after 4 as 5 is larger than 4 and lesser than 8, so it
will obtain the third highest priority in a priority queue.
Department of IT 347
Queue
Department of IT 348
Queue
Insertion Operation:
•While inserting elements in priority queue we will add it at the
appropriate position depending on its priority
Department of IT 349
Queue
Department of IT 350
Queue
Deletion Operation:
•While deletion, the element at the front
is always deleted.
DATA PRIORTY
NUMBER
B 1
E 2
D 3
A 5
G 6
F 8
Department of IT 351
Queue
5. Priority queues are used in operating system for load balancing and interrupt
handling.
7. In traffic light, depending upon the traffic, the colors will be given priority.
Department of IT 352
Queue
• https://drive.google.com/open?id=1z-mqjdEQ3FPjgr-Vyjn1k6MWZEjW
lRyi
Department of IT 353
Faculty Video Links, Youtube & NPTEL
Video Links and Online Courses Details
Self Made Video Link:
Youtube/other Video Links
https://www.youtube.com/watch?v=PGWZUgzDMYI&list=PLBF3763AF2E1
C572F&index=3
https://www.youtube.com/watch?v=zp6pBNbUB2U&list=PLdo5W4Nhv31bb
KJzrsKfMpo_grxuLl8LU&index=41
https://www.youtube.com/watch?v=UpvDOm3prfI
Department of IT 354
Daily Quiz
Department of IT 355
Weekly Assignment
Q5. The initial configuration of a queue is p,q,r,s (‘p’ is in the front end
). To get the configuration s,r,q,p, how many minimum dequeue and
enqueue are required?
Department of IT 356
MCQ s
Department of IT 357
MCQ s
3. In a stack, if a user tries to remove an element from empty stack it is
called _________
a) Underflow
b) Empty collection
c) Overflow
d) Garbage Collection
4. Pushing an element into stack already having five elements and stack
size of 5, then stack becomes
a) Overflow
b) Crash
c) Underflow
d) User flow
Department of IT 358
MCQ s
5. Which of the following applications may use a stack?
a) A parentheses balancing program
b) Tracking of local variables at run time
c) Compiler Syntax Analyzer
d) Data Transfer between two asynchronous process
Department of IT 359
MCQ s
Department of IT 360
MCQ s
9. If the elements “A”, “B”, “C” and “D” are placed in a queue and are
deleted one at a time, in what order will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
Department of IT 361
Expected Questions for University Exam
Department of IT 362
Expected Questions for University Exam
Q7. Convert the following infix expression into postfix expression:
B-C/D+A*(F-G/H).
Q8.Write a program in C to compute the factorial of given number
recursively.
Q9.Write a Program in C to implement all operations of a Stack using array.
Q10.Define Dequeue.
Q11. Write the syntax to check whether a given circular queue is full or
empty?
Q12. What is Recursion? Give disadvantages of recursion.
Q13.Explain Tower of Hanoi problem and write a recursive algorithm to
solve it.
Q14. Explain how a circular queue can be implemented using arrays. Write
all functions for circular queue operations.
Department of IT 363
Daily Quiz
Q1. What is the output of following function for start pointing to first node of
following linked list? 1->2->3->4->5->6
void fun(struct node* start)
{
if(start == NULL)
return;
printf("%d ", start->data);
if(start->next != NULL )
fun(start->next->next);
printf("%d ", start->data);
}
Q3. Describe what is Node in link list? And name the types of Linked Lists?
Q4. Mention what is the difference between Linear Array and Linked List?
Q7. Mention what is the difference between singly and doubly linked lists?
Q9. Mention how to insert a new node in linked list where free node will be
available?
Department of IT 365
Weekly Assignment
Department of IT 366
Weekly Assignment
Q5. Write a program for printing the following in a given linked list:
a. maximum b. minim
Q6. Print the sum of all even numbers stored in a circular linked list.
Q7. Take N numbers as input from the user and create a doubly linked list.
Q 10. Write the C Program to add all even number in the list.
Department of IT 367
MCQ s
1. Assume that reference of head of following doubly linked list is passed to above
function 1 <--> 2 <--> 3 <--> 4 <--> 5 <-->6. What should be the modified linked list
after the function call?
if(temp != NULL )
*head_ref = temp->prev;
}
Department of IT 368
MCQ s
2. The following function reverse() is supposed to reverse a singly linked list. There is one line missing at the end.
struct node
{
int data;
struct node* next;
};
/* head_ref is a double pointer which points to head (or start) pointer of linked list */
static void reverse(struct node** head_ref)
{
struct node* prev = NULL;
struct node* current = *head_ref;
struct node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
/*ADD A STATEMENT HERE*/
}
What should be added in place of "/*ADD A STATEMENT HERE*/", so that the function correctly reverses a
linked list.
Department of IT 369
MCQ s
3. The following C function takes a simply-linked list as input argument. It modifies the list by
moving the last element to the front of the list and returns the modified list. Some part of the code is
left blank. Choose the correct alternative to replace the blank line.
typedef struct node
{
int value;
struct node *next;
}Node;
4. In the worst case, the number of comparisons needed to search a singly linked
list of length n for a given element is (GATE CS 2002)
A log 2 n
B n/2
C log 2 n – 1
Dn
5. You are given pointers to first and last nodes of a singly linked list, which of
the following operations are dependent on the length of the linked list?
A Delete the first element
B Insert a new element as a first element
C Delete the last element of the list
D Add a new element at the end of the list
Department of IT 371
MCQ s
Department of IT 372
MCQ s
Department of IT 373
Expected Questions for University Exam
Q1. Write a program in c to delete a specific element in single linked list. Double linked
list takes more space than single linked list for storing one extra address. Under what
condition, could a double linked list more beneficial than single linked list.
Q2. What is a doubly linked list? How is it different from the single linked list?
Q3. What are the advantages and disadvantages of array over linked list?
Q4 . Write a program to implement linear linked list, showing all the operations that
can be performed on a linked list.
Q5. Implement Doubly Circular link list and insert an element at a given position in the
doubly circular link list.
Department of IT 374
References
Department of IT 375
MCQ
Q2. Which of the following operations is not O(1) for an array of sorted
data. You may assume that array elements are distinct.
A. Find the ith largest element
B. Delete an element
C. Find the ith smallest element
D. All of the above
Department of IT 376
MCQ
Department of IT 377
MCQ
int main()
{
int a[] = {1, 2, 3, 4, 5, 6};
int *ptr = (int*)(&a+1);
printf("%d ", *(ptr-1) );
return 0;
}
Department of IT 378
MCQ
#include <stdio.h>
#define SIZE(arr) sizeof(arr) / sizeof(*arr);
void fun(int* arr, int n)
{
int i;
*arr += *(arr + n - 1) += 10;
}
void printArr(int* arr, int n)
{
int i;
for(i = 0; i < n; ++i)
printf("%d ", arr[i]);
}
int main()
{
int arr[] = {10, 20, 30};
int size = SIZE(arr);
fun(arr, size);
printArr(arr, size);
return 0; Department of IT 379
}
MCQ
int main()
{
int i;
int arr[5] = {1};
for (i = 0; i < 5; i++)
printf("%d ", arr[i]);
return 0;
}
Department of IT 380
MCQ
Q9. Consider the following C-function in which a[n] and b[m] are two sorted
integer arrays and c[n + m] be another integer array.
void xyz(int a[], int b [], int c[])
{
int i, j, k;
i = j = k = O;
while ((i<n) && (j<m))
if (a[i] < b[j]) c[k++] = a[i++];
else c[k++] = b[j++];
}
Which of the following condition(s) hold(s) after the termination of the while loop?
Department of IT 381
Summary
Department of IT 382
References
Department of IT 383
Thank you
Department of IT 384