FDS U2 Technical
FDS U2 Technical
Syllabus
Concept of Sequential Organization, Overview of Array, Array as an Abstract Data Type, Operations
on Array, Merging of two arrays, Storage Representation and their Address Calculation : Row major
and Column Major, Multidimensional Arrays : Two-dimensional arrays, n-dimensional arrays.
Concept of Ordered List, Single Variable Polynomial : Representation using arrays, Polynomial as
array of structure, Polynomial addition, Polynomial multiplication. Sparse Matrix : Sparse matrix
representation using array, Sparse matrix addition, Transpose of sparse matrix- Simple and Fast
Transpose, Time and Space tradeoff.
Contents
2.1 Concept of Sequential Organization
2.2 Array as an Abstract Data Type
2.3 Array Overview
2.4 Operations on Array
2.5 Merging of Two Arrays
2.6 Storage Representation and their Address Calculation
. . . . . . . . . . . . . . . . . Dec.-06, 09, 16, 18, · · · · · · · · · Marks 6
2.7 Multidimensional Arrays
2.8 Concept of Ordered List
2.9 Single Variable Polynomial . . . . . . . . . . . . . . . May-17, 18, · · · · · · · · · · · · · · · Marks 3
2.10 Sparse Matrix . . . . . . . . . . . . . . . . . May-17, 19, Dec.-19, · · · · · · · · Marks 6
2.11 Time and Space Tradeoff
(2 - 1)
Fundamentals of Data Structures 2-2 Linear Data Structure using Sequential Organization
For example : If we want to store names of all the students in a class we can make use
of an array to store the names in sequential form.
Syntax
data_type name_of_array [size] ;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2-3 Linear Data Structure using Sequential Organization
1 20
Index
used to find 2 30
the element
3 40
0 10 0 10
1 20 1 20
2 30 New element 2 30
3 40 44 at position 4 3 44
4 50 4 40
Before 5 50
insertion
After
insertion
· We can implement array using Python program. Python does not support the
concept of array, but we can implement the array using List
· List is a sequence of values.
· String is also sequence of values. But in string this sequence is of characters. On
the 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 commas and enclosed within the square bracket.
For example
[10,20,30,40] # list of integers
[‘aaa’,’bbb’,’ccc’] #list of strings
· The list that contains no element is called empty list. The empty list is represented
by [].
Python Program
print(“\nHow many elements are there in Array?”)
n = int(input())
array = []
i=0
for i in range(n):
print(“\n Enter element in Array”)
item = int(input())
array.append(item)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2-5 Linear Data Structure using Sequential Organization
Logic Explanation
For insertion of any element in the array, we can make use of list slicing technique.
Here is an illustration.
Suppose the array is as follows -
0 1 2 3 4
10 20 30 40 50
array
Position = 4
Element to be inserted = 44
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2-6 Linear Data Structure using Sequential Organization
0 1 2 3 4 5
10 20 30 40 44 50
array
C++ Code
#include <iostream>
using namespace std;
int main()
{
int array[100], position, i, n, value;
cout<<"\n How many elements are there in array";
cin>>n;
cout<<"Enter the elements\n";
for (i = 0; i < n; i++)
cin>>array[i];
cout<<"\n Enter the location where you wish to insert an element: ";
cin>> position;
cout<<"\n Enter the value to insert: ";
cin>>value;
for (i = n - 1; i >= position - 1; i--)//creating space by shifting the element down
array[i + 1] = array[i];
array[position - 1] = value;//at the desired space inserting the element
printf("Resultant array is\n");
for (i = 0; i <= n; i++)
cout<<"\n"<< array[i]);
return 0;
}
(2) Traversing List
· The loop is used in list for traversing purpose. The for loop is used to traverse
the list elements.
Syntax
for VARIABLE in LIST :
BODY
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2-7 Linear Data Structure using Sequential Organization
Example
>>> a=[‘a’,’b’,’c’,’d’,’e’] # List a is created
>>> for i in a:
print(i)
will result into
a
b
c
d
e
>>>
· We can traverse the list using range() function. Using range() function we can
access each element of the list using index of a 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 #incremented each number by one
>>> a
[11, 21, 31, 41]
>>>
(3) Deleting an element from array
· Deleting an element 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.
0 10 0 10
1 20 Element at 1 20
Position 4 is
2 30 deleted 2 30
3 40 3 50
4 50
Python Program
print(“\nHow many elements are there in Array?”)
n = int(input())
array = []
i=0
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2-8 Linear Data Structure using Sequential Organization
for i in range(n):
print(“\n Enter element in Array”)
item = int(input())
array.append(item)
Logic Explanation :
Suppose array is
0 1 2 3 4
10 20 30 40 50
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2-9 Linear Data Structure using Sequential Organization
0 1 3 4
10 20 + 40 50
0 1 2 3
= 10 20 40 50
C++ Code
#include <iostream>
using namespace std;
int main()
{
int array[100], position, i, n;
cout<<"\n How many elements are there in array ";
cin>>n;
cout<<"\nEnter the elements:\n";
for (i = 0; i < n; i++)
cin>>array[i];
cout<<"\n Enter the location of the element which is to be deleted ";
cin>>position;
if (position >= n + 1)
cout<<"Element can not be deleted\n";
else
{
for (i = position - 1; i < n - 1; i++)
array[i] = array[i + 1];
cout<<"\nArray is\n";
for (i = 0; i < n - 1; i++)
cout<<"\n"<< array[i]);
}
return 0;
}
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 10 Linear Data Structure using Sequential Organization
a3
Step 2 :
a1 a2
10 30 50 70 20 40 60 80 Compare a[i] and a[j].
The lesser element is
transferred to a3.
i j
a3
10
k
As a1[i] < a2[j], transfer element a1[i]to a3[k]. Then increment i and k pointer
Step 3 :
a1 a2
10 30 50 70 20 40 60 80 As A[j] is less
than A[i] transfer
i j
it to a3
10 20
a3
a3
10 20 30
k
Increment i and k pointers. In this way we can transfer the elements from two
arrays a1 and a2 to get merged array a3.
Finally we get
10 20 30 40 50 60 70 80
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 11 Linear Data Structure using Sequential Organization
Python Program
def mergeArr(a1,a2,n,m):
a3 = [None]*(n+m)
i=0
j=0
k=0
#traverse both arrays
#if element of first array is less then store it in third array
#if element of second array is less then store it in third array
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
#if elements of first array are remaining
#then transfer them to third array
while i < n:
a3[k] = a1[i]
k=k+1
i=i+1
a2 = []
m = int(input(“Enter total number of elements in second array:”))
for i in range(0,m):
item = int(input(“Enter the element: ”))
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 12 Linear Data Structure using Sequential Organization
a2.append(item)
mergeArr(a1,a2,n,m)
Output
The array can be represented using i) Row Major ii) Column Major Representation.
Row Major Representation
If the elements are stored in rowwise manner then it is called row major
representation.
For example : If we want to store elements
10 20 30 40 50 60 then in a two dimensional array
0 1 2
0 10 20 30
The Þ elements will
be stored 1 40 50 60
horizontally
.
To access any element in two dimensional array we must specify both its row
number and column number. That is why we need two variables which act as row
index and column index.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 13 Linear Data Structure using Sequential Organization
0 1
0 10 40
1 20 50
2 30 60
Each element is occupied at successive locations if the element is of integer type then
2 bytes of memory will be allocated, if it is of floating type then 4 bytes of memory will
be allocated and so on.
For example :
int a [3] [2] = { {10, 20 }
{30, 40}
{50, 60} }
Then in row major matrix
a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[2][1]
10 20 30 40 50 60 …
100 102 104 106 108 110
And in column major matrix
a[0][0] a[1][0] a[2][0] a[0][1] a[1][1] a[2][1]
10 30 50 20 40 60 …
100 102 104 106 108 110
Here each element occupies 2 bytes of memory base address will be 100.
Address calculation for any element will be as follows
In row major matrix, the element a[i] [j] will be at
base address + (row_index * total number of columns + column_index)
* element_size.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 14 Linear Data Structure using Sequential Organization
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 15 Linear Data Structure using Sequential Organization
Review Questions
1. Derive address calculation formula for one dimensional array with one example.
SPPU : Dec.-16, Marks 6
2. Explain two dimensional arrays with row and column major implementation. Explain address
calculation in both cases with example SPPU : Dec.-18, Marks 6
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 16 Linear Data Structure using Sequential Organization
Solution :
# This program stores and displays the elements of two dimensional Array
row_num = int(input(“Input number of rows: ”))
col_num = int(input(“Input number of columns: ”))
arr = [[0 for col in range(col_num)] for row in range(row_num)]
print(arr)
Output
C++ Code
// This program stores and displays the elements of two dimensional Array
cout<<"\nInput number of rows: ";
cin>>row_num;
cout<<"\nInput number of columns: ";
cin>>col_num;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 17 Linear Data Structure using Sequential Organization
int arr[row_num][col_num];
for (row=0;row<row_num;row++)
{
for (col=0;col<col_num;col++)
{
cout<<"Enter the element: ";
cin>>arr[row][col];
}
}
for (row=0;row<row_num;row++)
{
for (col=0;col<col_num;col++)
{
cout<<"\t"arr[row][col];
}
cout<<"\n";
}
(1) Addition of Two Matrices
Consider matrix A and B as follows –
1 2 3 1 1 1 2 3 4
4 5 6 2 2 2 6 7 8
7 8 9 3 3 3 10 11 12
Example 2.7.2 Write a python program for performing addition of two matrices
Solution :
def add_matrix(arr1,arr2):
result = [[arr1[i][j] + arr2[i][j] for j in range(len(arr1[0]))] for i in range(len(arr1))]
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 18 Linear Data Structure using Sequential Organization
#Driver Code
add_matrix(arr1,arr2,)
Output
Input number of rows: 3
Input number of columns: 3
Enter the elements in first matrix: 1
Enter the elements in first matrix: 2
Enter the elements in first matrix: 3
Enter the elements in first matrix: 4
Enter the elements in first matrix: 5
Enter the elements in first matrix: 6
Enter the elements in first matrix: 7
Enter the elements in first matrix: 8
Enter the elements in first matrix: 9
The first matrix is...
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Enter the elements in second matrix: 1
Enter the elements in second matrix: 1
Enter the elements in second matrix: 1
Enter the elements in second matrix: 2
Enter the elements in second matrix: 2
Enter the elements in second matrix: 2
Enter the elements in second matrix: 3
Enter the elements in second matrix: 3
Enter the elements in second matrix: 3
The second matrix is...
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
The Addition of Two Matrices...
[[2, 3, 4], [6, 7, 8], [10, 11, 12]]
>>>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 19 Linear Data Structure using Sequential Organization
1 2 3 1 1 1 14 14 17
4 5 6 2 2 2 32 32 38
7 8 9 3 3 4 50 50 59
Solution :
A = [[1,2,3],
[4,5,6],
[7,8,9]]
B = [[1,1,1],
[2,2,2],
[3,3,4]]
result= [[0,0,0],
[0,0,0],
[0,0,0]]
print(“Matrix A is ...”)
print(A)
print(“Matrix B is ...”)
print(B)
1 2 3 1 4 7
4 5 6 2 5 8
7 8 9 3 6 9
Solution :
A = [[1,2,3],
[4,5,6],
[7,8,9]]
result= [[0,0,0],
[0,0,0],
[0,0,0]]
1
4 2 st
3 1 dimension
5
7 6
15
rows 8 nd
14 2 dimension
9 13
10 18
11 rd
12 17 3 dimension
16
columns
Python Program
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 22 Linear Data Structure using Sequential Organization
Output
C++ Code
/*
This program is for storing and retrieving the elements in a 3-D array
*/
# include<iostream>
using namespace std;
int main()
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 23 Linear Data Structure using Sequential Organization
{
int a[3][2][3]
int i,j,k;
cout<<"\n Enter the elements";
for (i=0; i<3; i++)
{
for(j=0; j<2; j++)
{
for(k=0; k<3; k++)
{
cin>>a[i][j][k];
}
}
}
cout<<"\n Printing the elements \n";
for(i=0; i<3; i++)
{
for (j=0; j<2; j++)
{
for(k=0; k<3; k++)
{
cout<<"\t"<<a[i][j][k];
}
cout<<"\n";
}
cout<<"\n-----------------------------------";
}
return 0;
}
With this concept in mind let us formally define the ordered list.
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 (a1, a2, a3 .................. an).
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 24 Linear Data Structure using Sequential Organization
(3) sort
The sort method arranges the elements in increasing order. For example
>>> a=[‘x’,’z’,’u’,’v’,’y’,’w’]
>>> a.sort()
>>> a
[‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’]
>>>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 25 Linear Data Structure using Sequential Organization
The methods append, extend and sort does not return any value. These methods
simply modify the list. These are void methods.
(4) Insert
This method allows us to insert the data at desired position in the list. The syntax is
insert(index,element)
For example -
>>> a=[10,20,40]
>>> a.insert(2,30)
>>> print(a)
[10, 20, 30, 40]
>>>
(5) Delete
The deletion of any element from the list is carried out using various functions like
pop, remove, del.
If we know the index of the element to be deleted then just pass that index as an
argument to pop function.
For example
>>> a=[‘u’,’v’,’w’,’x’,’y’,’z’]
>>> val=a.pop(1) #the element at index 1 is v, it is deleted
>>> a
[‘u’, ‘w’, ‘x’, ‘y’, ‘z’] #list after deletion
>>> val #deleted element is present in variable val
‘v’
>>>
If we do not provide any argument to the pop function then the last element of the
list will be deleted.
For example -
>>> a =[‘u’,’v’,’w’,’x’,’y’,’z’]
>>> val=a.pop()
>>> a
[‘u’, ‘v’, ‘w’, ‘x’, ‘y’]
>>> val
‘z’
>>>
If we know the value of the element to be deleted then 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. Unlike, pop function the remove function does not return any
value. The execution of remove function is shown by following screenshot.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 26 Linear Data Structure using Sequential Organization
>>> a=[‘a’,’b’,’c’,’d’,’e’]
>>> a.remove(‘c’)
>>> a
[‘a’, ‘b’, ‘d’, ‘e’]
>>>
In python, it is possible to remove more than one element at a time using del
function.
For example
>>> a=[‘a’,’b’,’c’,’d’,’e’]
>>> del a[2:4]
>>> a
[‘a’, ‘b’, ‘e’]
>>>
· There are various built in functions in python for supporting the list operations.
Following table shows these functions
Built-in Purpose
function
all() If all the elements of the list are true or if the list is
empty then this function returns true.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 27 Linear Data Structure using Sequential Organization
· List comprehension is an elegant way to create and define new lists using existing
lists.
· This is mainly useful to make new list where each element is obtained by
applying some operations to each member of another sequence.
Syntax
List=[expression for item in the list]
Example 2.8.1 Write a python program to create a list of even numbers from 0 to 10.
Solution :
even = [] #creating empty list
for i in range(11):
if i % 2 ==0:
even.append(i)
print(“Even Numbers List: ”,even)
even = [] #creating empty list
for i in range(11):
if i % 2 ==0:
even.append(i)
print(“Even Numbers List: ”,even)
Output
Even Numbers List: [0, 2, 4, 6, 8, 10]
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 28 Linear Data Structure using Sequential Organization
Output
[(‘a’, ‘b’), (‘a’, ‘d’), (‘b’, ‘d’)]
Definition : Polynomial is the sum of terms where each term consists of variable,
coefficient and exponent.
Various operations on polynomial are – addition, subtraction, multiplication and
evaluation.
2.9.1 Representation
For representing a single variable 0 –19
polynomial one can make use of one 1 10
dimensional array. In single dimensional Coefficients
2 7
of the polynomial
array the index of an array will act as the 3 5
exponent and the coefficient can be stored 4 3
at that particular index which can be 5
represented as follows :
6
For e.g. : 3x4 + 5x3 + 7x2 + 10x – 19 7
This polynomial can be stored in
Index which acts
single dimensional array. as exponent of
respective coefficient
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.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 29 Linear Data Structure using Sequential Organization
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 30 Linear Data Structure using Sequential Organization
6. 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.
}
7. 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.
3 2 x Polynomial A
3x 2x 1
i pointer
3 Polynomial B
5x 7x
j pointer
Polynomial C
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 31 Linear Data Structure using Sequential Organization
As the terms pointed by i and j shows that both the terms have equal exponent, we
can perform addition of these terms and we will store the result in polynomial C.
3 2 x Polynomial A
3x 2x 1
i pointer
3 Polynomial B
5x 7x
j pointer
3 Polynomial C
8x
k pointer
3 2 x Polynomial A
3x 2x 1
i pointer
3 Polynomial B
5x 7x
j pointer
3 Polynomial C
8x
k pointer
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 32 Linear Data Structure using Sequential Organization
Now pointer i points to 2x2 and pointer j points to 7x. As 2x2 > 7x. We will copy 2x2
in the polynomial C. And we will simply increment i and k pointers
3 2 x Polynomial A
3x 2x 1
i pointer
3 Polynomial B
5x 7x
j pointer
3 2 Polynomial C
8x 2x
k pointer
3 2 x Polynomial A
3x 2x 1
i pointer
3 Polynomial B
5x 7x
j pointer
3 2 Polynomial C
8x 2x 8x
k pointer
Now terms in polynomial B are over. Hence we will copy the remaining terms from
polynomial A to polynomial C.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 33 Linear Data Structure using Sequential Organization
3 2 x Polynomial A
3x 2x 1
3 Polynomial B
5x 7x
3 2 1 Polynomial C
8x 2x 8x
Python Program
# A[] represents coefficients of first polynomial
# B[] represents coefficients of second polynomial
# m and n are sizes of A[] and B[] respectively
def add(A, B, m, n):
size = max(m, n);
C = [0 for i in range(size)]
return C
# Driver Code
if __name__ == ‘__main__’:
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 34 Linear Data Structure using Sequential Organization
B = [0, 7,0, 5]
m = len(A)
n = len(B)
C = add(A, B, m, n)
size = max(m, n)
Output
First polynomial is
1 + 1x^ 1 + 2x^ 2 + 3x^ 3
Second polynomial is
0 + 7x^ 1 + 0x^ 2 + 5x^ 3
Addition of polynomial is
1 + 8x^ 1 + 2x^ 2 + 8x^ 3
>>>
C++ Code
/************************************************************
Program To Perform The Polynomial Addition And To Print
The Resultant Polynomial.
************************************************************/
#include<iostream>
using namespace std;
class APADD
{
private:
struct p
{
int coeff;
int expo;
};
public:
p p1[10],p2[10],p3[10];
int Read(p p1[10]);
int add(p p1[10],p p2[10],int t1,int t2,p p3[10]);
void Print(p p2[10],int t2);
};
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 35 Linear Data Structure using Sequential Organization
/*
------------------------------------------------------------------------------
The Read Function Is For Reading The Two Polynomials
--------------------------------------------------------------------------------
/*
int APADD::Read(p p[10])
{
int t1,i;
cout<<"\n Enter The Total number Of Terms in The Polynomial: ";
cin>>t1;
cout<<"\n Enter The Coef and Exponent In Descending Order";
for(i=0;i<t1;i++)
{
cout<<"\n Enter Coefficient and exponent: ";
cin>>p[i].coeff;
cin>>p[i].expo;
}
return(t1);
}
/*
------------------------------------------------------------
The add Function Is For adding The Two Polynomials
----------------------------------------------------------*/
int APADD::add(p p1[10],p p2[10],int t1,int t2,p p3[10])
{
int i,j,k;
int t3;
i=0;
j=0;
k=0;
while(i<t1 &&j<t2)
{
if(p1[i].expo==p2[j].expo)
{
p3[k].coeff=p1[i].coeff+p2[j].coeff;
p3[k].expo =p1[i].expo;
i++;j++;k++;
}
else if(p1[i].expo>p2[j].expo)
{
p3[k].coeff=p1[i].coeff;
p3[k].expo =p1[i].expo;
i++;k++;
}
else
{
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 36 Linear Data Structure using Sequential Organization
p3[k].coeff=p2[j].coeff;
p3[k].expo =p2[j].expo;
j++;k++;
}
}
while(i<t1)
{
p3[k].coeff=p1[i].coeff;
p3[k].expo =p1[i].expo;
i++;k++;
}
while(j<t2)
{
p3[k].coeff=p2[j].coeff;
p3[k].expo =p2[j].expo;
j++;k++;
}
t3=k;
return(t3);
}
/*
------------------------------------------------------------
The Print Function Is For Printing The Two Polynomials
------------------------------------------------------------
*/
void APADD::Print(p pp[10],int term)
{
int k;
cout<<"\n Printing The Polynomial";
for(k=0;k<term-1;k++)
cout<<" "<<pp[k].coeff<<"X^"<<pp[k].expo<<"+ ";
cout<<pp[k].coeff<<"X^"<<pp[k].expo;
}
/*
------------------------------------------------------------
The main function
------------------------------------------------------------
*/
int main()
{
APADD obj;
int t1,t2,t3;
cout<<"\n Enter The First Polynomial";
t1=obj.Read(obj.p1);
cout<<"\n The First Polynomial is: ";
obj.Print(obj.p1,t1);
cout<<"\n Enter The Second Polynomial";
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 37 Linear Data Structure using Sequential Organization
t2=obj.Read(obj.p2);
cout<<"\n The Second Polynomial is: ";
obj.Print(obj.p2,t2);
cout<<"\n The Addition is: ";
t3=obj.add(obj.p1,obj.p2,t1,t2,obj.p3);
obj.Print(obj.p3,t3);
return 0;
}
Python Program
# A[] represents coefficients of first polynomial
# B[] represents coefficients of second polynomial
# m and n are sizes of A[] and B[] respectively
def mul(A, B, m, n):
return C
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 38 Linear Data Structure using Sequential Organization
# Driver Code
if __name__ == ‘__main__’:
C = mul(A, B, m, n)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 39 Linear Data Structure using Sequential Organization
where x = 1,
= – 10 + 4 + 3 = – 6 + 3
= 3 is the result of polynomial evaluation.
Now, let us see the algorithm for polynomial.
Algorithm :
Step 4 : Then calculate coeff * pow (x, exp) of each term and add the result to sum.
Step 6 : Stop
Python Program
def evalPoly(A,n,x):
result = A[0]
for i in range(1,n):
result = result + A[i]*x**i
return result
# Driver Code
if __name__ == ‘__main__’:
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 40 Linear Data Structure using Sequential Organization
Output
Polynomial is:
1 + 1x^ 1 + 2x^ 2 + 3x^ 3
Enter the value of x: 2
The result of evaluation of polynomial is: 35
>>>
C++ Code
/*************************************************************
Program to evaluate a polynomial in single variable for a
given value of x.
*************************************************************/
#include <iostream>
#include <cmath>
using namespace std;
#define size 20
class APEVAL
{
private:
struct p
{
int coef;
int expo;
};
public:
p p1[size];
int get_poly(p p1[size]);
void display(p p1[size],int n1);
float eval(int n1, p p1[]);
};
/*----------------------------------------------------------
Function get_poly
------------------------------------------------------------*/
int APEVAL::get_poly( p p1[] )
{
int term,n;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 41 Linear Data Structure using Sequential Organization
/*
------------------------------------------------------------
This Function is to display the polynomial
Parameter Passing: By reference and value
------------------------------------------------------------*/
void APEVAL::display(p p1[ ],int n)
{
int term;
for (term = 0; term < n-1 ; term ++ )
cout<<p1[term].coef<<"x^"<<p1[term].expo<<"+ ";
cout<<p1[term].coef<<"x^"<<p1[term].expo;
}
/*----------------------------------------------------------
Function eval
------------------------------------------------------------*/
float APEVAL::eval(int n1, p p1[])
{
int i,sum, x;
cout<<"\nEnter the value for x for evaluation : ";
cin>>x;
sum = 0;
for(i=0; i < n1;i++ )
sum= sum+p1[i].coef *pow( x, p1[i].expo);
return( sum );
}
/*
------------------------------------------------------------
Function main
------------------------------------------------------------
*/
int main()
{
int n1;
int value;
APEVAL obj;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 42 Linear Data Structure using Sequential Organization
Review Question
· In a matrix, if there are m rows and n columns then the space required to store
the numbers will be m ´ n ´ s where s is the number of bytes required to store the
value. Suppose, there are 10 rows and 10 columns and we have to store the
integer values then the space complexity will be bytes.
10 ´ 10 ´ 2 = 200 bytes
1 2 3 1 0 0
4 5 6 0 0 0
7 8 9 0 1 0
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 43 Linear Data Structure using Sequential Organization
· The representation of sparse matrix will be a triplet only. That means it stores
rows, columns and values.
· The 0th row will store total rows of the matrix, total columns of the matrix, and
total non-zero values.
· For example – Suppose a matrix is 6 ´ 7 and number of non zero terms are say 8.
In our sparse matrix representation the matrix will be stored as
Index Row No. Col. No. Value
0 6 7 8
1 0 6 – 10
2 1 0 55
3 2 5 – 23
4 3 1 67
5 3 6 88
6 4 3 14
7 4 4 – 28
8 5 0 99
Python Program
# function display a matrix
def display(matrix):
for row in matrix:
for element in row:
print(element, end =" “)
print()
# sublist
temp.append(i)
temp.append(j)
temp.append(matrix[i][j])
# Driver code
#Original Matrix
A =[ [10, 0, 0, 0],
[0, 20, 0, 0],
[0, 0, 30, 0],
[0, 0, 0, 40],
[0, 50, 0, 0]]
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 45 Linear Data Structure using Sequential Organization
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 46 Linear Data Structure using Sequential Organization
Python Program
def create(s,row_num,col_num,non_zero_values):
s[0][0]= row_num
s[0][1] = col_num
s[0][2] = non_zero_values
for k in range(1,non_zero_values+1):
row = int(input(“Enter row value: ”))
col = int(input(“Enter col value: ”))
element = int(input(“Enter the element: ”))
s[k][0]= row
s[k][1] = col
s[k][2] = element
def display(s):
print(“Row\tcol\t Non_Zero_values”)
for i in range(0,(s[0][2]+1)):
for j in range(0,3):
print(s[i][j], “\t”, end=’’)
print()
def add(s1,s2):
i=1
j=1
k=1
s3 = []
if ((s1[0][0] == s2[0][0]) and (s1[0][1] == s2[0][1])):
#traversing thru all the terms
while ((i <= s1[0][2]) and (j <= s2[0][2])):
if (s1[i][0] == s2[j][0]):
temp =[]
if (s1[i][1] == s2[j][1]):
temp.append(s1[i][0])
temp.append(s1[i][1])
temp.append(s1[i][2]+s2[j][2])
s3.append(temp)
i += 1
j += 1
k += 1
elif (s1[i][1]<s2[j][1]):
temp.append(s1[i][0])
temp.append(s1[i][1])
temp.append(s1[i][2])
s3.append(temp)
i += 1
k += 1
else:
temp.append(s2[j][0])
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 47 Linear Data Structure using Sequential Organization
temp.append(s2[j][1])
temp.append(s2[j][2])
s3.append(temp)
j += 1
k += 1
elif (s1[i][0]<s2[j][0]):
temp =[]
temp.append(s1[i][0])
temp.append(s1[i][1])
temp.append(s1[i][2])
s3.append(temp)
i +=1
k +=1
else:
temp =[]
temp.append(s1[j][0])
temp.append(s1[j][1])
temp.append(s1[j][2])
s3.append(temp)
j +=1
k +=1
#copying remaining terms
while (i <= s1[0][2]): #s1 is greater than s2
temp = []
temp.append(s1[i][0])
temp.append(s1[i][1])
temp.append(s1[i][2])
s3.append(temp)
i += 1
k += 1
while (j <= s2[0][2]): #s2 is greater than s1
temp = []
temp.append(s2[j][0])
temp.append(s2[j][1])
temp.append(s2[j][2])
s3.append(temp)
j += 1
k += 1
#assigning total rows, total columns
#and total non zero values as a first row
#in resultant matrix
s3.insert(0,[s1[0][0],s1[0][1],k-1])
else:
print(“\n Addition is not possible”)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 48 Linear Data Structure using Sequential Organization
Output
Input total number of rows for first matrix: 2
Input total number of columns for first matrix: 2
Input total number of non-zero values: 3
Enter row value: 1
Enter col value: 1
Enter the element: 10
Enter row value: 1
Enter col value: 2
Enter the element: 20
Enter row value: 2
Enter col value: 1
Enter the element: 30
First sparse matrix is
Row col Non_Zero_values
2 2 3
1 1 10
1 2 20
2 1 30
Input total number of rows for second matrix: 2
Input total number of columns for second matrix: 2
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 49 Linear Data Structure using Sequential Organization
{
s3[k][2] = s1[i][2];
s3[k][1] = s1[i][1];
s3[k][0] = s1[i][0];
i++;
k++;
}
else
{
s3[k][2] = s2[j][2];
s3[k][1] = s2[j][1];
s3[k][0] = s2[j][0];
j++;
k++;
}
}//end of 0 if
else if (s1[i][0]<s2[j][0])
{
s3[k][2] = s1[i][2];
s3[k][1] = s1[i][1];
s3[k][0] = s1[i][0];
i++;
k++;
}
else
{
s3[k][2] = s2[j][2];
s3[k][1] = s2[j][1];
s3[k][0] = s2[j][0];
j++;
k++;
}
}//end of while
//copying remaining terms
while (i <= s1[0][2])
{
s3[k][2] = s1[i][2];
s3[k][1] = s1[i][1];
s3[k][0] = s1[i][0];
i++;
k++;
}
while (j <= s2[0][2])
{
s3[k][2] = s2[j][2];
s3[k][1] = s2[j][1];
s3[k][0] = s2[j][0];
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 51 Linear Data Structure using Sequential Organization
j++;
k++;
}
s3[0][2] = k - 1;
}
else
cout<<"\n Addition is not possible";
}
1 0 6 – 10
2 1 0 55
3 2 5 – 23
4 3 1 67
5 3 6 88
6 4 3 14
7 4 4 – 28
8 5 0 99
will become
Index Row No. Col. No. Value
0 7 6 8
1 0 1 55
2 0 5 99
3 1 3 67
4 3 4 14
5 4 4 – 28
6 5 2 – 23
7 6 0 – 10
8 6 3 88
During the transpose of matrix (i) Interchange rows and columns (ii) Also maintain
the rows in sorted order.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 52 Linear Data Structure using Sequential Organization
Python Program
row_num = int(input(“Input number of rows: ”))
col_num = int(input(“Input number of columns: ”))
non_zero_values = int(input(“Input total number of non-zero values: ”))
cols =3
s1 = [[0 for col in range(cols)] for row in range(non_zero_values+1)]
s2 = [[0 for col in range(cols)] for row in range(non_zero_values+1)]
def create(s1,row_num,col_num,cols,non_zero_values):
s1[0][0]= row_num
s1[0][1] = col_num
s1[0][2] = non_zero_values
for k in range(1,non_zero_values+1):
row = int(input(“Enter row value: ”))
col = int(input(“Enter col value: ”))
element = int(input(“Enter the element: ”))
s1[k][0]= row
s1[k][1] = col
s1[k][2] = element
def display(s,cols,non_zero_values):
print(“Row\tcol\t Non_Zero_values”)
for i in range(0,non_zero_values+1):
for j in range(0,cols):
print(s[i][j], “\t”, end=’’)
print()
def transpose(s1,row_num,col_num,s2,cols,non_zero_values):
s2[0][0]= col_num
s2[0][1] = row_num
s2[0][2] = non_zero_values
nxt=1
for c in range(0,col_num):
# for each column scan all the terms for a ‘term’ in that column
for Term in range(1,non_zero_values+1):
if (s1[Term][1] == c):
# Interchange Row and Column
s2[nxt][0] = s1[Term][1]
s2[nxt][1] = s1[Term][0]
s2[nxt][2] = s1[Term][2]
nxt=nxt+1
#Driver Code
create(s1,row_num,col_num,cols,non_zero_values)
print(“Original sparse matrix is”)
display(s1,cols,non_zero_values)
transpose(s1,row_num,col_num,s2,cols,non_zero_values)
print(“Transposed sparse matrix is”)
display(s2,cols,non_zero_values)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 53 Linear Data Structure using Sequential Organization
Output
Logic Explanation :
In above program we look for column values of s1 array starting from 0 to total
number of column value and interchange row and column one by one. For instance –
Consider the output of above program
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 54 Linear Data Structure using Sequential Organization
s1[0][0] =10, the column value is 0 here, we swap the row and column and copy the
column, row and non zero value to s2 array
Locate zero in Col, swap row, col and copy it to s2. At the same time copy
corresponding non-zero-value to s2
s1 s2
0 0 10 0 0 10
0 2 20
1 1 30
2 1 40
Locate 1 in Col, swap row, col and copy it to s2. At the same time copy
corresponding non-zero-value to s2
0 0 10 0 0 10
0 2 20 1 1 30
1 1 30
2 1 40
0 0 10 0 0 10
0 2 20 1 1 30
1 1 30 1 2 40
2 1 40
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 55 Linear Data Structure using Sequential Organization
Locate 2 in Col, swap row, col and copy it to s2. At the same time copy
corresponding non-zero-value to s2
0 0 10 0 0 10
0 2 20 1 1 30
1 1 30 1 2 40
2 1 40 2 1 20
C++ Code
void transp(int s1[size + 1][3], int s2[size + 1][3])
{
int nxt, c, Term;
int n, m, terms;
/*Read Number of rows, columns and terms of given matrix */
n = s1[0][0];
m = s1[0][1];
terms = s1[0][2];
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 56 Linear Data Structure using Sequential Organization
{
/* Interchange Row and Column */
s2[nxt][0] = s1[Term][1];
s2[nxt][1] = s1[Term][0];
s2[nxt][2] = s1[Term][2];
nxt++;
}
}
}
}
}
Python Program
def create(s1,row_num,col_num,cols,non_zero_values):
s1[0][0]= row_num
s1[0][1] = col_num
s1[0][2] = non_zero_values
for k in range(1,non_zero_values+1):
row = int(input(“Enter row value: ”))
col = int(input(“Enter col value: ”))
element = int(input(“Enter the element: ”))
s1[k][0]= row
s1[k][1] = col
s1[k][2] = element
def display(s,cols,non_zero_values):
print(“Row\tcol\t Non_Zero_values”)
for i in range(0,non_zero_values+1):
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 57 Linear Data Structure using Sequential Organization
for j in range(0,cols):
print(s[i][j], “\t”, end=’’)
print()
def transpose(s1,row_num,col_num,s2,cols,non_zero_values):
s2[0][0]= col_num
s2[0][1] = row_num
s2[0][2] = non_zero_values
rterm = []
rpos = []
if non_zero_values > 0:
for i in range(col_num):
rterm.insert(i,0)
for i in range(1,non_zero_values+1):
#rterm[s1[i][1]]++
index = s1[i][1]
val = rterm.pop(index)
rterm.insert(index,val+1)
rpos.insert(0,1)
for i in range(1,col_num+1):
#rpos[i]=rpos[i-1]+ rterm[(i - 1)]
rpos_val=rpos[i-1]
rterm_val=rterm[i-1]
rpos.insert(i,(rpos_val+rterm_val))
for i in range(1,non_zero_values+1):
j = rpos[s1[i][1]]
s2[j][0] = s1[i][1]
s2[j][1] = s1[i][0]
s2[j][2] = s1[i][2]
rpos[s1[i][1]] = j + 1
#Driver Code
create(s1,row_num,col_num,cols,non_zero_values)
print(“Original sparse matrix is”)
display(s1,cols,non_zero_values)
transpose(s1,row_num,col_num,s2,cols,non_zero_values)
print(“Transposed sparse matrix is”)
display(s2,cols,non_zero_values)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 58 Linear Data Structure using Sequential Organization
Output
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 59 Linear Data Structure using Sequential Organization
0 3 3 4
1 0 1 10
2 1 0 20
3 2 0 30
4 2 1 40
We will first consider one dimensional array, named rterm[]. In this array we will
store non zero terms present in each column.
At 0 th column there are two non zero rterm
terms. At 1 st column also there are two non 0 2
zero terms but there is non zero term in 2 nd 1 2
column.
2 0
Similarly we will take another one dimensional array named rpos[]. We initialize 0 th
location of rpos[] by 1. so,
rpos
rpos
Now we use following formula to fill up 0 1
the rpos array.
rpos[i] = rpos[i – 1] + rterm[i – 1]
= 1+ 2 =3+2 =5+0=5
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 60 Linear Data Structure using Sequential Organization
rpos
0 1
1 3
2 5
3 5
rpos[1] points to value 3. That means place the triplet (1, 0, 10) at index 3 in S2
array.
S2
3 1 0 10
rpos
0 1
1 34
2 5
3 5
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 61 Linear Data Structure using Sequential Organization
rpos[0] = 1
S2
1 0 1 20
3 1 0 10
rpos
0 12
1 4
2 5
3 5
rpos[0] = 2
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 62 Linear Data Structure using Sequential Organization
1 0 1 20
2 0 2 30
3 1 0 10
1 4
2 5
3 5
rpos[1] = 4
S2
1 0 1 20
2 0 2 30
3 1 0 10
4 1 2 40
Thus we get
Row Col Non-Zero values
0 3 3 4
1 0 1 20
2 0 2 30
3 1 0 10
4 1 2 40
C++ Code
void trans (int s1[max1][3],int s2[max1][3] )
{
int rterm[max1],rpos[max1];
int j,i ;
int row,col,num ;
row= s1[0][0];
col= s1[0][1];
num= s1[0][2];
s2[0][0] = col;
s2[0][1] = row;
s2[0][2] = num;
if ( num > 0 )
{
for ( i = 0; i <= col ; i ++ )
rterm[i] = 0;
for ( i = 1; i <= num ; i ++ )
rterm[s1[i][1]] ++;
rpos[0] = 1; /*setting the rowwise position*/
for ( i = 1; i <= col; i++ )
rpos[i]=rpos[i-1]+ rterm[(i - 1)];
for ( i = 1; i <= num ; i ++ )
{
j = rpos[s1[i][1]];
s2[j][0] = s1[i][1];
s2[j][1] = s1[i][0];
s2[j][2] = s1[i][2];
rpos[s1[i][1]] = j + 1;
}
}
}
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 64 Linear Data Structure using Sequential Organization
Review Questions
1. Explain fast transpose of sparse matrix with suitable example. Discuss time complexity of fast
transpose. SPPU : May-17, Marks 6
2. Write pseudo code to perform simple transpose of sparse matrix. SPPU : May-19, Marks 4
4. Write a pseudo code to perform the simple transpose of sparse matrix. Also discuss the time
complexity. SPPU : Dec.-19, Marks 6
C Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],b[10],n,mid,i,j,temp;
clrscr();
printf(“\n How many elements do you want? ”);
scanf(“%d”,&n);
printf(“\n Enter the elements in the ascending order ”);
for(i=0;i<n;i++)
{
printf(“\n Enter the element ”);
scanf(“%d”,&a[i]);
}
printf(“\nThe elements in descending order(By Method 1) are ...\n”);
j=0;
for(i=n–1;i>=0;i–)// reading the array in reverse direction
{
b[j]=a[i];//storing them in another array
j++;
}
for(j=0;j<n;j++) This method makes use of some
printf(“ %d”,b[j]); computations for storing the
elements in descending order. It
makes use of the same array. Hence
printf(“\nThe elements in descending
less amount of space is needed at
order(By Method 2) are ...\n”);
mid=n/2; the cost of addition computational
for(i=0;i<mid;i++) time.
{
j=(n–1)–i;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
for(i=0;i<n;i++)
printf(“ %d”,a[i]);
getch();
}
Output (Run 1)
How many elements do you want? 5
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 66 Linear Data Structure using Sequential Organization
Output (Run 2)
How many elements do you want? 6
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge