0% found this document useful (0 votes)
25 views12 pages

Fds Unit 2frompg6

Uploaded by

24.unknowncoder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views12 pages

Fds Unit 2frompg6

Uploaded by

24.unknowncoder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Structures

Fundamentels ofDate

Fundamentals of Data Structures Linear Data Structure


a2 2-7
Step 4 using Sequential Orzanzation
a1
20 40 60 80
k k+1
70
10 30 50 = i+ 1

#if elements of second array are


a3 remaining
#then transfer them to third array
10 2030 while<m:
K
a3[k) = a2[il
transrer the elements
Increment i and k pointers. In
this way we can
from k k+ 1
array a .
two arrays al and a2 to get merged j =j +1

Finally we get
#display the resultant merged array
50 60 70 80
10 20 30 40 print("Merged Array is ...")
for i in range (ntm):
two arrays.
a.9 Write a Python function for merging of print(str(a3[il), end = " ")

Ans.: Python Program


2.6: Storage Representation and thefr
def mergeAr(a1,a2,n,m):
a3 [None]*(n+m) Address Calculation
i 0
j 0 Q.10 Explain two dimensional arrays with row and columa major
k = 0 implementation. Explain address calculation in both cases with
#traverse both arrays exampleB [SPPU: Dec.-18, Marks 6]
#if element of first array is less then store it in third array
Ans.: Row Major Representation
#if element of second array is less then store it in third array
while i <n andj < m: If the elements are stored in row wise manner then it is called row

ifa1i<a2lil: major representation..


a3[k] = a1li] For example: If we want to store elements
k k+1 10 20 30 40 50 60 then in a two dimensional array
i =i+1
else 1 2
a3[k] = a2[jl
0 10 20 30
k = k+ 1
The elements will
40 50 60
=j +1 be stored horizontally
#if elements of first array are remaining
#then transfer them to third array
while i < n:
a3k) = a1

OECODED A Guide for


Engineering Students
DICODBD A Guide for Engineering Students
Linear Data Structue
2-8 using Sequential Organtzaton
Structures
ofData Linear Data Structure
Fundamentals
Fundamentals of Data Structures 2-9 using Sequentlal Organluaton
Column Major Representation
then it is called col amn
are stored in
column wise
manner
Column Major Representatlon
If elements
The element ali]G] will be at
major representation.
ali]g] = base address+(col_index*total number of
elements
If we want to store
:
For example
then the elements
will be filled up by column wise rowstrow_index)*element_size
10 20 30 40 50 60 Here 3 represents number o
manner as
follows (consider array a[3] [2]).
=
(base address+G°row_sizeti) element_size)
number of columns. when i-3 and j=4, element_size=int occupies 2 bytes of memory hence it
rows and 2 represents
is 2
0 total number of rows = 4

10 40 a[3][4] = 1020+(4*4+3)*2

= 1020+38
1 20 50

60
a[3]14]= 1058
2 30
2.7 Multidimenslonal Arrays
Example: Refer Q.11.
a11 Consider integer array int arrl4]15] declared in C program Q.12 Write a python program for performing addition of two
If the base address is 1020, find the address of the element arr[3]14] matrices.
with row major and column major representation of array. Ans.

SISPPU : Dec.-09, Marks 61 def add_matrix(arr1,arr2):


result [larr14|bl + ar2[401 for j in range(len(ar1101) for i in
Ans. : Row Major Representation
range(len(arr1)
The element a[i]G] will be at
ali]g] = base address+(row_index*total number of columns +
print("The Addition of Two Matrices.")
print(result)
col_index)*element_size row_num = int(finput("Input number of rows: " )

(base address+( i*col_size+j)*element_size) col num int(input("Input number of columns: "))


when i-3 and j=4 ,element_size=int occupies 2 ar1 I[0 for col in range(col_num)] for row in range(row_num)]
=

bytes of memory hence it


is 2 for row in range(row_num):
total number of columns=5 for col in range(colnum):
item=
a[3][4] = 1020+(3*5+4)*2 int(input("Enter the elements in first matrix: "))
arrl [row][col]= item
1020+38
print("The first matrix is... ")
a[3]14]= 1058 print(arr1)

arr2= [[0 for col in range(col_num)] for row


in range(row_num)
CIcoDS
A Guide for A Guide for Engineering Students
Engineering Students OIcODD
Linear Data Struct
2-10 using Sequential Organa
Fundamentals ofData
Structures
zaton Fundamentals of Data Structures 2-11
Linear Data Structure
using Sequential Organization

in range(row_num):
for row Enter the elements in second matrix: 3
for col in range(col_num): in second matrix; " Enter the elements in second matrix: 3
elements
the
item int(input("Enter
ar2row]|col]= item The second matrix is...

[[1, 1, 1, [2, 2, 2], [3, 3,3]]


print("The second matrix
is...") The Addition of Two Matrices..
print(arr2) [(2, 3, 4), [6, 7, 8], [10, 11, 12]]
>>>
#Driver Code
(2) Matrlx Multiplicatilon
add_matrix(arr1,ar?2,)
Output Consider matrlx A Consider matrix B The resutant matrix is

Input number of rows: 3 14 14 17


2
Input number of columns: 3 5 6 2 2 32 32 38
Enter the elements in first matrix: 1
50 50 59
Enter the elements in first matrix: 2
Write a python program to implement matrix multiplication
Enter the elements in first matrix:3 Q.13
operatio.
Enter the elements in first matrix: 4
Enter the elements in first matrix: 5 Ans.
A = I1,2,3],
Enter the elements in first matrix: 6
14,5,61,
Enter the elements in first matrix: 7
17,8,9|1
Enter the elements in first matrix: 8
Enter the elements in first matrix: 9
The first matrix is. B I11,1,1],
(2,2,2],
t[, 2, 3), [4, 5, 6), [7, 8, 9]]
13,3,4]1
Enter the elements in second matrix: 1
Enter the elements in second matrix: 1
Enter the elements in second matrix: 1 result= [[0,0,0,

Enter the elements in second matrix: 2 0,0,0,


0,0,0]1
Enter the elements in second matrix: 2
Enter the elements in second matrix: 2
Enter the elements in second matrix:
3
A Guide for Engineering Sudents
OECODE A Guide for OICOD
Engineering Students
Linear Data Structee
Linear Data Sructure
using Sequential Organizaton using Sequrntial Organtzatlon
2-12 Fundamentals of Data Structures 2- 13
Strucures

Fundamentals ofData of matrix.


a.14 Write a python program for performing transpose
print("Matrix A is...")
Ans.
print[A) A = I11,2,31.
4,5,6]
print("Matrix B is..")
7,8,9]1
print(B)

rows of X
iterate through result= I[0,0,0),
#
range(len(A)):
for i in 0,0,01.
for j in range(len[B|0]) 0,0,011
range(len(B);:
for k in
+= Ali]|k]
*
B[k]lil
result[i|il

print("Original Matrix is...")


print("Matrix Multiplication is..")
print[A)
for r in result:
print(r) iterate through rows
#
Output for i in range(len[A):
Matrix A is ..
for j in range(len(A[0]))
resultilil = A[i|lil
8, 9]]
l1, 2, 3]. [4, 5, 6], [7,
Matrix B is
print("Transposed
Matrix is ..")
3, 4]]
I[1, 1, 1]. [2, 2, 2]. [3, for r in result:

Matrix Multiplication is.. print(r)

[14, 14, 17] Output


132, 32, 38] Original Matrix is...

[50, 50, 59 [[1, 2, 3]. [4, 5, 6], [7, 8, 9]]


Transposed Matrix is
. .

Matrix
(3) Transpose of [1, 4, 7
Transposed matrlx
Conslder matrlx A
[2, 5, 8]
[3, 6, 9
2 5 8 >>>
5

9 3 6 9
8
Students
Engineering
4 Giuide for

A Gulde for Engineertng Students IcoDD


PIcoDD
Strwcfare
sing Sequential Organttan
2-14
Fandie
Fundamentals of Data Structure Linear Data Structure
Three dimensional arrays. 1-15
wsimg Sequntel Organtatlon
5
rte sbert note on
similar to the two dimensia sional Q.17 Write
he
mulbdimensional amay is
a
python program to ereate a list of even numbers from
ATS Here is 3-D aray 0 to 10.
dimensions for example
mubpie

a[3] (] (3] - {{{.2.3}.45.0} Ans.

{f78 {101 112}} even [ #creating empty list


for i in range(11):
dmensio
{31415}161718 ifi %2 = =0:
rows colum

even.append(i)
ecT Tepresent it gaphically as print("Even Numbers List: ",even)
even = I #creating empty list

1dimension for i in range(11):


ifi % 2 ==0:
14
2 dimension even.append(i)
3 dimension print("Even Numbers List: ",even)
121
Output
Even Numbers List: [0, 2, 4, 6, 8, 10]
Coiumns

Q.18 Write a python program to combine and print two lists using
2.8 Concept of Ordered List list comprehension.
Ans.
Q.16 Explain the concept of ordered list. print((x,y)for x inl'a','b'] for y in |'b',d'] if xl=yl)
Ordered list is nothing but a set of elements. Such a list
Ans.
sometimes called as linear list. Output
Ca', 'b'), (a', 'd'), (b, d')]
For example
1. List of one digit numbers 2.9: Single Variable Polynomial
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Q.19 Explain polynomial representation using arrays.
2. Days in a week.
SPPU: May 17, 18, Marks 3
(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)
With this concept in mind let us formmally define the ordered list. Ans. Definition Polynomial is the sum of terms where cach term

consists of variable, coefficient and exponent. .


Definition : An ordered list is set of elements where set may be empty or
it can be written as a collection of elements such as (al, a2, a Representation For representing a single variable polynomial one can
:

an). make use of one dimensional aray. In single dimensional aray the index
of an array will act as the exponent and the coefficient can be stored
at

that particular index which can be represented as follows .

pIcoDD A Guide for Engineering Students


A Guldefor Englneerlng Students pIcODD
Linear Data Struct
2- 16 using Sequentlal Organ
Structures
Linear Data Structure
Fundamentals
of Data Fundamentals of Data Structures 2-17 ustng Sequendal Organizatton
19
7x + 10x
-

e.g.:3x+5x
+
array.
For stored in single
dimensional

can be
This polynomial The Read Function Is For Reading The Two Polynomials
-19

1 10
Coefficients
of the polynomial int APADD::Read(p p[10])

int t1,i;

5
cout<<"\n Enter The Total number Of Terms in The Polynomial:
cin> >t1;
Order;
cout<<"\n Enter The Coef and Exponent In Descending
for(i=0;i<t1i++)
Index which acts

cout<<"\n Enter Coefficient and exponent: ";


as exponent of
respective coefficient
cin>>plil.coeff
representation
Fig. Q.19.1 Polynomial cin>>pli].expo;
two polynomials.
Q.20 Write a program to add
return(t1);
Ans.
#include <iostream>

using namespace std;


/*
class APADD
Polynomials
Function Is For adding The Two
The add
private:
p2[10],int t1,int t2,p p3/10})
struct p int APADD:add(p p1/10].p

int coef int i,j,k;


int expo int t3;
i=0;
public:
j=0;
P p1/10]p2[10],p3[10]: k=0;
int Read(p pi[10]); while(i<t1 &&j<t2)
int add(p p1[10],p p2[10] int t1,int t2,p p3[10);
void Print(p p2[10],int t2); if(p1i].expo==p2jl.expo)

Students
A Gulde for Engineering
OICODE
PECODE A Gulde for Engineering Students
Linear Data Struct Linear Data Structur
2-18 using Sequential Organi
wzing Saquuntal Orqnizatlon
Sructures Re,Fundamentals of Data Structures 2-1
Pundamentals ofData
p3/k).coeff=pli|.coeff+p2j|.coeff
p3/k].expo =p1[i).expo; void APADD::Print(p pp[10].int term)

i++jt+;k++;
int k;
else ifp1il.expo>p2|j].expo)
cout<"n Printing The Polynomial";
for(k=0;k<term-1;k++)

p3k].coeff=pl|i|.coeff
cout" <<pplk].coeff< <X* '<<pp[ik}.axpo<<".

p3[k].expo =p1li|.expo; cout<pp[k].coeff< <X^'<<pp|k].expo


i+k++

else
The main function

p3/kl.coeff=p2j].coeff;

p3k].expo =p2j].expo;

j++:k++ int main()

APADD obj;
while(i<t1) int t1,t2,t3
cout<<"n Enter The First Polynomial";
p3k].coeff=p1li|.coeff; t1=obj.Read(obj.p1);
p3k].expo =p1[i|.expo; cout<<"n The First Polynomial is: ";
i++k++ obj.Print(obj.p1,.t1);
cout<<"\n Enter The Second Polynomial";
whilej<t2) t2=obj.Read(objp2);
is: ";
cout<"n The Second Polynomial
p3k].coef=p2[j|.coeff; obj.Print(obj.p2,t2);
p3k].expo =p2jl.expo; cout<<"n The Addition is: ";
j+k+ t3=obj.add(objp1,obj.p2,t1,t2.obj.p3);
obj.Print(obj p3,t3);
t3=
retum 0;
returm(t3);

The Print Punction Is For


Printing The Two Polynomials
Students
A Guidefor Enginering
OIcoD
A
Guide for Engineering Studens
Linear Data Structure
Linear Data Structus
ustng Seguential Organtzation
20
using Sequential Organization Fundamentals of Data Structures
2-21
Structures

Fundamentals
of Data if (s14i][0] == s21j|10])
2.10: Sparse Matrix
if (s1i1[1) == s2[jll1])

it with example.
matrix? Explain
What is sparse s2[i112];
a.21
P ISPPU: May-19, Marks 4 s3[k][2]=s1[|[2] +
s3[k][1] = s1[i|[1];

is a matrix containing few non Zern


s3[k][0] = s1li|[0};
Ans. Definition Sparse matrix
elements. i++
size 100 x 100 and only 10 element it+t
For example -
if the matrix is of has to make
one
these 10 elements k++
zero. Then for accessing
are non
10 spaces will be
with non-zero elements
10000 times scan. Also only
matrix will be filled with zeros only. i.e. we have else if (s1[i|[1]<s2[j|11))
remaining spaces of 20000.
x 100 x 2
toallocate the memory of 100
s3k][2] = s1|[2];
is a kind of representation in which
Hence sparse matrix representation
with their rows and columns is stored. s3[k][1 s1[i][1];
onlynon zero elements along
s3[k][0] = s1[i][0};

2 3 i++

4 S 6 0 k++
7 9 else

Dense Matrix Sparse Matrix s3[k]2] = s261[2]1:

Q.22 Write a function for addition of two sparse matrices. s3k][1 =


s2j]11};
s3[k]10] = s2[i110];
Ans.
void add(int s1/10]13],int s2[10]13],.int s3[10]13]) jt+
k++;
int i, j, k;
i = 1; j = 1;k = 1; H/end of0 if
if (s1[0]10] else if (s1[i][0]<s2[Gi[O)
==
s2j0]10]) && (s1[0][1] ==
s210111]))
s3[k]2] = s1][2];
s310]10)= s1[0]|0]; s3[k][1] = s1li|[1];
s3/0]11) = s1|0]11];

Itraversing thru all the terms s3|k][0] = s1li|[0

while (i<= s1[0]|2]) && G <= s2[0]|2])) i++


k++
A Guide for Engineering Students
QECODD OICODD
A Guide for Engineering Studen
Linear Data Structure
Linear Data Strucno Structures 2-23 using Sequental Orzanizatlon
Fundamentals of Data
using Sequential Organiza
2-22
matrix
Structures
fast transpose is a transpose method in which
Fundamentals ofData Ans.: The
In this method an axiliary
transpose operation
is performed efficiently.
used to locate the position be
of the elements to transposed
are
array
else sequentially.
Fast Transpose
s3[k]|2] = s2j||2); Logic for
matrix representative as
83[k]11 = s2j|/1); Consider the sparse
$1
$3k]10)= s2]|0];

i++ Col Non-Zero values


Index Row
k++
W/end of while 10
//copying remaining terms
20
while (i <= s1[0|2])
30
3 2
s3[k]|2] = s1i|[2]; 40
4 2
s3[k]11] = s1l||1];

s3[k]10] = s1|i|[0]:
named rterm]. In this array
one dimensional array,
We will first consider
i++ zero terms present
in each column.
we will store non
k++ rterm
column there are
At 0
while G= s2[0]|[2]) two non zero terms.
At 1st
two
column also there are

s3k]12]=s2i12]; non zero terms but there is


s3[k]11= s2|l|1]; non zero term in nd
s3[k]10 = s2j]10];
column. We
dimensional array named rpos].
it+: Similarly we will take another one

k++ location of rpos[| by 1. so,


initialize 0th pos

631012 =
k- 1; the
formula to fill up
Now we use following
else rpos array.
1]
cout<<"n Addition is not possible"; rpos[i] rposfi - 1] +rtermi

Q.23 Explain fast


transpose of sparse matrix with suitable examp
Discuss time complexity of fast transpose.
Sudents

K[SPPU : May-17, Marks A Guldefor Engtnoering


pIcODDS
oIcoDD uiua Suden
Linear Data Strw
2-24 using Sequentlal Organt
Fundamentalh of Date
Srutures Fundamentals of Data Strurtuses Lineu Daa Saruetart
ming Seqauntal Orzaniatoa
-3
2 Now since rpos[|) is read yust tarw,
ctement
pon{3) - rpon[2] n ryon1) vse ry
poe1penfo) rnerm[0) rponl2) rpos{1]
*
rnerm{)| Hence
3 2 - 5+0-5
-12
rpon|3 5
rpon|2 5
pon1

pos

3
Read next element from S1 array
inde row col value
Intarchange
2 20
Now we will read values of SI array from 1 to 4. rpos
We must find the triplet from S1 array which is at index 1. It is (0, 1, 10
That mean place triplet (0, 1, 20) at index 1 in S2 array

inde row Col value row Co value $2


Just interchange
1 1S1 0 row and col O 10 Row Col Non-Zero values

Since value is 1,
check rpos[1]
20

rpos[1] points to value 3. That means place the triplet (1, 0, 10) at inde 2

3 in $2 aray. 3 1 0 10

$2 4

increment rpos[0} by 1
Row Col Non-Zero values Since rpos[0] is read just now,
rpos

1 4

3 1 10

4 Gaide or Enginoering Stdens


Qucoo
pIcoD A Gulde for Engineertng Studen
Linear Data Struet
using Sequentlal Organi Linear Data Structure
2-26 ustng Sequntal Organation
2-27
Structures
Fundamentals ofData Structures
Fundamentals
ofData
array row Col value $2
from SI
clement
next
Read value Interchange 2 30 Non-Zero values
index
row col Row Col
o 30
32 rpos[0] 2

1 20
at index
2 in $2 array.
(0, 2, 30) 30
That means place triplet 2 0 2
$2

Col Non-Zero values 3 0 10


Row
2 40

20 sparse matrix.
Thus we get transposed
number of couns
30 fill up $2[0] by total number of rows, total
2
2 Finally we

number of non-zero values.


and total
0 10
1
Thus we get
Non-Zero values
Row Col

|3 4

just increment rpos[0] by 1.


Since rpos[0} is read
now

1 20
rpos
2 30

4 3 10

4 2 40

5
Read next element from S1 array C+ Code
rodd trans (int s1/max1|13],int s2[max1|13])
Col value row col value
inde oW
Interchange
2 1 40 12 40 int rtermmax1].rpos|max1|;

inti,
rposf1 4 ínt row.col,num;
That means place triple (1, 2, 40) at index 2 in $2 array. row= s1|OJIO];
col s1101}:
num s1|0|2];
A Gulde for Engineering Students
A Guldefor Englneering Studens pIcoDDD
Linear Data Stus
2-28
Astng Sequenttal Orpa
Linear Data Structur
S c t u r e s

Fundamentals of Data Structures 1-29 wsing Sequential Orgamkatlon


Data
F u n d a m e n t a l s of

be
the cost of
time or a time efficiency (performance efficiency) can

s2/0110) = col; at the cost of memory.


achieved
Consider the programs like compilers in which symbol table is
Example:
s2/0]1=row,

entire symbol tabie is


used to handle the variables and constants. Now if
s2/0]12) = num;

(num
> 0) stored in the program then the time required for searching or storing the
f will
variable in the symbol table will be reduced but memory requirement
col; i ++) the table in the
0; i <= On the other hand, if we do not store symbol
(i be more.
=
for
rterm|li = 0; and simply compute the table entries then memory will be
program
num;it+)
reduced but the processing time will be more.
for (i 1;i
=
<=

rerm/s1|l1}] ++*;
the rowwise position*/

rpos|0
=
1; /'setting END.
for(i =
1; i < = col; i++)
rpos|il=rpos|i-1]+ rterm|(i 1)];
num;i++)
for( i 1; i = <=

j= rpos|s1|[1]1;
s2j]0= s1li|[1};
s2il1 = s1 i|[0];
s2512 s1||2);
pos|s1|i||1]l =j+ 1;

Time Complexity of Fast Transpose


For transposing the elements using simple transp0se method we need two
ested for loops but in case of fast transpose we are determining te
position of the elements that get transposed using only one for loop
Hence the time complexity of fast
transpose is O(n)
2.11 Time and Space Tradeoff
Q.24 Explain theconcept of time and space tradeoff.
Ans.: Basie
concept : Time space trade-off is
where eitheT a basically a situati
space efficiency (memory utilization) can be achieved &

DICODI A Guide for Enginering Sadents


A Guide for QIcoDD
Engineering Sudems

You might also like