FDS Unit II
FDS Unit II
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].
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.
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)
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
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)
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)
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 [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]
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.
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.
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)
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-
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.
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