Lecture Notes DSA Unit-I
Lecture Notes DSA Unit-I
m
Lecture No. 1-8
co
he term data structure is used to describe the way data is stored, and the term
T
l.
algorithmisusedtodescribethewaydataisprocessed.Datastructuresandalgorithmsare
interrelated. Choosing a data structure affects the kind of algorithm you might use, and
choosinganalgorithmaffectsthedatastructuresweuse.AnAlgorithmisafinitesequenceof
ai
instructions,eachofwhichhasaclearmeaningandcanbeperformedwithafiniteamount
of effort in a finite length of time. No matter what the input values may be, an algorithm
gm
ata Structureisawayoforganising,managing,andstoringdatainacomputerso
D
thatitcanbeaccessedandusedefficiently.Itprovidesasystematicwayoforganisingand
.l
accessingdatathatenablesfastandefficientoperationsonthedata.Themaingoalofusing
Data Structure is to reduce the complexity of accessing and manipulating data.
fi
Datastructureisarepresentationoflogicalrelationshipsexistingbetweenindividual
elementsofdata.Inotherwords,adatastructuredefinesawayoforganisingalldataitems
that considers not only the elements stored but also their relationship to each other. The
ro
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
• Non-primitive data structures.
Primitive DataStructures are the basic data structures that directly operate upon the
achine instructions.They have different representations on different computers. Integers,
m
floating point numbers, character constants, string constants and pointers come under this
Category.
Non-primitivedatastructuresaremorecomplicateddatastructuresandarederived
from primitive data structures. They emphasise on grouping same or different data items
with relationship between each data item. Arrays, lists and filescomeunderthiscategory.
Figure 1.1 shows the classification of data structures.
m
co
l.
ai
gm
c@
cb
The collection of data a program have some kind of structure or organization.No
matter how complex data structures are they can be broken down into two fundamental
fi
types:
• Contiguous
ro
• Non-Contiguous.
Incontiguousstructures,termsofdataarekepttogetherinmemory(eitherRAMor
inafile).Anarrayisanexampleofacontiguousstructure.Sinceeachelementinthearrayis
locatednexttooneortwootherelements.Incontrast,itemsinanon-contiguousstructure
are scattered in memory, but they are linkedtoeachotherinsomeway.Alinkedlistisan
example of a non-contiguous data structure (as shown in figure 1.2).
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
1.3 Abstract Data Type (ADT):
Thedesignofadatastructureinvolvesmorethanjustitsorganisation.Youalsoneed
to plan forthewaythedatawillbeaccessedandprocessed–thatis,howthedatawillbe
interpreted actually, non-contiguous structures – including lists, tree and graphs – can be
implemented either contiguously or non- contiguously likewise, the structures that are
normally treated as contiguously - arrays and structures – can also be implemented
non-contiguously.
The notion of a data structure in the abstract needs to be treated differently from
whatever is used to implement the structure. The abstract notion of a data structure is
defined in terms of the operations we plan to perform on the data.
Considering both theorganisationofdataandtheexpectedoperationsonthedata,
leads to the notion of an abstract data type. An abstract data type(ADT) is a theoretical
construct that consists ofdataaswellastheoperationstobeperformedonthedatawhile
m
hiding implementation.
Somecommonabstractdatatypesarelinkedlists,stack,queue,trees,trie,graphs
co
etc.
l.
1.4 Fundamental and Derived Data Types
ai
The basic data(also known as fundamental data types) types are defined in the
programminglanguageCorC++formthefundamentalbasisofanyprogram,asthename
suggests. e.g : int, char, float, double are fundamental types in C/C++.
gm
Derived data types: The data types are formed by using a collective of a few
fundamentaldatatypes,hencearederiveddatatypes,asthenamesuggests.e.g. arrays,
c@
programs.Theyprovideanefficientwaytoaccessandmanipulatedata,makingiteasierfor
programmers to write code that is both efficient and easy to understand. Here are some
reasons why data structures are important:
fi
a. Efficient Data Access: Data structures provide efficient methods for
accessing and searching data. By organisingdatainaspecificway,wecan
ro
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
1.6 Array as a data structure (characteristics, advantages, disadvantages) (Lecture 2)
An array is a collection of similar types of dataitemsstoredatcontiguousmemory
locations.Theideaistostoremultipleitemsofthesametypetogether.Thismakesiteasier
tocalculatethepositionofeachelementbysimplyaddinganoffsettoabasevalue,i.e.,the
memory location of the first element of the array (generally denoted by the name of the
array).
m
co
l.
ai
gm
Applications:
c@
Storingandaccessingdata:Arraysareusedtostoreandretrievedatainaspecific
order.Forexample,anarraycanbeusedtostorethescoresofagroupofstudents,
cb
algorithms such as bubble sort, merge sort, and quicksort rely heavily on arrays.
Searching: Arrays can be searchedforspecificelementsusingalgorithmssuchas
fi
Characteristics:
An array is always stored in consecutive memory locations.
It can store multiple values of similar type, which can be referred to with a single
name.
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
hepointerpointstothefirstlocationofthememoryblock,whichisallocatedtothe
T
array name.
Anarraycaneitherbeaninteger,character,orfloatdatatypethatcanbeinitialised
only during the declaration.
The particular element ofanarraycanbemodifiedseparatelywithoutchangingthe
other elements.
All elements of an array can be distinguished with the help of index number.
Advantages:
fficient access to elements: Arrays provide direct and efficient access to any
E
element in the collection. Accessing an element in an array is an O(1) operation,
meaning that the time required to access an element is constant and does not
depend on the size of the array.
m
Fastdataretrieval:Arraysallowforfastdataretrievalbecausethedataisstoredin
contiguousmemorylocations.Thismeansthatthedatacanbeaccessedquicklyand
co
efficiently without the need for complex data structures or algorithms.
Memoryefficiency:Arraysareamemory-efficientwayofstoringdata.Becausethe
l.
elementsofanarrayarestoredincontiguousmemorylocations,thesizeofthearray
is known at compile time. This means that memory can be allocated for theentire
ai
array in one block, reducing memory fragmentation.
Versatility: Arrays can be used to store a wide range of data types, including
gm
integers,floating-pointnumbers,characters,andevencomplexdatastructuressuch
as objects and pointers.
c@
Easytoimplement:Arraysareeasytoimplementandunderstand,makingtheman
ideal choice for beginners learning computer programming.
cb
Compatibility with hardware: The array data structure is compatible with most
hardwarearchitectures,makingitaversatiletoolforprogramminginawiderangeof
.l
environments.
Disadvantages:
fi
createdandthedatamustbecopiedfromtheoldarraytothenewarray,whichcan
be time-consuming and memory-intensive.
Memoryallocationissues:Allocatingalargearraycanbeproblematic,particularly
insystemswithlimitedmemory.Ifthesizeofthearrayistoolarge,thesystemmay
run out of memory, which can cause the program to crash.
Insertion and deletion issues: Inserting or deletinganelementfromanarraycan
be inefficient and time-consuming because all the elements after the insertion or
deletion point must be shifted to accommodate the change.
Wasted space: If an array is notfullypopulated,therecanbewastedspaceinthe
memory allocated for the array. This can be a concern if memory is limited.
Limiteddatatypesupport:Arrayshavelimitedsupportforcomplexdatatypessuch
asobjectsandstructures,astheelementsofanarraymustallbeofthesamedata
type.
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
ack of flexibility: The fixed size and limited support for complex data types can
L
make arrays inflexible compared to other data structures such as linked lists and
trees.
m
co
l.
ai
gm
c@
cb
.l
fi
ro
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
1.7 Representation of arrays in memory – single and multidimensional (Lecture 3)
m
co
l.
Multi Dimensional Array (2D Array):
ai
Representation of 2 D array:
1. Row Major Ordering
gm
.8Addresscalculationofarrayelementusingcolumnandrowmajorordering(1D,2D
1
and 3D):
Address Translation Function(ATF):
Address of any element In the 1-D array:
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
Address of A[I] = B + W * (I – LB)where,
I= Subset of element whose address to be found,
B= Base address,
W= Storage size of one element store in any array(in byte),
LB= Lower Limit/Lower Bound of subscript(If not specified assume zero).
xample:GiventhebaseaddressofanarrayA[1300…………1900]as1020andthesize
E
of each element is 2 bytes in the memory, find the address of A[1700].
Solution:
iven,
G
m
Base addressB= 1020
Lower Limit/Lower Bound of subscriptLB= 1300
co
Storage size of one element store in any arrayW= 2 Byte
Subset of element whose address to be foundI= 1700
Formula used:
l.
Address ofA[I] = B + W * (I – LB)
Solution:
ai
Address ofA[1700]= 1020 + 2 * (1700 – 1300)
= 1020 + 2 * (400)
gm
= 1020 + 800
Address ofA[1700]= 1820
c@
cb
The 2-dimensional array can be defined as an array of arrays. The
2-Dimensional arrays are organised as matrices which can be represented as the
collectionofrowsandcolumnsasarray[M][N]whereMisthenumberofrowsand
fi
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
o find the address of any element in a 2-Dimensional array there are the
T
following two ways-
Row Major Order
Column Major Order
Row Major Order:
Row major ordering assigns successive elements, moving across the rows
and then down the next row, to successive memory locations. In simple language,
the elements of an array are stored in a Row-Wise fashion.
To find the address of theelementusingrow-majororderusesthefollowing
formula:
m
I= Row Subset of an element whose address to be found,
J= Column Subset of an element whose address to be found,
B= Base address,
co
W= Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as
l.
zero),
LC=LowerLimitofcolumn/startcolumnindexofthematrix(Ifnotgivenassumeit
ai
as zero),
N= Number of column given in the matrix.
gm
c@
Fig.2DRow Major
cb
order.
Solution:
fi
Given:
Base addressB= 100
ro
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
Column Major Order: (Lecture 5)
m
M= Number of rows given in the matrix.
co
Fig.2DColumn Major
l.
xample:Givenanarrayarr[1………10][1………15]withabasevalueof100andthesize
E
ai
of each element is 1 Byte in memory find the address of arr[8][6] with the help of
column-major order.
gm
Solution:
Given,
c@
= 10 – 1 + 1
= 10
ro
Formula used,
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
Address ofA[8][6]= 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address ofA[I][J]= 157
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
1.8 Insertion and deletion in arrays (Lecture 6)
Insert Operation:
1.Insert at the end:
In an unsorted array, the insert operation is faster ascomparedtoa
sorted array because we don’t have to care about thepositionatwhichthe
element is to be placed.
m
co
l.
ai
gm
c@
#include <stdio.h>
.l
{
arr[n] = key;
return (n + 1);
}
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
int n = 6;
int i, key = 26;
return 0;
}
m
2. Insert at any position:
co
Insert operation in an array at any position can be performed by
shifting elements to the right, which are on the right side of the required
l.
position.
ai
gm
c@
cb
.l
fi
ro
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
// C Program to Insert an element
// at a specific position in an Array
include <stdio.h>
#
// Function to insert element
// at a specific position
void insertElement(int arr[], int n, int x, int pos)
{
// shift elements to the right
// which are on the right side of pos
for (int i = n - 1; i >= pos; i--)
arr[i + 1] = arr[i];
arr[pos] = x;
}
m
// Driver's code
int main()
co
{
int arr[15] = { 2, 4, 1, 8, 5 };
int n = 5;
l.
rintf("Before insertion : ");
p
ai
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
gm
printf("\n");
c@
return 0;
}
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
Deletion Operation: (Lecture 7)
Inthedeleteoperation,theelementtobedeletedissearchedusingthelinear
search, and then the delete operation is performed followed by shifting the elements.
m
co
l.
// C program to implement delete operation in a
ai
// unsorted array
#include <stdio.h>
gm
}
return n - 1;
}
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
return i;
return -1;
}
m
printf("%d ", arr[i]);
co
// Function call
n = deleteElement(arr, n, key);
l.
rintf("\nArray after deletion\n");
p
for (i = 0; i < n; i++)
ai
printf("%d ", arr[i]);
return 0;
gm
}
c@
cb
as we want.
In our new representation, we have an array of "digits" (integers) in some base b.
ro
First, we need a way of making a "normal" integer into a "big" integer; we'd like a
functioncalledmake_intsuchthate.g.make_int(A,123)wouldput3inA[0],2inA[1],1in
A[2], and zerosinA[3..N-1].We'lldotheseinCratherthanpseudocodebecausethecode
works out very easily:
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
/* put the normal int n into the big int A */
void make_int (int A[], int n) {
int i;
i = 0;
while (n) {
m
A[i++] = n % BASE;
co
/* get rid of the least significant digit,
* i.e., shift right once
l.
*/ ai
n /= BASE;
}
gm
owlet'slookatthemoregeneralcaseofadditionoftwobigintegers.Here,wewant
N
.l
toaddtwobigintsinarrayscalledA[0..N-1]andB[0..N-1],andputtheresultintoC[0..N-1].
We'llusethealgorithmwelearnedingradeschool:addcorrespondingdigits,plusa"carry"
fi
carry = 0;
/* if the sum exceeds the base, then we have a carry. */
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT
if (sum >= BASE) {
carry = 1;
sum -= BASE;
} else
/* otherwise no carry */
carry = 0;
C[i] = sum;
}
m
/* if we get to the end and still have a carry, we don't have
co
* anywhere to put it, so panic!
*/
if (carry) printf ("overflow in addition!\n");
l.
} ai
gm
c@
cb
.l
fi
ro
LN-BCA/DSA/2024/Jan-Aug
Masud Alam Rofi
LCBC/IT