0% found this document useful (0 votes)
16 views

FDS U2 Technical

this the technical book of fundamentals of data structure unit 2

Uploaded by

suncrest5000
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)
16 views

FDS U2 Technical

this the technical book of fundamentals of data structure unit 2

Uploaded by

suncrest5000
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/ 66

Unit - II

Linear Data Structure


2 using Sequential Organization

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

2.1 Concept of Sequential Organization


Arrays is refered as the sequential organization that means the data in arrays is
stored in some sequence.

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.

Defintion of Arrays : Array is a set of consecutive memory locations which contains


similar data elements.
Array is basically a set of pair-index and the value.

Syntax
data_type name_of_array [size] ;

For example, int a [10]; double b[10] [10];


Here ‘a’ is the name of the array inside the square bracket size of the array is given.
This array is of integer type i.e. all the elements are of integer type in array ‘a’.

Advantages of sequential organization of data structure


1. Elements can be retrieved or stored very efficiently in sequential organization with
the help of index or memory location.
2. All the elements are stored at continuous memory locations. Hence searching of
element from sequential organization is easy.

Disadvantages of sequential organization of data structure


1. Insertion and deletion of elements becomes complicated due to sequential nature.
2. For storing the data large continuous free block of memory is required.
3. Memory fragmentation occurs if we remove the elements randomly.

2.2 Array as an Abstract Data Type


The abstract data type is written with the help of instances and operations.
We make use of the reserved word AbstractDataType while writing an ADT.
AbstractDataType Array
{
Instances : An array A of some size, index i and total number of
elements in the array n.
Operations :
1. Create () – This operation creates an array.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2-3 Linear Data Structure using Sequential Organization

2. Insert() - This operation is for inserting the element in an array


3. Delete() - This operation is for deleting the elements from the array.
Only logical deletion of the element is possible.
4. display () – This operation displays the elements of the array.
}

2.3 Array Overview


Definition: Array is a collection of similar type of elements.
The arrays can be one dimensional, two dimensional, or multidimensional.
One dimensional array :
The one dimensional array 'a' is declared as int a[10];
a
0 10 Value stored in array

1 20
Index
used to find 2 30
the element
3 40

Two dimensional array :


If we declare a two dimensional array as
int a[10] [3];
Then it will look like this -
Column
¯
0 1 2
row ® 0 10 20 30
1 40 50 60
2
.
.
.
9
The two dimensional array should be in row-column form.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2-4 Linear Data Structure using Sequential Organization

2.4 Operations on Array


(1) Insertion of Element in Array
· Inserting 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 incremented by one.

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

print(“Enter the location where you want to insert an element”)


position = int(input())

print(“Enter the value to insert”)


value = int(input())
array=array[:position]+[value]+array[position:]
print(“Resultant array is\n”)
print(array)
Output

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

array [:position] + value + array [position]


0 1 2 3
10 20 30 40 + 44 + 50
array array

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)

print(“Enter the index from where you want to delete an element”)


position = int(input())
array=array[:position]+array[position+1:]
print(“Resultant array is\n”)
print(array)
Output

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

Position = 2. That meants we want to delete an element 30, then

array [:position] + array [position + 1:]

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;
}

2.5 Merging of Two Arrays


Merging of two arrays result into a single array in which elements are arranged in
sorted order.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 10 Linear Data Structure using Sequential Organization

For example - consider two arrays as follows


Step 1 :
a1 a2
10 30 50 70 20 40 60 80

Create empty resultant array named a3

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

As a2[j] is transferred to a3 array increment j and k pointer.


Step 4 :
a1 a2
10 30 50 70 20 40 60 80
i j

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

#if elements of second array are remaining


#then transfer them to third array
while j < m:
a3[k] = a2[j]
k=k+1
j=j+1

#display the resultant merged array


print(“Merged Array is ...”)
for i in range (n+m):
print(str(a3[i]), end = “ ”)
#Driver Code
a1 = []
n = int(input(“Enter total number of elements in first array:”))
for i in range(0,n):
item = int(input(“Enter the element: ”))
a1.append(item)

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

2.6 Storage Representation and their Address Calculation


SPPU : Dec.-06, 09, 16, 18, Marks 6

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

Column Major Representation


If elements are stored in column wise manner then it is called column major
representation.
For example : If we want to store elements
10 20 30 40 50 60 then the elements will be filled up by
columnwise manner as follows (consider array a[3] [2]). Here 3 represents number of
rows and 2 represents number of columns.

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

In column major matrix, the element at a[i] [j] will be at


base address + (column_index * total number of rows + row_index) * element.
In C normally the row major representation is used.
Example 2.6.1 Consider integer array int arr[3][4] declared in ‘C’ program. If the base address
is 1050, find the address of the element arr[2][3] with row major and column major
representation of array. SPPU : Dec.-06, Marks 6
Solution : Row Major Representation
The element a[i][j] will be at
a[i][j]=base address+(row_index*total number of columns + column_index )
*element_size
= (base address+(i*col_size+j)*element_size)
when i=2 and j=3, element_size=int occupies 2 bytes of memory hence it is 2
total number of columns=4,
a[2][3] = 1050+(2*4+3)*2
= 1050+22
a[2][3] = 1072
Column Major Representation
The element a[i][j] will be at
a[i][j] = base address+(col_index*total number of
rows+row_index)*element_size
= (base address+(j*row_size+i)*element_size)

when i=2 and j=3 ,element_size=int occupies 2 bytes of memory hence it is 2


total number of rows=3
a[2][3] = 1050+(3*3+2)*2
= 1050+22
a[2][3] = 1072
Example 2.6.2 Consider integer array int arr[4][5] declared in ‘C’ program. If the base
address is 1020, find the address of the element arr[3][4] with row major and column major
representation of array. SPPU : Dec.-09, Marks 6
Solution : Row Major Representation
The element a[i][j] will be at

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 15 Linear Data Structure using Sequential Organization

a[i][j] = base address+(row_index*total number of columns +


col_index)*element_size
= (base address+( i*col_size+j)*element_size)

when i=3 and j=4 ,element_size=int occupies 2 bytes of memory hence it is 2


total number of columns=5
a[3][4] = 1020+(3*5+4)*2
= 1020+38
a[3][4] = 1058

Column Major Representation


The element a[i][j] will be at
a[i][j] = base address+(col_index*total number of
rows+row_index)*element_size
= (base address+(j*row_size+i)*element_size)

when i=3 and j=4, element_size=int occupies 2 bytes of memory hence it is 2


total number of rows = 4
a[3][4] = 1020+(4*4+3)*2
= 1020+38
a[3][4] = 1058

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

2.7 Multidimensional Arrays


Multidimensional array is an array having more than one dimension. Popularly, two
and three dimensional arrays are used.

2.7.1 Two Dimensional Array


The two dimensional array is used to represent the matrix.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 16 Linear Data Structure using Sequential Organization

Various operations that can be performed on matrix are –


(1) Matrix Addition (2) Matrix Multiplication and (3) Transpose of Matrix
Let us discuss the implementation of various matrix operations
Example 2.7.1 Write a python program for representation two dimensional matrix.

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)]

for row in range(row_num):


for col in range(col_num):
item = int(input(“Enter the element: ”))
arr[row][col]= item

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 –

Matrix A Matrix B Addition of Matrices is

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))]

print(“The Addition of Two Matrices...”)


print(result)
row_num = int(input(“Input number of rows: ”))
col_num = int(input(“Input number of columns: ”))
arr1 = [[0 for col in range(col_num)] for row in range(row_num)]
for row in range(row_num):
for col in range(col_num):
item = int(input(“Enter the elements in first matrix: ”))
arr1[row][col]= item

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 18 Linear Data Structure using Sequential Organization

print(“The first matrix is...”)


print(arr1)

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


for row in range(row_num):
for col in range(col_num):
item = int(input(“Enter the elements in second matrix: ”))
arr2[row][col]= item

print(“The second matrix is...”)


print(arr2)

#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

(2) Matrix Multiplication

Consider matrix A Consider matrix B The resultant matrix is

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

Example 2.7.3 Write a python program to implement matrix multiplication operation.

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)

# iterate through rows of X


for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]

print(“Matrix Multiplication is ...”)


for r in result:
print(r)
Output
Matrix A is ...
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Matrix B is ...
[[1, 1, 1], [2, 2, 2], [3, 3, 4]]
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 20 Linear Data Structure using Sequential Organization

Matrix Multiplication is ...


[14, 14, 17]
[32, 32, 38]
[50, 50, 59]
>>>

(3) Transpose of Matrix

Consider matrix A Transposed matrix

1 2 3 1 4 7

4 5 6 2 5 8

7 8 9 3 6 9

Example 2.7.4 Write a Python program for performing transpose of matrix.

Solution :
A = [[1,2,3],
[4,5,6],
[7,8,9]]

result= [[0,0,0],
[0,0,0],
[0,0,0]]

print(“Original Matrix is...”)


print(A)

# iterate through rows


for i in range(len(A)):
for j in range(len(A[0])):
result[j][i] = A[i][j]

print(“Transposed Matrix is ...”)


for r in result:
print(r)
Output
Original Matrix is...
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Transposed Matrix is ...
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
>>>
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 21 Linear Data Structure using Sequential Organization

2.7.2 Three Dimensional Array


The multidimensional array is similar to the two dimensional array with multiple
dimensions for example Here is 3-D array
a [ 3] [ 2] [ 3] = { { {1, 2, 3}, {4 , 5, 6} },
dimension
{ {7 , 8, 9}, {10,11,12} },
rows column { {13,14 ,15} {16,17 ,18} }
}

We can represent it graphically as

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

row_num = int(input(“Input number of rows: ”))


col_num = int(input(“Input number of columns: ”))
dim_num = int(input(“Input number of dimensions: ”))
arr1 =[]#creating an empty list
for dim in range(dim_num):
arr1.append([])
for row in range(row_num):
arr1[dim].append([])
for col in range(col_num):
item = int(input(“Enter Element: ”))
arr1[dim][row].append(item)

print(“\n Elements in 3D Array are...”)


for dim in range(dim_num):
for row in range(row_num):
for col in range(col_num):
print(arr1[dim][row][col],end =" “)
print()
print(“——————-”)

®
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;
}

2.8 Concept of Ordered List


Ordered list is nothing but a set of elements. Such a list sometimes called as linear
list.
For example
1. List of one digit numbers
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
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 : 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

Operations on ordered list


Following operations can be possible on an ordered list.
1. Display of list
2. Searching a particular element from the list
3. Insertion of any element in the list
4. Deletion of any element from the list
Ordered List can be implemented using the List data structure in Python.
Various operations on List are possible using following methods

2.8.1 Ordered List Methods


(1) append
The append method adds the element at the end of the list. For example
>>> a=[10,20,30]
>>> a.append(40) #adding element 40 at the end
>>> a
[10, 20, 30, 40]
>>> b=[‘A’,’B’,’C’]
>>> b.append(‘D’) #adding element D at the end
>>> b
[‘A’, ‘B’, ‘C’, ‘D’]
>>>
(2) extend
The extend function takes the list as an argument and appends this list at the end of
old list. For example
>>> a=[10,20,30]
>>> b=[‘a’,’b’,’c’]
>>> a.extend(b)
>>> a
[10, 20, 30, ‘a’, ‘b’, ‘c’]
>>>

(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’]
>>>

2.8.2 Built in Functions

· 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.

any() If the list contains any element true or if the list is


empty then this function returns true.

len() This function returns the length of the string.

max() This function returns maximum element present in the


list.

min() This function returns minimum element present in the


list.

sum() This function returns the sum of all the elements in


the list.

sorted() This function returns a list which is sorted one.

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 27 Linear Data Structure using Sequential Organization

For example - Following screenshot of python shell represents execution of various


built in functions –

2.8.3 List Comprehension

· 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

Program explanation : In above program,


1) We have created an empty list first.
2) Then using the range of numbers from 0 to 11 we append the empty list with even
numbers. The even number is test using the if condition. i.e. if I %2= =0. If so then
that even number is appended in the list.
3) Finally the comprehended list will be displayed using print statement.
Example 2.8.2 Write a python program to combine and print two lists using list
comprehension.
Solution :
print([(x,y)for x in[‘a’,’b’] for y in [‘b’,’d’] if x!=y])

Output
[(‘a’, ‘b’), (‘a’, ‘d’), (‘b’, ‘d’)]

2.9 Single Variable Polynomial SPPU : May-17, 18, Marks 3

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

2.9.2 Polynomial Addition Fig. 2.9.1 Polynomial representation

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

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 t1 and read
the number of terms of B polynomial in variable t2.
5. While i < t1 and j < t2 then
{ if exponent at ith position of A poly 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.
}
}

®
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.

Logic of Addition of two polynomials


Let us take polynomial A and B as follows :
3x3 + 2x2 + x + 1
5x3 + 7x

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

Now increment i, j, and k pointers.

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

Thus the addition of polynomials A and B is in polynomial C.

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)]

for i in range(0, m, 1):


#Each term from first polynomial to C array
C[i] = A[i]
# Add each term of second poly and add it to C
for i in range(n):
C[i] += B[i]

return C

# A function to print a polynomial


def display(poly, n):
for i in range(n):
print(poly[i], end = “”)
if (i != 0):
print(“x^”, i, end = “”)
if (i != n - 1):
print(“ + ”, end = “”)

# Driver Code
if __name__ == ‘__main__’:

# The following array represents


# polynomial 1 + 1x +2x^2+ 3x^3
A = [1, 1, 2, 3]

# The following array represents


# polynomial 7x + 5x^3

®
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)

print(“\nFirst polynomial is”)


display(A, m)
print(“\nSecond polynomial is”)
display(B, n)

C = add(A, B, m, n)
size = max(m, n)

print(“\n Addition of polynomial is”)


display(C, size)

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;
}

2.9.3 Polynomial Multiplication


We will now discuss another operation on polynomials and that is multiplication.
For example
If two polynomials are 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
6 + 5
15x
1444 10x 5x 4 + 5x33 + 21x
42+4444 1444
4 + 14x 3 + 7x 2 + 7x
424444 3
Multiplied poly A by 5x 3 Multiplied poly A by 7x

Now rearranging the terms

15x6 + 10x5 + 26x4 + 19x3 + 7x2 + 7x is a resultant polynomial

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):

#allocating total size for resultant array


C = [0]* (m+n-1)
for i in range(0, m, 1):
#multiplying by current term of first polynomial
#to each term of second polynomial
for j in range(n):
C[i+j] += A[i]*B[j]

return C

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 38 Linear Data Structure using Sequential Organization

# A function to print a polynomial


def display(poly, n):
for i in range(n):
print(poly[i], end = “”)
if (i != 0):
print(“x^”, i, end = “”)
if (i != n - 1):
print(“ + ”, end = “”)

# Driver Code
if __name__ == ‘__main__’:

# The following array represents


# polynomial 1 + 1x +2x^2+ 3x^3
A = [1, 1, 2, 3]

# The following array represents


# polynomial 7x + 5x^3
B = [0, 7,0, 5]
m = len(A)
n = len(B)

print(“\nFirst polynomial is”)


display(A, m)
print(“\nSecond polynomial is”)
display(B, n)

C = mul(A, B, m, n)

print(“\n Multiplication of polynomial is...”)


display(C, m+n-1)
Output
First polynomial is
1 + 1x^ 1 + 2x^ 2 + 3x^ 3
Second polynomial is
0 + 7x^ 1 + 0x^ 2 + 5x^ 3
Multiplication of polynomial is...
0 + 7x^ 1 + 7x^ 2 + 19x^ 3 + 26x^ 4 + 10x^ 5 + 15x^ 6
>>>

2.9.4 Polynomial Evaluation


We will now discuss the algorithm for evaluating the polynomial.
Consider the polynomial for evaluation –
- 10x7 + 4 x5 + 3x 2

®
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 1 : Read the polynomial array A

Step 2 : Read the value of x.

Step 3 : Initialize the variable sum to zero.

Step 4 : Then calculate coeff * pow (x, exp) of each term and add the result to sum.

Step 5 : Display “ 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

def display(poly, n):


for i in range(n):
print(poly[i], end = “”)
if (i != 0):
print(“x^”, i, end = “”)
if (i != n - 1):
print(“ + ”, end = “”)

# Driver Code
if __name__ == ‘__main__’:

# The following array represents


# polynomial 1 + 1x +2x^2+ 3x^3
A = [1, 1, 2, 3]
n = len(A)
print(“\n Polynomial is: ”);
display(A,n)

x = int(input(“\nEnter the value of x: ”))


print(“\nThe result of evaluation of polynomial is: ”,evalPoly(A,n,x))

®
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;

cout<<"\nHow Many Terms are there? ";


cin>>n;
if (n>size)
{
cout<<"Invalid number Of Terms\n";
getch();
return;
}
cout<<"\nEnter the terms of the Polynomial ";
cout<<"in descending order of the exponent\n";

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 41 Linear Data Structure using Sequential Organization

for (term = 0; term < n ; term ++ )


{
cout<<"Enter coefficient and exponenet: ";
cin>>p1[term].coef;
cin>>p1[term].expo;
}
return( n);
}

/*
------------------------------------------------------------
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

cout<<"\n Enter the Polynomial";


n1 =obj.get_poly(obj.p1);
cout<<"The First polynomial is : \n";
obj.display(obj.p1,n1);
value = obj.eval(n1,obj.p1);
cout<<"\n The Resultant Value of the polynomial is : "<<value<<"\n";
return 0;
}

Review Question

1. Explain polynomial representation using arrays with suitable example.


SPPU : May-17, 18, Marks 3

2.10 Sparse Matrix SPPU : May-17, 19, Dec.-19, Marks 6

· 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

(Here 2 bytes are required to store an integer value.)


· It is observed that, many times we deal with matrix of size m ´ n and values of m
and n are reasonably higher and only a few elements are non zero. Such matrices
are called sparse matrices.
· Definition: Sparse matrix is a matrix containing few non zero elements.
· For example - if the matrix is of size 100 ´ 100 and only 10 elements are non zero.
Then for accessing these 10 elements one has to make 10000 times scan. Also only
10 spaces will be with non-zero elements remaining spaces of matrix will be filled
with zeros only. i.e. we have to allocate the memory of 100 ´ 100 ´ 2 = 20000.
· Hence sparse matrix representation is a kind of representation in which only non
zero elements along with their rows and columns is stored.

1 2 3 1 0 0

4 5 6 0 0 0

7 8 9 0 1 0

Dense Matrix Sparse Matrix

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 43 Linear Data Structure using Sequential Organization

2.10.1 Sparse Matrix Representation using Array

· 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()

# function to convert the matrix


# into a sparse matrix
def convert(matrix):
SP =[]
# searching values greater
# than zero
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != 0 :

# creating a temporary sublist


temp = []

# appending row value, column


# value and element into the
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 44 Linear Data Structure using Sequential Organization

# sublist
temp.append(i)
temp.append(j)
temp.append(matrix[i][j])

# appending the sublist into


# the sparse matrix list
SP.append(temp)

# displaying the sparse matrix


print(“\nSparse Matrix: ”)
print(“Row Col Non_Zero_Value”)
display(SP)

# 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]]

# displaying the matrix


display(A)

# converting the matrix to sparse


convert(A)
Output

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 45 Linear Data Structure using Sequential Organization

2.10.2 Sparse Matrix Addition


Algorithm :
1. Start
2. Read the two sparse matrices say SP1 and SP2 respectively.
3. The index for SP1 and SP2 will be i and j respectively. Non zero elements
are n1 and n2 for SP1 and SP2.
4. The k index will be for sparse matrix SP3 which will store the addition of
two matrices.
5. If SP1 [0][0] > SP2 [0][0] i.e. total number of rows then
SP3 [0][0] = SP1 [0][0]
else
SP3 [0][0] = SP2 [0][0]
Similarly check in SP1 and SP2 the value of total number of columns which ever
value is greater transfer it to SP3.
Set i = 1, j = 1, k = 1.
6. When i < n1 and j < n2.
7. a) If row values of SP1 and SP2 are same then check also column values
are same, if so add the non-zero values of SP1 and SP2 and store them in
SP3, increment i, j, k by 1.
b) Otherwise if colno of SP1 is less than colno of SP2 copy the row, col and
nonzero value of SP1 to SP3. Increment i and k by 1.
c) Otherwise copy the row, col and non-zero value of SP2 to SP3.
Increment j and k by 1.
8. When rowno of SP1 is less than SP2 copy row, col and non-zero element
of SP1 to SP3. Increment i and k by 1.
9. When rowno of SP2 is less than SP1 copy row, col and non-zero element
of SP2 to SP3. Increment j, k by 1. Repeat step 6 to 9 till condition is true.
10. Finally whatever k value that will be total number of non-zero values in
SP3 matrix.
\ SP3 [0][2] = k
11. Print SP3 as a result.
12. Stop.

®
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”)

print(“Addition of Sparse Matrix ...”)


print(“\nRow Col Non_Zero_values”)

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 48 Linear Data Structure using Sequential Organization

for row in s3:


for element in row:
print(element, end =" “)
print()
#Driver Code
row_num1 = int(input(“Input total number of rows for first matrix: ”))
col_num1 = int(input(“Input total number of columns for first matrix: ”))
non_zero_values1 = int(input(“Input total number of non-zero values: ”))
cols =3
s1 = [[0 for col in range(cols)] for row in range(non_zero_values1+1)]
#creating first sparse matrix
create(s1,row_num1,col_num1,non_zero_values1)
print(“First sparse matrix is”)
display(s1)

row_num2 = int(input(“Input total number of rows for second matrix: ”))


col_num2 = int(input(“Input total number of columns for second matrix: ”))
non_zero_values2 = int(input(“Input total number of non-zero values: ”))
s2 = [[0 for col in range(cols)] for row in range(non_zero_values2+1)]
#creating second sparse matrix
create(s2,row_num2,col_num2,non_zero_values2)
print(“Second sparse matrix is”)
display(s2)
#Performing and displaying addition of two sparse matrices
add(s1,s2)

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

Input total number of non-zero values: 2


Enter row value: 2
Enter col value: 1
Enter the element: 5
Enter row value: 2
Enter col value: 2
Enter the element: 40
Second sparse matrix is
Row col Non_Zero_values
2 2 2
2 1 5
2 2 40
Addition of Sparse Matrix ...

Row Col Non_Zero_values


2 2 4
1 1 10
1 2 20
2 1 35
2 2 40
>>>
C++ code

Following is a C++ function for addition of two sparse matrices


void add(int s1[10][3],int s2[10][3],int s3[10][3])
{
int i, j, k;
i = 1; j = 1; k = 1;
if ((s1[0][0] == s2[0][0]) && (s1[0][1] == s2[0][1]))
{
s3[0][0] = s1[0][0];
s3[0][1] = s1[0][1];
//traversing thru all the terms
while ((i <= s1[0][2]) && (j <= s2[0][2]))
{
if (s1[i][0] == s2[j][0])
{
if (s1[i][1] == s2[j][1])
{
s3[k][2] = s1[i][2] + s2[j][2];
s3[k][1] = s1[i][1];
s3[k][0] = s1[i][0];
i++;
j++;
k++;
}
else if (s1[i][1]<s2[j][1])
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 50 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";
}

2.10.3 Transpose of Sparse Matrix


We will now discuss the algorithm for performing transpose of sparse matrix.
For eg :
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

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

Row Col Non_Zero_values Row Col Non_Zero_values

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

Row Col Non_Zero_values Row Col Non_Zero_values

0 0 10 0 0 10

0 2 20 1 1 30

1 1 30

2 1 40

Row Col Non_Zero_values Row Col Non_Zero_values

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

Row Col Non_Zero_values Row Col Non_Zero_values

0 0 10 0 0 10

0 2 20 1 1 30

1 1 30 1 2 40

2 1 40 2 1 20

Thus we get transposed matrix in the form of sparse matrix representation.

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];

/* Interchange Number of rows with number of columns */


s2[0][0] = m;
s2[0][1] = n;
s2[0][2] = terms;
if (terms > 1) /* if nonzero matrix then */
{
nxt = 1; /* Gives next position in the transposed matrix */
/* Do the transpose columnwise */
for (c = 0; c <= m; c++)
{
/* for each column scan all the terms for a term in that column */
for (Term = 1; Term <= terms; Term++)
{
if (s1[Term][1] == c)

®
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++;
}
}
}
}
}

Time complexity of simple transpose:


The simple transpose of sparse matrix can be performed using two nested for loops.
Hence the time complexity is O(n 2 )

2.10.4 Fast Transpose


The fast transpose is a transpose method in which matrix transpose operation is
performed efficiently. In this method an auxiliary array are used to locate the position of
the elements to be transposed sequentially.
Here is an implementation of fast transpose of sparse matrix in Python.

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):
®
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

Logic for Fast Transpose


Consider the sparse matrix representative as
S1

Index Row Col Non-Zero values

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]

i=1 i=2 i=3

rpos[1] = rpos[0] + rterm[0] rpos[2] = rpos[1] + rterm[1] rpos[3] = rpos[2] + rterm[2]

= 1+ 2 =3+2 =5+0=5

rpos = 3 rpos[2] = 5 rpos[3] = 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

Now we will read values of S1 array from 1 to 4.


We must find the triplet from S1 array which is at index 1. it is (0, 1, 10)

index row col value row col value


Just interchange
1 0 1 10 row and col. 1 0 10
S1
Since value is 1,
check rpos[1]

rpos[1] points to value 3. That means place the triplet (1, 0, 10) at index 3 in S2
array.

S2

Row Col Non-Zero values

3 1 0 10

Now since rpos[1] is read just now, increment rpos[1] value by 1.


Hence

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

Read next element from S1 array

index row col value row col value


Interchange
2 1 0 20 0 1 20

rpos[0] = 1

That mean place triplet (0, 1, 20) at index 1 in S2 array

S2

Row Col Non-Zero values

1 0 1 20

3 1 0 10

Since rpos[0] is read just now, increment rpos[0] by 1.

rpos
0 12

1 4

2 5

3 5

Read next element from S1 array

index row col value row col value


Interchange
3 2 0 30 0 2 30

rpos[0] = 2

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 62 Linear Data Structure using Sequential Organization

That means place triplet (0, 2, 30) at index 2 in S2 array.


S2

Row Col Non-Zero values

1 0 1 20

2 0 2 30

3 1 0 10

Since rpos[0] is read just now increment rpos[0] by 1.


rpos
0 2 3

1 4

2 5

3 5

Read next element from S1 array

index row col value row col value


Interchange
4 2 1 40 1 2 40

rpos[1] = 4

That means place triple (1, 2, 40) at index 2 in S2 array.

S2

Row Col Non-Zero values

1 0 1 20

2 0 2 30

3 1 0 10

4 1 2 40

Thus we get transposed sparse matrix.


Finally we fill up S2[0] by total number of rows, total number of colums and total
number of non-zero values.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 63 Linear Data Structure using Sequential Organization

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

Time Complexity of Fast Transpose


For transposing the elements using simple transpose method we need two nested for
loops but in case of fast transpose we are determining the position of the elements that
get transposed using only one for loop. Hence the time complexity of fast transpose is
O(n)

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

3. What is sparse matrix ? Explain its representation with an example.


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

2.11 Time and Space Tradeoff


Basic concept : Time space trade-off is basically a situation where either a space
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.
Example 1 : Consider the programs like compilers in which symbol table is used to
handle the variables and constants. Now if entire symbol table is stored in the program
then the time required for searching or storing the variable in the symbol table will be
reduced but memory requirement will be more. On the other hand, if we do not store
the symbol table in the program and simply compute the table entries then memory will
be reduced but the processing time will be more.
Example 2 : Suppose, in a file, if we store the uncompressed data then reading the
data will be an efficient job but if the compressed data is stored then to read such data
more time will be required.
Example 3 : This is an example of reversing the order of the elements. That is, the
elements are stored in an ascending order and we want them in the descending order.
This can be done in two ways -
· We will use another array b[] in which the elements in descending order can be
arranged by reading the array a[] in reverse direction. This approach will actually
increase the memory but time will be reduced.
· We will apply some extra logic for the same array a[] to arrange the elements in
descending order. This approach will actually reduce the memory but time of
execution will get increased.
The illustration of above mentioned example is given be following C program -
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 65 Linear Data Structure using Sequential Organization

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

Enter the elements in the ascending order


Enter the element 11

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fundamentals of Data Structures 2 - 66 Linear Data Structure using Sequential Organization

Enter the element 22


Enter the element 33

Enter the element 44

Enter the element 55


The elements in descending order(By Method 1) are ...
55 44 33 22 11
The elements in descending order(By Method 2) are ...
55 44 33 22 11

Output (Run 2)
How many elements do you want? 6

Enter the elements in the ascending order


Enter the element 11

Enter the element 22

Enter the element 33

Enter the element 44

Enter the element 55

Enter the element 66

The elements in descending order(By Method 1) are ...


66 55 44 33 22 11
The elements in descending order(By Method 2) are ...
66 55 44 33 22 11
Thus time space trade-off is a situation of compensating one performance measure at
the cost of another.
qqq

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge

You might also like