SlideShare a Scribd company logo
1 of 87
UNIT-1
CS-303
DATA STRUCTURE
DATA STRUCTURE DEFINITION
• Whenever we want to work with a large amount of
data, then organizing that data is very important.
• If that data is not organized effectively, it is very
difficult to perform any task on that data.
• If it is organized effectively then any operation can
be performed easily on that data.
• Data structure is a method of organizing a large
amount of data more efficiently so that any
operation on that data becomes easy
TYPES OF DATA STRUCTURE
Primitive Data Structures
• These are the structures which are supported at the
machine level, they can be used to make non-
primitive data structures.
• Examples: Integer, float, character, pointers.
• The pointers, however don’t hold a data value,
instead, they hold memory addresses of the data
values. These are also called the reference data
types.
Non Primitive Data Structures
• The non-primitive data structures cannot be
performed without the primitive data structures.
Although, they too are provided by the system itself
yet they are derived data structures and cannot be
formed without using the primitive data structures.
• The Non-primitive data structures are further divided
into the following categories:
1. Arrays
• Arrays are a homogeneous and contiguous collection
of same data types.
• They have a static memory allocation technique,
which means, if memory space is allocated for once,
it cannot be changed during runtime.
• If we do not know the memory to be allocated in
advance then array can lead to wastage of memory.
2. Files
• A file is a collection of records.
• The file data structure is primarily used for managing
large amounts of data which is not in the primary
storage of the system.
• The files help us to process, manage, access and
retrieve or basically work with such data, easily.
3.Lists
• The lists support dynamic memory allocation. The
memory space allocated, can be changed at run time
also. The lists are of two types:
• a) Linear Lists
• The linear lists are those which have the elements
stored in a sequential order. The insertions and
deletions are easier in the lists. They are divided into
two types:
Stacks
Stacks
Stacks
• The stack follows a “LIFO” technique for storing and
retrieving elements. The element which is stored at
the end will be the first one to be retrieved from the
stack. The stack has the following primary functions:
– Push(): To insert an element in the stack.
– Pop(): To remove an element from the stack.
Queues
Queues
• The queues follow “FIFO” mechanism for storing and
retrieving elements. The elements which are stored
first into the queue will only be the first elements to
be removed out from the queue.
• The “ENQUEUE” operation is used to insert an
element into the queue
• The “DEQUEUE” operation is used to remove an
element from the queue.
Non Linear Lists
The non linear lists do not have elements stored in a
certain manner. These are:
• Graphs: The Graph data structure is used to
represent a network.
• It comprises of vertices and edges (to connect the
vertices). The graphs are very useful when it comes
to study a network.
• Trees: Tree data structure comprises of nodes
connected in a particular arrangement and they
make search operations on the data items easy. The
tree data structures consists of a root node which is
further divided into various child nodes and so on.
Tree
Graph
Need of using Array
• In computer programming, the most of the cases
requires to store the large number of data of similar
type.
• To store such amount of data, we need to define a
large number of variables.
• It would be very difficult to remember names of all
the variables while writing the programs. Instead of
naming all the variables with a different name, it is
better to define an array and store all the elements
into it.
Example
• We have marks of a student in six different
subjects. The problem intends to calculate the
average of all the marks of the student.
Program without Array
#include <stdio.h>
void main ()
{
int marks_1 = 56, marks_2 = 78, marks_3 = 88,
marks_4 = 76, marks_5 = 56, marks_6 = 89;
float avg = (marks_1 + marks_2 + marks_3 + marks_4
+ marks_5 +marks_6) / 6 ;
printf(avg);
}
Array
• Arrays are defined as the collection of similar type of
data items stored at contiguous memory locations.
• Arrays are the derived data type in C programming
language which can store the primitive type of data
such as int, char, double, float, etc.
• Array is the simplest data structure where each data
element can be randomly accessed by using its index
number.
Array
• For example, if we want to store the marks of a
student in 6 subjects, then we don't need to define
different variable for the marks in different subject.
instead of that, we can define an array which can
store the marks in each subject at a the contiguous
memory locations.
How to declare an array?
Syntax:- data_type array_name[SIZE];
data_type is a valid C data type that must be common
to all array elements.
array_name is name given to array and must be a valid
C identifier.
SIZE is a constant value that defines array maximum
capacity.
Example :- int marks[5];
How to initialize an array?
There are two ways to initialize an array.
Static array initialization - Initializes all elements of
array during its declaration.
Dynamic array initialization - The declared array is
initialized some time later during execution of
program.
Static initialization of array
We define value of all array elements within a pair of
curly braces { and } during its declaration.
Values are separated using comma , and must be of
same type.
Example of static array initialization
int marks[500] = {90, 86, 89, 76, 91};
int marks[] = {90, 86, 89, 76, 91};
Dynamic initialization of array
You can assign values to an array element dynamically
during execution of program.
First declare array with a fixed size. Then use the
following syntax to assign values to an element
dynamically.
array_name[index] = some value;
Example to initialize an array dynamically
marks[0] = 90
Cin>>marks[1];
Basic Operations on 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.
• Update − Updates an element at the given index.
Address Calculation in 1D Array
Array of an element of an array say “A[ I ]” is calculated
using the following formula:
Address of A [ I ] = B + W * ( I – LB )
Where,
B = Base address
W = Storage Size of one element stored in the array
(in byte)
I = Subscript of element whose address is to be
found
LB = Lower limit / Lower Bound of subscript, if not
specified assume 0 (zero)
Example:
Given the base address of an
array A[900…..1900] as 1400 and size of
each element is 4 bytes in the memory. Find
the address of B[1100] & B[1475].
A[I]=1400+4*(1475-900)
Example:
Solution:
The given values are: B = 1020, LB = 1300, W =
2, I = 1700
Address of A [ I ] = B + W * ( I – LB )
= 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800
= 1820 [Ans]
Properties of the Array
• Each element is of same data type and carries a same
size i.e. int = 2 bytes.
• Elements of the array are stored at contiguous
memory locations
• Elements of the array can be randomly accessed
since we can calculate the address of each element
of the array with the given base address and the size
of data element.
Advantage of Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can
retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we
need a few lines of code only.
4) Random Access: We can access any element
randomly using the array.
Address Calculation in
2D Array
• While storing the elements of a 2-D array in memory,
these are allocated contiguous memory locations.
• Therefore, a 2-D array must be linearized so as to
enable their storage.
• There are two alternatives to achieve linearization:
Row-Major and Column-Major.
2D Array
2D Array
Address Calculation Formula
Row Major System:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
Column Major System:
Address of A [ I ][ J ] = B + W * [( I – Lr ) + M * ( J – Lc )]
Where
B=Base Address W=Size of Each Element
N=No of Columns M=No of Rows
Address Calculation Formula
Lr =Lower Bound of row
Lc = Lower Bound of Column
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
Number of rows (M) will be calculated as = (Ur – Lr) + 1
Number of columns (N) will be calculated as = (Uc – Lc) + 1
LR =FIRST ROW FIRST VALUE
UR=FIRST ROW LAST VALUE
UC=LAST COLUMN LAST VALUE
LC=FIRST COLUMN LAST VALUE
Consider the linear array AAA(5:50),BBB(-5:10)
and CCC(18)
A) find the number of element in each array
B) suppose Base (AAA)=300 and w=4 words per
memory cell for AAA.find the address of
AAA[15],AAA[35] and AAA[55]
Example
• An array X [-15……….10, 15……………40] requires one
byte of storage. If beginning location is 1500
determine the location of X [15][20].
Solution
As you see here the number of rows and columns are
not given in the question.
So they are calculated as:
Number or rows say M = (Ur – Lr) + 1
= [10 – (- 15)] +1=26
Number or columns say N = (Uc – Lc) + 1
= [40 – 15)] +1 = 26
Solution
Column Major Wise Calculation of above equation
The given values are:
B = 1500 W = 1 byte I = 15
J = 20 Lr = -15 Lc = 15
M = 26
Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ]
= 1500 + 1 * [(15 – (-15)) + 26 * (20 – 15)]
= 1500 + 1 * [30 + 26 * 5] = 1500 + 1 * [160]
= 1660 [Ans]
Solution
Row Major Wise Calculation of above equation
The given values are:
B = 1500 W = 1 byte I = 15
J = 20 Lr = -15 Lc = 15
N = 26
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
= 1500 + 1* [26 * (15 – (-15))) + (20 – 15)]
= 1500 + 1 * [26 * 30 + 5]
= 1500 + 1 * [780 + 5]
= 1500 + 785 = 2285 [Ans]
Example 2
• Each element of an array a[-20….20,10….35] requires
1 byte of storage .if the array is column major
implemented and the beginning of the array is at
location 500(base address).determine the address of
elementa[0,30]
Solution
Column Major Wise Calculation of above equation
The given values are:
B = 500 W = 1 byte I = 0
J = 30 Lr = -20 Lc = 10
Ur=20 Uc=35
M=Ur-Lr+1=20-(-20)+1=41
Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ]
= 500 + 1 * [(0 – (-20)) + 41 * (30 – 10)]
= 500 + 1 * [20+41*20] = 500 + 1 * [840]
= 1340 [Ans]
Solution
Row Major Wise Calculation of above equation
The given values are:
B = 500 W = 1 byte I = 0
J = 30 Lr = -20 Lc = 10
Ur=20 Uc=35
N=Uc-Lc+1=35-10+1=26
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
= 500 + 1* [26 * (0 – (-20))) + (30 – 10)]
= 500 + 1 * [26 * 20 + 20]
= 500 + 1 * [540]
= 500 + 540 = 1040 [Ans]
Example 3
• Calculate the address of X[4,3]in a 2 d array
X[1….5,1….4] stored in row major order in main
memory .Assume the base address to be 1000 and
that each element requires 4 word of storage.
Solution
Column Major Wise Calculation of above equation
The given values are:
B = 1000 W = 4 byte I = 4
J = 3 Lr = 1 Lc =1
Ur=5 Uc=4
M=Ur-Lr+1=5-1+1=5
Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ]
= 1000 + 4 * [(4– (1)) + 5 * (3 – 1)]
= 1000 + 4 * [3+5*2] = 1000 + 4 * [13]
= 1052 [Ans]
Solution
Row Major Wise Calculation of above equation
The given values are:
B = 1000 W = 4 byte I = 4
J = 3 Lr = 1 Lc =1
Ur=5 Uc=4
N=Uc-Lc+1=4-1+1=4
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
= 1000 + 4* [4 * (4– (1))) + (3 – 1)]
= 1000 + 4 * [4 * 3 + 2]
= 1000 + 4 * [14]
= 1000 + 56 = 1056 [Ans]
Example 4
• Each element of an array DATA[20][50]
requires 4 bytes of storage. Base Address of
DATA is 2000,determine the location of
DATA[10][10]when the array is stored as
• 1) Row Major
• 2) Column Major
Example 5
• A two dimensional array X[5][4] is stored a row wise
in the memory .The first element of the array is
stored at location 80 .find the memory location of
X[3][2] if the each elements of array requires 4
memory locations.
Algorithm
 Algorithm is a step-by-step procedure, which defines
a set of instructions to be executed in a certain order
to get the desired output.
 An algorithm is a sequence of unambiguous
instructions used for solving a problem, which can be
implemented (as a program) on a computer.
 Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be
implemented in more than one programming
language.
Algorithm
• Algorithms are used to convert our problem solution
into step by step statements.
• These statements can be converted into computer
programming instructions which form a program.
• This program is executed by a computer to produce
a solution.
• Here, the program takes required data as input,
processes data according to the program instructions
and finally produces a result as shown in the
following picture.
Algorithm
Specifications of Algorithms
• Input - Every algorithm must take zero or more number
of input values from external.
• Output - Every algorithm must produce an output as
result.
• Definiteness - Every statement/instruction in an
algorithm must be clear and unambiguous (only one
interpretation).
• Finiteness - For all different cases, the algorithm must
produce result within a finite number of steps.
• Effectiveness - Every instruction must be basic enough
to be carried out and it also must be feasible.
Performance Analysis of an algorithm
• If we want to go from city "A" to city "B",
there can be many ways of doing this. We can
go by flight, by bus, by train and also by
bicycle.
• Depending on the availability and
convenience, we choose the one which suits
us.
• Similarly, in computer science, there are
multiple algorithms to solve a problem.
Performance Analysis of an algorithm
• When we have more than one algorithm to solve
a problem, we need to select the best one.
• Performance analysis helps us to select the best
algorithm from multiple algorithms to solve a
problem.
When there are multiple alternative algorithms to
solve a problem, we analyze them and pick the
one which is best suitable for our requirements.
Performance analysis of an algorithm
• Performance analysis of an algorithm is the process
of calculating space and time required by that
algorithm
• Space required to complete the task of that
algorithm (Space Complexity). It includes program
space and data space
• Time required to complete the task of that algorithm
(Time Complexity)
Space complexity
• Total amount of computer memory required by an
algorithm to complete its execution is called as space
complexity
Example 1
int square(int a)
{
return a*a;
}
Space complexity
• In the above piece of code, it requires 2 bytes of
memory to store variable 'a' and another 2 bytes of
memory is used for return value.
• That means, totally it requires 4 bytes of memory to
complete its execution. And this 4 bytes of memory
is fixed for any input value of 'a'. This space
complexity is said to be Constant Space Complexity.
Example 2
int sum(int A[ ], int n)
{
int sum = 0, i;
for(i = 0; i < n; i++)
sum = sum + A[i];
return sum;
}
Example 2 Solution
• In the above piece of code it requires
'n*2' bytes of memory to store array variable 'a[ ]'
2 bytes of memory for integer parameter 'n'
4 bytes of memory for local integer variables 'sum' and
'i' (2 bytes each)
2 bytes of memory for return value.
That means, totally it requires '2n+8' bytes of
memory to complete its execution. Here, the total
amount of memory required depends on the value of
'n'. As 'n' value increases the space required also
increases proportionately. This type of space
complexity is said to be Linear Space Complexity.
Time complexity
• The time complexity of an algorithm is the total
amount of time required by an algorithm to
complete its execution.
Example 1
int square(int a)
{
return a*a;
}
Time complexity
• In the above sample code, it requires 1 unit of
time to calculate a+b and 1 unit of time to return
the value.
• That means, totally it takes 2 units of time to
complete its execution.
• And it does not change based on the input values
of a and b. That means for all input values, it
requires the same amount of time i.e. 2 units.
• If any program requires a fixed amount of time
for all input values then its time complexity is said
to be Constant Time Complexity.
Dynamic Memory Allocation
.
Function Purpose
malloc Allocates the memory of requested size and
returns the pointer to the first byte of
allocated space
calloc Allocates the space for elements of an
array. Initializes the elements to zero and
returns a pointer to the memory.
realloc It is used to modify the size of previously
allocated memory space.
Free Frees or empties the previously allocated
memory space
The malloc Function
• The malloc() function stands for memory allocation.
• It is a function which is used to allocate a block of
memory dynamically.
• It reserves memory space of specified size and
returns the null pointer pointing to the memory
location.
• The pointer returned is usually of type void. It means
that we can assign malloc function to any pointer.
• Syntax
• ptr = (cast_type *) malloc (byte_size);
The malloc Function
• Here,
• ptr is a pointer of cast_type.
• The malloc function returns a pointer to the
allocated memory of byte_size.
• Example: ptr = (int *) malloc (50)
• When this statement is successfully executed, a
memory space of 50 bytes is reserved.
• The address of the first byte of reserved space is
assigned to the pointer ptr of type int.
The calloc Function
• The calloc function stands for contiguous allocation.
• This function is used to allocate multiple blocks of
memory.
• It is a dynamic memory allocation function which is
used to allocate the memory to complex data
structures such as arrays and structures.
• Malloc function is used to allocate a single block of
memory space while the calloc function is used to
allocate multiple blocks of memory space.
The calloc Function
• Each block allocated by the calloc function is of the
same size.
• Syntax:
• ptr = (cast_type *) calloc (n, size);
• The above statement is used to allocate n memory
blocks of the same size.
• After the memory space is allocated, then all the
bytes are initialized to zero.
• The pointer which is currently at the first byte of the
allocated memory space is returned.
The realloc Function
• Using the realloc() function, you can add more
memory size to already allocated memory.
• It expands the current block while leaving the
original content as it is.
• realloc stands for reallocation of memory.
• realloc can also be used to reduce the size of the
previously allocated memory.
• Syntax
• ptr = realloc (ptr,newsize);
The free Function
• The memory for variables is automatically
deallocated at compile time. In dynamic memory
allocation, you have to deallocate memory explicitly.
If not done, you may encounter out of memory error.
• The free() function is called to release/deallocate
memory
Linked List
• When we want to work with an unknown number of
data values, we use a linked list data structure to
organize that data.
• The linked list is a linear data structure that contains
a sequence of elements such that each element links
to its next element in the sequence.
• Each element in a linked list is called "Node".
• SINGLY LINKED LIST
• SINGLY CIRCULAR LINKED LIST
• DOUBLY LINKED LIST
• DOUBLY CIRCULAR LINKED LIST
Single Linked List
• Single linked list is a sequence of elements in which
every element has link to its next element in the
sequence.
• In any single linked list, the individual element is
called as "Node". Every "Node" contains two fields,
data field, and the next field.
• The data field is used to store actual value of the
node and next field is used to store the address of
next node in the sequence.
Single Linked List
Example:-
Operations on Single Linked List
• The following operations are performed on a Single
Linked List
• Insertion
• Deletion
• Display
Insertion
• In a single linked list, the insertion operation can be
performed in three ways.
• Inserting At Beginning of the list
• Inserting At End of the list
• Inserting At Specific location in the list
Abstract Data Types
• Abstract Data type (ADT) is a type (or class) for
objects whose behavior is defined by a set of value
and a set of operations.
The definition of ADT only mentions what operations
are to be performed but not how these operations
will be implemented.
• It does not specify how data will be organized in
memory and what algorithms will be used for
implementing the operations.
Abstract Data Types
• It is called “abstract” because it gives an
implementation-independent view. The process of
providing only the essentials and hiding the details is
known as abstraction.
• The user of data type does not need to know how
that data type is implemented,
• for example, we have been using Primitive values like
int, float, char data types only with the knowledge
that these data type can operate and be performed
on without any idea of how they are implemented.
List ADT
• A list contains elements of the same type arranged in
sequential order and following operations can be
performed on the list.
• get() – Return an element from the list at any given
position.
• insert() – Insert an element at any position of the list.
• remove() – Remove the first occurrence of any
element from a non-empty list.
List ADT
• removeAt() – Remove the element at a specified
location from a non-empty list.
• replace() – Replace an element at any position by
another element.
• size() – Return the number of elements in the list.
• isEmpty() – Return true if the list is empty, otherwise
return false.
• isFull() – Return true if the list is full, otherwise
return false.
Sparse Matrix
• In computer programming, a matrix can be defined
with a 2-dimensional array.
• Any array with 'm' columns and 'n' rows represent a
m X n matrix.
• There may be a situation in which a matrix contains
more number of ZERO values than NON-ZERO values.
Such matrix is known as sparse matrix.
• Sparse matrix is a matrix which contains very few
non-zero elements.
Sparse Matrix
• When a sparse matrix is represented with a 2-
dimensional array, we waste a lot of space to
represent that matrix.
• For example, consider a matrix of size 100 X 100
containing only 10 non-zero elements.
• In this matrix, only 10 spaces are filled with non-zero
values and remaining spaces of the matrix are filled
with zero.
• That means, totally we allocate 100 X 100 X 2 =
20000 bytes of space to store this integer matrix.
Sparse Matrix
• And to access these 10 non-zero elements we have
to make scanning for 10000 times.
• To make it simple we use the following sparse matrix
representation.
• A sparse matrix can be represented by using TWO
representations, those are as follows...
• Triplet Representation (Array Representation)
• Linked Representation
Triplet Representation
(Array Representation)
• In this representation, we consider only non-zero
values along with their row and column index values.
• In this representation, the 0th row stores the total
number of rows, total number of columns and the
total number of non-zero values in the sparse matrix.
• For example, consider a matrix of size 5 X 6
containing 6 number of non-zero values
Triplet Representation
(Array Representation)
Triplet Representation
(Array Representation)
• In above example matrix, there are only 6 non-zero
elements ( those are 9, 8, 4, 2, 5 & 2) and matrix size is
5 X 6.
• Here the first row in the right side table is filled with
values 5, 6 & 6 which indicates that it is a sparse matrix
with 5 rows, 6 columns & 6 non-zero values.
• The second row is filled with 0, 4, & 9 which indicates
the non-zero value 9 is at the 0th-row 4th column in
the Sparse matrix.
• In the same way, the remaining non-zero values also
follow a similar pattern
Linked Representation
• In linked representation, we use a linked list data
structure to represent a sparse matrix.
• In this linked list, we use two different nodes namely
header node and element node. Header node
consists of three fields and element node consists of
five fields
Linked Representation

More Related Content

Similar to data structure unit -1_170434dd7400.pptx

Similar to data structure unit -1_170434dd7400.pptx (20)

unit 2.pptx
unit 2.pptxunit 2.pptx
unit 2.pptx
 
Unit 1.ppt
Unit 1.pptUnit 1.ppt
Unit 1.ppt
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
cluod.pdf
cluod.pdfcluod.pdf
cluod.pdf
 
M v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notesM v bramhananda reddy dsa complete notes
M v bramhananda reddy dsa complete notes
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptx
 
Arrays.pptx
Arrays.pptxArrays.pptx
Arrays.pptx
 
DS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and EngineeringDS Complete notes for Computer science and Engineering
DS Complete notes for Computer science and Engineering
 
Arrays in C.pptx
Arrays in C.pptxArrays in C.pptx
Arrays in C.pptx
 
Array 2 hina
Array 2 hina Array 2 hina
Array 2 hina
 
DATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGESTDATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGEST
 
8074.pdf
8074.pdf8074.pdf
8074.pdf
 
PPT Lecture 2.2.1 onn c++ data structures
PPT Lecture 2.2.1 onn c++ data structuresPPT Lecture 2.2.1 onn c++ data structures
PPT Lecture 2.2.1 onn c++ data structures
 
Data structure
Data structureData structure
Data structure
 
Arrays
ArraysArrays
Arrays
 
Array
ArrayArray
Array
 
BHARGAVIARRAY.PPT.pptx
BHARGAVIARRAY.PPT.pptxBHARGAVIARRAY.PPT.pptx
BHARGAVIARRAY.PPT.pptx
 
Array
ArrayArray
Array
 
Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1Ist year Msc,2nd sem module1
Ist year Msc,2nd sem module1
 
DATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARIDATA STRUCTURE BY SIVASANKARI
DATA STRUCTURE BY SIVASANKARI
 

Recently uploaded

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
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
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
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
 
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
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
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
 
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
 

Recently uploaded (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
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
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
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
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
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
 
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
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
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
 
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...
 

data structure unit -1_170434dd7400.pptx

  • 2. DATA STRUCTURE DEFINITION • Whenever we want to work with a large amount of data, then organizing that data is very important. • If that data is not organized effectively, it is very difficult to perform any task on that data. • If it is organized effectively then any operation can be performed easily on that data. • Data structure is a method of organizing a large amount of data more efficiently so that any operation on that data becomes easy
  • 3. TYPES OF DATA STRUCTURE
  • 4. Primitive Data Structures • These are the structures which are supported at the machine level, they can be used to make non- primitive data structures. • Examples: Integer, float, character, pointers. • The pointers, however don’t hold a data value, instead, they hold memory addresses of the data values. These are also called the reference data types.
  • 5. Non Primitive Data Structures • The non-primitive data structures cannot be performed without the primitive data structures. Although, they too are provided by the system itself yet they are derived data structures and cannot be formed without using the primitive data structures. • The Non-primitive data structures are further divided into the following categories:
  • 6. 1. Arrays • Arrays are a homogeneous and contiguous collection of same data types. • They have a static memory allocation technique, which means, if memory space is allocated for once, it cannot be changed during runtime. • If we do not know the memory to be allocated in advance then array can lead to wastage of memory.
  • 7. 2. Files • A file is a collection of records. • The file data structure is primarily used for managing large amounts of data which is not in the primary storage of the system. • The files help us to process, manage, access and retrieve or basically work with such data, easily.
  • 8. 3.Lists • The lists support dynamic memory allocation. The memory space allocated, can be changed at run time also. The lists are of two types: • a) Linear Lists • The linear lists are those which have the elements stored in a sequential order. The insertions and deletions are easier in the lists. They are divided into two types:
  • 11. Stacks • The stack follows a “LIFO” technique for storing and retrieving elements. The element which is stored at the end will be the first one to be retrieved from the stack. The stack has the following primary functions: – Push(): To insert an element in the stack. – Pop(): To remove an element from the stack.
  • 13. Queues • The queues follow “FIFO” mechanism for storing and retrieving elements. The elements which are stored first into the queue will only be the first elements to be removed out from the queue. • The “ENQUEUE” operation is used to insert an element into the queue • The “DEQUEUE” operation is used to remove an element from the queue.
  • 14. Non Linear Lists The non linear lists do not have elements stored in a certain manner. These are: • Graphs: The Graph data structure is used to represent a network. • It comprises of vertices and edges (to connect the vertices). The graphs are very useful when it comes to study a network. • Trees: Tree data structure comprises of nodes connected in a particular arrangement and they make search operations on the data items easy. The tree data structures consists of a root node which is further divided into various child nodes and so on.
  • 15. Tree
  • 16. Graph
  • 17. Need of using Array • In computer programming, the most of the cases requires to store the large number of data of similar type. • To store such amount of data, we need to define a large number of variables. • It would be very difficult to remember names of all the variables while writing the programs. Instead of naming all the variables with a different name, it is better to define an array and store all the elements into it.
  • 18. Example • We have marks of a student in six different subjects. The problem intends to calculate the average of all the marks of the student.
  • 19. Program without Array #include <stdio.h> void main () { int marks_1 = 56, marks_2 = 78, marks_3 = 88, marks_4 = 76, marks_5 = 56, marks_6 = 89; float avg = (marks_1 + marks_2 + marks_3 + marks_4 + marks_5 +marks_6) / 6 ; printf(avg); }
  • 20. Array • Arrays are defined as the collection of similar type of data items stored at contiguous memory locations. • Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. • Array is the simplest data structure where each data element can be randomly accessed by using its index number.
  • 21. Array • For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variable for the marks in different subject. instead of that, we can define an array which can store the marks in each subject at a the contiguous memory locations.
  • 22. How to declare an array? Syntax:- data_type array_name[SIZE]; data_type is a valid C data type that must be common to all array elements. array_name is name given to array and must be a valid C identifier. SIZE is a constant value that defines array maximum capacity. Example :- int marks[5];
  • 23. How to initialize an array? There are two ways to initialize an array. Static array initialization - Initializes all elements of array during its declaration. Dynamic array initialization - The declared array is initialized some time later during execution of program.
  • 24. Static initialization of array We define value of all array elements within a pair of curly braces { and } during its declaration. Values are separated using comma , and must be of same type. Example of static array initialization int marks[500] = {90, 86, 89, 76, 91}; int marks[] = {90, 86, 89, 76, 91};
  • 25. Dynamic initialization of array You can assign values to an array element dynamically during execution of program. First declare array with a fixed size. Then use the following syntax to assign values to an element dynamically. array_name[index] = some value; Example to initialize an array dynamically marks[0] = 90 Cin>>marks[1];
  • 26. Basic Operations on 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. • Update − Updates an element at the given index.
  • 27. Address Calculation in 1D Array Array of an element of an array say “A[ I ]” is calculated using the following formula: Address of A [ I ] = B + W * ( I – LB ) Where, B = Base address W = Storage Size of one element stored in the array (in byte) I = Subscript of element whose address is to be found LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)
  • 28. Example: Given the base address of an array A[900…..1900] as 1400 and size of each element is 4 bytes in the memory. Find the address of B[1100] & B[1475]. A[I]=1400+4*(1475-900)
  • 29. Example: Solution: The given values are: B = 1020, LB = 1300, W = 2, I = 1700 Address of A [ I ] = B + W * ( I – LB ) = 1020 + 2 * (1700 – 1300) = 1020 + 2 * 400 = 1020 + 800 = 1820 [Ans]
  • 30. Properties of the Array • Each element is of same data type and carries a same size i.e. int = 2 bytes. • Elements of the array are stored at contiguous memory locations • Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of data element.
  • 31. Advantage of Array 1) Code Optimization: Less code to the access the data. 2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily. 3) Ease of sorting: To sort the elements of the array, we need a few lines of code only. 4) Random Access: We can access any element randomly using the array.
  • 32. Address Calculation in 2D Array • While storing the elements of a 2-D array in memory, these are allocated contiguous memory locations. • Therefore, a 2-D array must be linearized so as to enable their storage. • There are two alternatives to achieve linearization: Row-Major and Column-Major.
  • 35. Address Calculation Formula Row Major System: Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ] Column Major System: Address of A [ I ][ J ] = B + W * [( I – Lr ) + M * ( J – Lc )] Where B=Base Address W=Size of Each Element N=No of Columns M=No of Rows
  • 36. Address Calculation Formula Lr =Lower Bound of row Lc = Lower Bound of Column I = Row subscript of element whose address is to be found J = Column subscript of element whose address is to be found Number of rows (M) will be calculated as = (Ur – Lr) + 1 Number of columns (N) will be calculated as = (Uc – Lc) + 1 LR =FIRST ROW FIRST VALUE UR=FIRST ROW LAST VALUE UC=LAST COLUMN LAST VALUE LC=FIRST COLUMN LAST VALUE
  • 37. Consider the linear array AAA(5:50),BBB(-5:10) and CCC(18) A) find the number of element in each array B) suppose Base (AAA)=300 and w=4 words per memory cell for AAA.find the address of AAA[15],AAA[35] and AAA[55]
  • 38. Example • An array X [-15……….10, 15……………40] requires one byte of storage. If beginning location is 1500 determine the location of X [15][20].
  • 39. Solution As you see here the number of rows and columns are not given in the question. So they are calculated as: Number or rows say M = (Ur – Lr) + 1 = [10 – (- 15)] +1=26 Number or columns say N = (Uc – Lc) + 1 = [40 – 15)] +1 = 26
  • 40. Solution Column Major Wise Calculation of above equation The given values are: B = 1500 W = 1 byte I = 15 J = 20 Lr = -15 Lc = 15 M = 26 Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ] = 1500 + 1 * [(15 – (-15)) + 26 * (20 – 15)] = 1500 + 1 * [30 + 26 * 5] = 1500 + 1 * [160] = 1660 [Ans]
  • 41. Solution Row Major Wise Calculation of above equation The given values are: B = 1500 W = 1 byte I = 15 J = 20 Lr = -15 Lc = 15 N = 26 Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ] = 1500 + 1* [26 * (15 – (-15))) + (20 – 15)] = 1500 + 1 * [26 * 30 + 5] = 1500 + 1 * [780 + 5] = 1500 + 785 = 2285 [Ans]
  • 42. Example 2 • Each element of an array a[-20….20,10….35] requires 1 byte of storage .if the array is column major implemented and the beginning of the array is at location 500(base address).determine the address of elementa[0,30]
  • 43. Solution Column Major Wise Calculation of above equation The given values are: B = 500 W = 1 byte I = 0 J = 30 Lr = -20 Lc = 10 Ur=20 Uc=35 M=Ur-Lr+1=20-(-20)+1=41 Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ] = 500 + 1 * [(0 – (-20)) + 41 * (30 – 10)] = 500 + 1 * [20+41*20] = 500 + 1 * [840] = 1340 [Ans]
  • 44. Solution Row Major Wise Calculation of above equation The given values are: B = 500 W = 1 byte I = 0 J = 30 Lr = -20 Lc = 10 Ur=20 Uc=35 N=Uc-Lc+1=35-10+1=26 Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ] = 500 + 1* [26 * (0 – (-20))) + (30 – 10)] = 500 + 1 * [26 * 20 + 20] = 500 + 1 * [540] = 500 + 540 = 1040 [Ans]
  • 45. Example 3 • Calculate the address of X[4,3]in a 2 d array X[1….5,1….4] stored in row major order in main memory .Assume the base address to be 1000 and that each element requires 4 word of storage.
  • 46. Solution Column Major Wise Calculation of above equation The given values are: B = 1000 W = 4 byte I = 4 J = 3 Lr = 1 Lc =1 Ur=5 Uc=4 M=Ur-Lr+1=5-1+1=5 Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ] = 1000 + 4 * [(4– (1)) + 5 * (3 – 1)] = 1000 + 4 * [3+5*2] = 1000 + 4 * [13] = 1052 [Ans]
  • 47. Solution Row Major Wise Calculation of above equation The given values are: B = 1000 W = 4 byte I = 4 J = 3 Lr = 1 Lc =1 Ur=5 Uc=4 N=Uc-Lc+1=4-1+1=4 Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ] = 1000 + 4* [4 * (4– (1))) + (3 – 1)] = 1000 + 4 * [4 * 3 + 2] = 1000 + 4 * [14] = 1000 + 56 = 1056 [Ans]
  • 48. Example 4 • Each element of an array DATA[20][50] requires 4 bytes of storage. Base Address of DATA is 2000,determine the location of DATA[10][10]when the array is stored as • 1) Row Major • 2) Column Major
  • 49. Example 5 • A two dimensional array X[5][4] is stored a row wise in the memory .The first element of the array is stored at location 80 .find the memory location of X[3][2] if the each elements of array requires 4 memory locations.
  • 50. Algorithm  Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output.  An algorithm is a sequence of unambiguous instructions used for solving a problem, which can be implemented (as a program) on a computer.  Algorithms are generally created independent of underlying languages, i.e. an algorithm can be implemented in more than one programming language.
  • 51. Algorithm • Algorithms are used to convert our problem solution into step by step statements. • These statements can be converted into computer programming instructions which form a program. • This program is executed by a computer to produce a solution. • Here, the program takes required data as input, processes data according to the program instructions and finally produces a result as shown in the following picture.
  • 53. Specifications of Algorithms • Input - Every algorithm must take zero or more number of input values from external. • Output - Every algorithm must produce an output as result. • Definiteness - Every statement/instruction in an algorithm must be clear and unambiguous (only one interpretation). • Finiteness - For all different cases, the algorithm must produce result within a finite number of steps. • Effectiveness - Every instruction must be basic enough to be carried out and it also must be feasible.
  • 54. Performance Analysis of an algorithm • If we want to go from city "A" to city "B", there can be many ways of doing this. We can go by flight, by bus, by train and also by bicycle. • Depending on the availability and convenience, we choose the one which suits us. • Similarly, in computer science, there are multiple algorithms to solve a problem.
  • 55. Performance Analysis of an algorithm • When we have more than one algorithm to solve a problem, we need to select the best one. • Performance analysis helps us to select the best algorithm from multiple algorithms to solve a problem. When there are multiple alternative algorithms to solve a problem, we analyze them and pick the one which is best suitable for our requirements.
  • 56. Performance analysis of an algorithm • Performance analysis of an algorithm is the process of calculating space and time required by that algorithm • Space required to complete the task of that algorithm (Space Complexity). It includes program space and data space • Time required to complete the task of that algorithm (Time Complexity)
  • 57. Space complexity • Total amount of computer memory required by an algorithm to complete its execution is called as space complexity Example 1 int square(int a) { return a*a; }
  • 58. Space complexity • In the above piece of code, it requires 2 bytes of memory to store variable 'a' and another 2 bytes of memory is used for return value. • That means, totally it requires 4 bytes of memory to complete its execution. And this 4 bytes of memory is fixed for any input value of 'a'. This space complexity is said to be Constant Space Complexity.
  • 59. Example 2 int sum(int A[ ], int n) { int sum = 0, i; for(i = 0; i < n; i++) sum = sum + A[i]; return sum; }
  • 60. Example 2 Solution • In the above piece of code it requires 'n*2' bytes of memory to store array variable 'a[ ]' 2 bytes of memory for integer parameter 'n' 4 bytes of memory for local integer variables 'sum' and 'i' (2 bytes each) 2 bytes of memory for return value. That means, totally it requires '2n+8' bytes of memory to complete its execution. Here, the total amount of memory required depends on the value of 'n'. As 'n' value increases the space required also increases proportionately. This type of space complexity is said to be Linear Space Complexity.
  • 61. Time complexity • The time complexity of an algorithm is the total amount of time required by an algorithm to complete its execution. Example 1 int square(int a) { return a*a; }
  • 62. Time complexity • In the above sample code, it requires 1 unit of time to calculate a+b and 1 unit of time to return the value. • That means, totally it takes 2 units of time to complete its execution. • And it does not change based on the input values of a and b. That means for all input values, it requires the same amount of time i.e. 2 units. • If any program requires a fixed amount of time for all input values then its time complexity is said to be Constant Time Complexity.
  • 63. Dynamic Memory Allocation . Function Purpose malloc Allocates the memory of requested size and returns the pointer to the first byte of allocated space calloc Allocates the space for elements of an array. Initializes the elements to zero and returns a pointer to the memory. realloc It is used to modify the size of previously allocated memory space. Free Frees or empties the previously allocated memory space
  • 64. The malloc Function • The malloc() function stands for memory allocation. • It is a function which is used to allocate a block of memory dynamically. • It reserves memory space of specified size and returns the null pointer pointing to the memory location. • The pointer returned is usually of type void. It means that we can assign malloc function to any pointer. • Syntax • ptr = (cast_type *) malloc (byte_size);
  • 65. The malloc Function • Here, • ptr is a pointer of cast_type. • The malloc function returns a pointer to the allocated memory of byte_size. • Example: ptr = (int *) malloc (50) • When this statement is successfully executed, a memory space of 50 bytes is reserved. • The address of the first byte of reserved space is assigned to the pointer ptr of type int.
  • 66. The calloc Function • The calloc function stands for contiguous allocation. • This function is used to allocate multiple blocks of memory. • It is a dynamic memory allocation function which is used to allocate the memory to complex data structures such as arrays and structures. • Malloc function is used to allocate a single block of memory space while the calloc function is used to allocate multiple blocks of memory space.
  • 67. The calloc Function • Each block allocated by the calloc function is of the same size. • Syntax: • ptr = (cast_type *) calloc (n, size); • The above statement is used to allocate n memory blocks of the same size. • After the memory space is allocated, then all the bytes are initialized to zero. • The pointer which is currently at the first byte of the allocated memory space is returned.
  • 68. The realloc Function • Using the realloc() function, you can add more memory size to already allocated memory. • It expands the current block while leaving the original content as it is. • realloc stands for reallocation of memory. • realloc can also be used to reduce the size of the previously allocated memory. • Syntax • ptr = realloc (ptr,newsize);
  • 69. The free Function • The memory for variables is automatically deallocated at compile time. In dynamic memory allocation, you have to deallocate memory explicitly. If not done, you may encounter out of memory error. • The free() function is called to release/deallocate memory
  • 70. Linked List • When we want to work with an unknown number of data values, we use a linked list data structure to organize that data. • The linked list is a linear data structure that contains a sequence of elements such that each element links to its next element in the sequence. • Each element in a linked list is called "Node".
  • 71. • SINGLY LINKED LIST • SINGLY CIRCULAR LINKED LIST • DOUBLY LINKED LIST • DOUBLY CIRCULAR LINKED LIST
  • 72. Single Linked List • Single linked list is a sequence of elements in which every element has link to its next element in the sequence. • In any single linked list, the individual element is called as "Node". Every "Node" contains two fields, data field, and the next field. • The data field is used to store actual value of the node and next field is used to store the address of next node in the sequence.
  • 74. Operations on Single Linked List • The following operations are performed on a Single Linked List • Insertion • Deletion • Display
  • 75. Insertion • In a single linked list, the insertion operation can be performed in three ways. • Inserting At Beginning of the list • Inserting At End of the list • Inserting At Specific location in the list
  • 76. Abstract Data Types • Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a set of value and a set of operations. The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented. • It does not specify how data will be organized in memory and what algorithms will be used for implementing the operations.
  • 77. Abstract Data Types • It is called “abstract” because it gives an implementation-independent view. The process of providing only the essentials and hiding the details is known as abstraction. • The user of data type does not need to know how that data type is implemented, • for example, we have been using Primitive values like int, float, char data types only with the knowledge that these data type can operate and be performed on without any idea of how they are implemented.
  • 78. List ADT • A list contains elements of the same type arranged in sequential order and following operations can be performed on the list. • get() – Return an element from the list at any given position. • insert() – Insert an element at any position of the list. • remove() – Remove the first occurrence of any element from a non-empty list.
  • 79. List ADT • removeAt() – Remove the element at a specified location from a non-empty list. • replace() – Replace an element at any position by another element. • size() – Return the number of elements in the list. • isEmpty() – Return true if the list is empty, otherwise return false. • isFull() – Return true if the list is full, otherwise return false.
  • 80. Sparse Matrix • In computer programming, a matrix can be defined with a 2-dimensional array. • Any array with 'm' columns and 'n' rows represent a m X n matrix. • There may be a situation in which a matrix contains more number of ZERO values than NON-ZERO values. Such matrix is known as sparse matrix. • Sparse matrix is a matrix which contains very few non-zero elements.
  • 81. Sparse Matrix • When a sparse matrix is represented with a 2- dimensional array, we waste a lot of space to represent that matrix. • For example, consider a matrix of size 100 X 100 containing only 10 non-zero elements. • In this matrix, only 10 spaces are filled with non-zero values and remaining spaces of the matrix are filled with zero. • That means, totally we allocate 100 X 100 X 2 = 20000 bytes of space to store this integer matrix.
  • 82. Sparse Matrix • And to access these 10 non-zero elements we have to make scanning for 10000 times. • To make it simple we use the following sparse matrix representation. • A sparse matrix can be represented by using TWO representations, those are as follows... • Triplet Representation (Array Representation) • Linked Representation
  • 83. Triplet Representation (Array Representation) • In this representation, we consider only non-zero values along with their row and column index values. • In this representation, the 0th row stores the total number of rows, total number of columns and the total number of non-zero values in the sparse matrix. • For example, consider a matrix of size 5 X 6 containing 6 number of non-zero values
  • 85. Triplet Representation (Array Representation) • In above example matrix, there are only 6 non-zero elements ( those are 9, 8, 4, 2, 5 & 2) and matrix size is 5 X 6. • Here the first row in the right side table is filled with values 5, 6 & 6 which indicates that it is a sparse matrix with 5 rows, 6 columns & 6 non-zero values. • The second row is filled with 0, 4, & 9 which indicates the non-zero value 9 is at the 0th-row 4th column in the Sparse matrix. • In the same way, the remaining non-zero values also follow a similar pattern
  • 86. Linked Representation • In linked representation, we use a linked list data structure to represent a sparse matrix. • In this linked list, we use two different nodes namely header node and element node. Header node consists of three fields and element node consists of five fields