0% found this document useful (0 votes)
10 views18 pages

FDS Unit II

Uploaded by

amitbiradar002
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)
10 views18 pages

FDS Unit II

Uploaded by

amitbiradar002
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/ 18

Unit II

Linear Data Structure Using Sequential Organization


Concept of Sequential Organization
In computer science, sequential access means that a group of elements (such as data in
a memory array or a disk file or on magnetic tape data storage) is accessed in a
predetermined, ordered sequence.
Sequential access is sometimes the only way of accessing the data, for example if it is
on a tape.

Fig- Sequential Access


Overview of Array
Array is referred as the Sequential Organization that means the data in arrays is stored
in some Sequence.
If we want to store names of all the students in a class we can make use o a array to
store the names in sequential form.

Definition of an array
An array is a set of consecutive memory location with contains similar data elements.
Or
Array is a collection of similar type of elements
An array as a data structure is defined as a set of pairs ( index, value ) such that with
each index a value is associated.
index - indicates the location of an element in an array.
value - indicates the actual value of that data element.
Declaration of an array in „C++‟: data_types name_of_array[size]
Example- int a[20];
Here „a‟ is the name of the array inside the square bracket size of the array is given .
This array is of integer type in array „a‟.
The Array can be one dimension, two dimensions or multi- dimensional.

One dimension
The one dimensional array „a‟ is declared as int a[10].

Syntax- data_types name_of_array[size]


Example- int a[20];
Two dimensional
The two dimensional array „a‟ is declared as int a[3][3]. The two dimensional array
should be in row – column form.
Syntax- data_types name_of_array[row_size][column_size]
Example- int a[3][4];

Multi- dimensional
The Multi-dimensional array „a‟ is declared as int a[3][3]…..[3] .
Syntax- data_types name_of_array[size1][size2] ….[sizen]
Example- int a[3][3]…..[3];
Array as an Abstract Data Type
The Abstract Data Type is written with help of instances &operations.
We make use of the reserved word AbstractDataType while writing an ADT.
AbstractDataType Array
{ Instances - An array a of size ,index & total number of elements in the array n.
Operations-
Create ( ) - This operation create an array.
Insert ( ) - This operation is for inserting elements in the array.
Delete ( ) - This operation is for deleting elements from the array of logical deletion
of element is possible.
Display ( ) - This operation is for display the elements of the array
}

Operations on Array
1. Insertion of elements in array
Insert an element in an array is complex activity because we have to shift the elements
ahead in order to create a space for new element. That means after Inserting an element array
size gets increase by one.
We can implement array using python program. Python doesn‟t support the concept
of array but we can implement the array using lists. List is a sequence of values.
String is also a sequence of values but in string this sequence is of characters. On other-hand,
in case of list the values can be of any type.
The values in the list are called elements or items. These elements are separated by
comma & enclosed with square brackets.
Example – a=[10,20,30,40] #list of integers
B=[“aaa”,”bbb”,”ccc‟‟] #list of strings

Python Program
n=int(input("Enter how many elements you want insert"))
a=[]
i=0
for i in range(n):
item=int(input("Enter element in array"))
a.append(item)
possition=int(input("Enter loation where you want to insert an elements"))
value=int(input("Enter value to insert"))
a=a[:possition]+[value]+a[possition:]
print("Resultant array is ==>",a)

2.Traversing List
The loop is used in list for traversing purpose. The for loop is used to traverse the list
element. Syntax – for variable in List:
Body
Example- a=['a','b','c','d','e']
for i in a:
print(i)
We can traverse the list using range() function. We can access each element of the list
using index of list.
If we want to increment each element of the list by one then we must pass index as
argument to for loop. This can be done using range() function as follows.
a=[10,20,30,40]
for i in range(len(a)):
a[i] = a[i]+1
print(a) # [11,21,31,41]
3.Deleting an elements from array
Deleting an elements from array is complex activity because have to shift the
elements to previous position. That means after Deleting an element size gets decremented by
one.

n=int(input("Enter how many elements you want insert"))


a=[]
i=0
for i in range(n):
item=int(input("Enter element in array"))
a.append(item)

pos=int(input("Enter location where you want to delete an elements"))


a=a[:pos]+a[pos+1:]
print("Resultant array is ==>",a)

4. Merging of two arrays


Merging of two arrays results into a single array in which elements are arranged in
sorted order.
a1=[]
n=int(input("Enter how many elements you want insert in first array"))
for i in range(0,n):
item=int(input("Enter element in array"))
a1.append(item)

a2=[]
m=int(input("Enter how many elements you want insert in second array"))
for i in range(0,m):
item=int(input("Enter element in array"))
a2.append(item)

def mergeArray(a1,a2,n,m):
a3=[None]*(n+m)
i=0
j=0
k=0
while i <n and j<m:
if a1[i]<a2[j]:
a3[k]=a1[i]
k=k+1
i=i+1
else:
a3[k]=a2[j]
k=k+1
j=j+1
while i<n:
a3[k]=a1[i]
k=k+1
i=i+1
while j<m:
a3[k]=a2[j]
k=k+1
j=j+1
print("Merge array")
for i in range(n+m):
print(str(a3[i]),end = " ")
mergeArray(a1,a2,n,m)

Storage Representation and their Address Calculation


The array can be represented using
i) Row major Representation ii) Column Major Representation

i) Row major Representation


If the elements are stored in row wise manner then it is called as Row major
Representation.
Example – if you want to store elements 10 20 30 40 50 60 then in two dimensional array.

The elements will be stored horizontally. To access any elements in two dimensional
array we must specify both its row number & column number. That is why we need two
variables which is act as row index & column index.
In row major matrix, the element at a[i][j] will be equal to
Address of [i][j] = base address + row_index * total no.of column +column_index)* element-size

Example- Consider integer array int arr[3][4] declared in program. If the base address
is 1050, find the address of the element arr[2][3] with row major Representation.
base address + row_index * total no.of column +column_index)* element-size
a[2][3] =1050+(2*4+3)*2 = 1050+(8+3)*2=1050+11*2=1072
ii) Column Major Representation
If elements are stored in column wise manner then it is called as Column Major
Representation.
Example – if you want to store elements 10 20 30 40 50 60 then the elements will be filled
up by column wise manner as follows

In Column major matrix, the element at a[i][j] will be equal to


Address of [i][j] = base address + Column _index * total no.of row +row_index)* element-size
Example- Consider integer array int arr[3][4] declared in program. If the base address
is 1050, find the address of the element arr[2][3] with Column major Representation.
base address + Column _index * total no.of row +row_index)* element-size
a[2][3] =1050+(3*3+2)*2 = 1050+(9+2)*2=1050+11*2=1072
Multidimensional Arrays
Multidimensional Array is an array having more than one dimension.
Popularly two & three dimensional array are used.
The Multi-dimensional array „a‟ is declared as int a[3][3]…..[3] .
Syntax- data_types name_of_array[size1][size2] ….[sizen]
Example- int a[3][3]…..[3];
Two-dimensional arrays
The Two-dimensional array is used to represent the matrix

Program to create Two dimensional array


row=int(input("Enter no. of row for matrix"))
col=int(input("Enter no. of column for matrix"))
A=[[0 for i in range(0,row)] for j in range(0,col)]
print("Enter element of matrix")
for i in range(0,row):
for j in range(0,col):
ele=int(input("Enter Elemets for matrix"))
A[i][j]=ele
print("Matrix A ==> ",A)

Program for performing addition of two matrix


def Add():
C=[[0 for i in range(0,row)] for j in range(0,col)]
for i in range(0,row):
for j in range(0,col):
C[i][j] = A[i][j] + B[i][j]
print("Matrix Addition==> " ,C)

row=int(input("Enter no. of row for matrix"))


col=int(input("Enter no. of column for matrix"))
A=[[0 for i in range(0,row)] for j in range(0,col)]
print("Enter element of matrix")
for i in range(0,row):
for j in range(0,col):
A[i][j] = int(input('\nEnter element A{}{}:'.format(i, j)))
print("Matrix A ==> ",A)

row=int(input("Enter no. of row for matrix"))


col=int(input("Enter no. of column for matrix"))
B=[[0 for i in range(0,row)] for j in range(0,col)]
print("Enter element of matrix")
for i in range(0,row):
for j in range(0,col):
B[i][j] = int(input('\nEnter element A{}{}:'.format(i, j)))
print("Matrix B==> ",B)
Add()

Matrix Multiplication-
def Mul():
C=[[0 for i in range(0,row)] for j in range(0,col)]
for i in range(0,row):
for j in range(0,q):
for k in range(0,col):
C[i][j]=C[i][j]+ A[i][k] * B[k][j]
print("Matrix Addition==> " ,C)

row=int(input("Enter no. of row for matrix"))


col=int(input("Enter no. of column for matrix"))
A=[[0 for i in range(0,row)] for j in range(0,col)]
print("Enter element of matrix")
for i in range(0,row):
for j in range(0,col):
A[i][j] = int(input('\nEnter element A{}{}:'.format(i, j)))
print("Matrix A ==> ",A)

p=int(input("Enter no. of row for matrix"))


q=int(input("Enter no. of column for matrix"))
B=[[0 for i in range(0,p)] for j in range(0,q)]
print("Enter element of matrix")
for i in range(0,p):
for j in range(0,q):
B[i][j] = int(input('\nEnter element A{}{}:'.format(i, j)))
print("Matrix B==> ",B)
Mul()

Transpose of Matrix
def Transpose():
C=[[0 for i in range(0,row)] for j in range(0,col)]
for i in range(0,row):
for j in range(0,col):
C[i][j] = A[j][i]
print(" Transpose of Matrix==> " ,C)

row=int(input("Enter no. of row for matrix"))


col=int(input("Enter no. of column for matrix"))
A=[[0 for i in range(0,row)] for j in range(0,col)]
print("Enter element of matrix")
for i in range(0,row):
for j in range(0,col):
A[i][j] = int(input('\nEnter element A{}{}:'.format(i, j)))
print("Matrix A ==> ",A)
Transpose()

Concept of Ordered List


Ordered List is nothing but a set of elements such as list sometimes called as linear
list. Example 1– list of one digit number [0,1,2,3,4,…….,9]
Example 2– Days in a week
[“Sunday”, “Monday”, “Tuesday”,” Wednesday”, “Thursday”, “Friday”, “Saturday”]
With this concept in mind let us formally define the ordered list.
Definition-
Ordered List is set of elements where set may be emepty or it can be written as a
collection of elements such as [a1, a2 , a3 , a4 , ……. an ]

Operation on Ordered List


1) Display a List 2) Searching a particular elements from the a List
3) Insertion of any element in a List 4) deleting of any elements from the a List
Ordered List can be implemented using list in python. Various operations on list are
possible using following method.
Ordered List Methods-
1. append()
append method adds the element at the end of the list
Example 1-
a=[10,20,30]
print("Original elements in the list", a)
a.append(40)
print("List after adding 40 Elements in the list", a)
Output- Original elements in the list [10, 20, 30]
List after adding 40 Elements in the list [10, 20, 30, 40]

Example 2-
b=['A','B','C']
print("Original elements in the list", b)
b.append('D')
print("List after adding 40 Elements in the list", b)
output- Original elements in the list ['A', 'B', 'C']
List after adding 40 Elements in the list ['A', 'B', 'C', 'D']

2.extend
The extend function takes the list as an argument & appends this list at the end of the
old list
a=[10,20,30]
print("Original elements in the list", a)
b=['A','B','C']
print("Original elements in the list", b)
a.extend(b)
print("List after extend function in the list", a)

output- Original elements in the list [10, 20, 30]


Original elements in the list ['A', 'B', 'C']
List after extend function in the list [10, 20, 30, 'A', 'B', 'C']
sort()
The sort method arrange elements in increasing order.
a=[40,50,10,20,80,90]
print("Original elements in the list", a)
a.sort()
print("List after sort function", a)

output-Original elements in the list [40, 50, 10, 20, 80, 90]
List after sort function [10, 20, 40, 50, 80, 90]

Insert()
This insert method allows us to insert the element at desired position in the list..
a=[10, 20, 40, 50, 60, 70]
print("Original elements in the list", a)
a.insert(2,30)
print("List after insert 30 at index 2 function", a)

"""" output-Original elements in the list [10, 20, 40, 50, 60, 70]
List after insert 30 at index 2 function [10, 20, 30, 40, 50, 60, 70] """

delete()
The deletion of any element from the list is carried out using various function like
pop, remove, del.
If we know the index of the element to be deleted then just use pop function.. the
index as an argument to the pop function.
a=[10, 20, 40, 50, 60, 70]
print("Original elements in the list", a)
a.pop(2)
print("List after pop 30 from index 2 function", a)

output-Original elements in the list [10, 20, 40, 50, 60, 70]
List after pop 30 from index 2 function [10, 20, 50, 60, 70]

If you do not provide any argument to pop function then last element of the list
will be deleted.
a=[10, 20, 40, 50, 60, 70]
print("Original elements in the list", a)
a.pop()
print("List after pop function with no argument ", a)

output-Original elements in the list [10, 20, 40, 50, 60, 70]
List after pop function with no argument [10, 20, 40, 50, 60]

If we know the value of the element to be deleted the the remove function is used.
That means the parameter passed to the remove function is the actual value that is to be
removed from the list.
a=[10, 20, 40, 50, 60, 70]
print("Original elements in the list", a)
a.remove(50)
print("List after remove 50 element ", a)

output-Original elements in the list [10, 20, 40, 50, 60, 70]
List after remove 50 element [10, 20, 40, 60, 70]

In python it is possible to remove more than one element at a time using del function
a=[10, 20, 40, 50, 60, 70]
print("Original elements in the list", a)
del a[2:4] # 4-1 index 3 i.e. 2 and 3 index element will be deleted
print("List after del index from 2 to 4 element ", a)

output-Original elements in the list [10, 20, 40, 50, 60, 70]
List after del index from 2 to 4 element [10, 20, 60, 70]

Built-in List Functions:-


Methods Description Example
index() Returns the index of the first matched item a=[10, 20, 40, 50, 60, 70]
print(" Index of 50 ", a.index(50)) # 3
count() Returns the count of number of items passed a=[10, 20, 40, 50, 60, 50]
as an argument print(" Count of 50 ", a.count(50)) # 2
reverse() Reverse the order of items in the list a= [10,20,30,40,50]
a.reverse()
print("Reverse of a List ",a)
copy() Returns a shallow copy of the list a= [10,20,30,40,50]
print("Copy of a List ",a.copy())
all() If all the elements of the list are true or if the a=[10, 20, 40, 50, 60, 70]
list is empty then this function returns True print("returns ", all(a)) # True
b=[10, 20, 0, 50, 60, 70]
print("returns ", all(b)) # False
List comprehension
List comprehension is an elegant way to create & define new list using
existing list. This is many useful to make a new list where each element is obtained by
applying some operation to each member of another sequence.
List1=[expression for item in the list]
Example-
name= ["ishwar","Rahul","Rohit","Ramesh","Pankaj","Sham","Ram","Vitthal"]
without compression
rname=[]
for title in name:
if title.startswith('R'):
rname.append(title)

print("Another List from name ",rname)


with compression
name= ["ishwar","Rahul","Rohit","Ramesh","Pankaj","Sham","Ram","Vitthal"]
rname=[ title for title in name if title.startswith('R') ]
print("Another List from name ",rname)

Single Variable Polynomial


A Polynomial p(x) is the expression in variable x which is in the form of
(axn + bxn-1 +-------+k) where a,b,c……k fall in real number & „n‟ is non-negative integer,
which is called as degree of the polynomial.
An important characteristics of polynomial is that each term in the polynomial
expression consist of two parts.
1. coefficient 2. exponent
Polynomial – Definition-
Polynomial is the sum of terms where each term consists of variable ,coefficient and
exponent.
A single variable Polynomial can be written as
( an xn + an-1 xn-1 + an-2 xn-2 +-------+ a1x + a0 ) where an ≠ 0 and degree of A(x) is n

Representation of Single Variable Polynomial using arrays


For representing a single variable polynomial one can make use of one dimensional
array.
In single dimensional array 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 :
For e.g. : 3x4 + 5x3 + 7x2 + 10x – 19

Fig- Polynomial Representation


This polynomial can be stored in single dimensional array.

Polynomial Addition
Algorithm:
Assume that the two polynomials say A and B and the resultant polynomial storing
the addition result is stored in one large array.
1. Set a pointer i to point to the first term in a polynomial A.
2. Set a pointer j to point to first term in a polynomial B.
3. Set a pointer k to point to the first position in array C.
4. Read the number of terms of A polynomial in variable tl and read the number of terms of B
polynomial in variable t2 & read the n.
5.While i < tl and j < t2 then
{ if exponent at ith position of A polynomial is equal to the exponent at jth position of
polynomial B then
Add the coefficients at that position from both the polynomial and store the result in C
arrays coefficient field at position k copy the exponent either pointed by i or j at position k in
C array.
Increment i, j and k to point to the next position in the array A, B and C.
}
else
{
if the exponent position i is greater than the exponent at position j in polynomial B
then
{
copy the coefficient at position i from A polynomial into coefficient field at position k
of array C copy the exponent pointed by i into the exponent field at position k in array C.
Increment i, k pointers.
}
else
{
Copy the coefficient at position j of B polynomial into coefficient field at position k in C
array.
Copy the exponent pointed by j into exponent field at position k in C array.
Increment j and k pointers to point to the next position in array B and C.
}
}
while i< t1
{
copy the coefficient at position i of into the coefficient field at position k in C.
copy the exponent pointed by i into the exponent field at position k in C array.
Increment i and k to point to the next position in arrays A and C.
}
while j < t2
{
Copy the coefficient at position j of B into the coefficient field at position k in C.
Copy the exponent pointed by j into exponent field at position k in C.
Increment j, k to point to the next position in B and C arrays.
8. Display the complete array C as the addition of two given polynomials.
9. Stop.

Logic of Addition of two polynomials


Let us take polynomial A and B as follows :
A=3x3 + 2x2 + x + 1
B= 5x3 + 7x
As the term pointed by i & j shows that both term have equal exponent. We can
perform the addition of the terms & we will store the result in the polynomial C.

Now increment i,j,k pointer

Now point I points to 2x2 & pointer j points to 7x as 2x2 >7x. We will copy 2x2 in
polynomial C & we will increment i &k

As the term pointed by i & j shows that both term have equal exponent. We can perform the
addition of the terms & we will store the result in the polynomial C. Now increment i,j,k
pointer.
Now term in polynomial B is over. Hence we will copy remaining term polynomial A to
polynomial C.

Thus the addition of polynomial A & B is in polynomial C.

Polynomial multiplication
Example – if two polynomials given as
3x3 + 2x2 + x +1
× 5x3 + 7x
Then we will perform multiplication by multiplying each term of Polynomial A by each
term of Polynomial B
3x3 + 2x2 + x +1
× 5x3 + 7x
-----------------------------------------------------------------------------------
(15x6 + 10x5 + 5x4 +5x3) + (21x4+ 14x3 + 7x2 +7x)

Multiplied Polynomial A by 5x3 Multiplied Polynomial A by 7x

Now rearranging the term


15x6 + 10x5 + 26x4 +19x3+ 7x2 +7x is the result.

Sparse Matrix
A matrix can be defined as a two dimensional array having „m‟ column & „n‟ rows
representing m * n matrix.
Sparse Matrix are those matrices that have the majority of their elements equal to
zero. In other words, the Sparse Matrix can be defined as the matrix that has greater number
of zero elements than the non-zero element.
Example-

Sparse matrix representation using array


The representation of Sparse Matrix will be a triplet only. That means it store rows ,
column and values.
The 0th row will store that rows of the matrix , total column of the matrix & total
number of non-zero values.
Suppose a matrix is 4 × 5 & number of non-zero term are say 7.
Row- index of the row where non-zero element is located.
Column - index of the column where non-zero element is located.
Value - value of the non-zero element is located at index.

Sparse matrix addition


Algorithm-
1. Obtain the triplet form both Sparse matrix.
2. Create a new triplet to store result matrix.
3. Copy number of rows & column from any sparse matrix to result matrix.
4. Let i,j,k be the indices of sparse matrix 1,2,3 respectively.
5. Initialize i,j,k to 1
6. Traverse both matrices from second row
if(row no. of matrix1== row no. of matrix2)
{ if(column no.of matrix1==column no. of matrix2 )
{ Make the addition of non-zero & store it into result matrix by
incrementing indices.
}
else
{ Which ever has less column value that to result matrix by incrementing
respective indices.
}
}

else
{
Compare row of both sparse matrix & which ever has less row value copy that to
result matrix by incrementing respectively indices.
}
7. Copy stop 6 till end of any matrix triplet.
8. Copy the reaming term of sparse matrix (if any) to resultant matrix.

Transpose of sparse matrix


Simple Transpose of sparse matrix
Algorithm of Transpose of sparse matrix-
1. Obtain the triplet form of sparse matrix.
2. Traverse the triplet from second row and consider column elements.
3. Check if column number is 0 then swap its row and column & add it to transpose of
matrix.
4. Repeat above step for all rows.
5. Repeat step 3 & 4 for the column values from 1,2,3 (total number of column).

Fast transpose of sparse matrix


It is very fast but little complex method to find out transpose of sparse matrix.
Algorithm of Fast transpose of sparse matrix
1. Obtain the triplet from sparse matrix.
2. Create 2 one dimensional array total_array & index_array.
3. Size of total array is the total number of column in the original matrix.
4. At every index of total put the number of times index appears in second column of sparse
matrix.
5. Size of index array = size of total array + 1.
6. Assign index[0]=1 & index[i]=index[i-1]+total[i-1]
7. Now traverse the sparse matrix from second row & consider column elements
8. Location = index[column_number]
9. Locationth index of transpose matrix =swapped row from original matrix
10. Increase index [column_number] by 1
11. Repeat step from 7 to 10 for the remaining triplet of the original matrix.
Time and Space tradeoff
Time space trade-off is basically a situation where either a efficiency (memory
utilization) can be achieved at the cost of time or a time efficiency (performance efficiency)
can be achieved at the cost of memory.
1)In less time by using more memory
2) In less memory by using more time.

Types of Tradeoff-
1. Lookup tables vs. Recalculation
A common situation in an algorithm involving a lookup tables an implementation can include
the entire table which reduces computing time, but increases the amount of memory needed,
or it can compute table entries as needed, increasing computing time, but reducing memory
requirements

2. Compressed vs. uncompressed data


A space-time tradeoff can be applied to the problem of data storage. If data is stored
uncompressed, it takes more space but takes less time.
Depending on the particular instance of the problem, either way is practical. There are
also rare instances where it is possible to directly work with compressed data, such as in the
case of compressed bitmap indices, where it is faster to work with compression than without
compression.

3. Re-rendering vs. stored images


Storing only the SVG source of a vector image and rendering it as a bitmap image
every time the page is requested would be trading time for space; more time used, but less
space.
Rendering the image when the page is changed and storing the rendered images
would be trading space for time; more space used, but less time. This technique is more
generally known as caching.

4. Smaller code vs. loop unrolling


Larger code size can be traded for higher program speed. This technique makes the
code longer for each iteration of a loop, but saves the computation time required for jumping
back to the beginning of the loop at the end each iteration.

You might also like