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

Array

Uploaded by

Ak221197
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)
50 views

Array

Uploaded by

Ak221197
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/ 30

Data Structures Notes

by

Farhan Sufyan
Contents

1 Introduction to Data Structures 1


1.1 Data Structure (DS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Abstract Data Types (ADT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1 List ADT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.2 Stack ADT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.3 Queue ADT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Data Structures vs Abstract Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Advantages of the Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Operations on Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Classification of Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7.1 Analysis of algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7.2 What Is Complexity? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7.3 Complexities of an Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7.4 How to calculate f (n)? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.7.5 Time Complexities or Asymptotic Notations . . . . . . . . . . . . . . . . . . . . . . . . 9
1.7.5.1 Big Oh Notation, O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.7.6 Various Time Complexities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.8 Sample Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Chapter 1

Arrays

1.1 Arrays
• An array is a collection of homogeneous or similar type of data items called elements of an array.
• The elements of an array is stored at contiguous memory locations.
• The elements of an array may be like char, int, float etc.

• For Example: int arr[10]; char arr[10]; float arr[5].


• The total number of elements in an array is called size or length of an array.
• The elements of an array have same variable name but each element has different index number or subscript.
• Elements of the array can be randomly accessed since we can calculate the address of each element of the
array with the given base address and the size of data element.
• Information about an array used in the program is stored in a descriptor or stride vector or dope vector.

Figure 1.1: Concept Diagram of Array

• Some array Examples

[1, 2, 3, 4, 5] // is an integer array


[`f',`a',`r',`h',`a',`n'] // is a character array
[1, 2, 3,'f','a','r'] // not an array

1
1.2 Need of Arrays
• Arrays are best for storing multiple values in a single variable.
• Arrays are better at processing many values easily and quickly.
• Sorting and Searching the values is easier in arrays.

1.3 Advantages of Arrays


• Array provides the single name for the group of variables of the same type therefore, it is easy to remember
the name of all the elements of an array.
• Traversing an array is a very simple process, we just need to increment the base address of the array in order
to visit each element one by one.
• Arrays allow random access to its elements. Any element in the array can be directly or randomly accessed
by using the index.
• We can easily find the location of each element in the array, so every element of an array can be accessed in
O(1) time.
• Arrays have better cache locality that can make a pretty big difference in performance.
• Memory locality: Most programming problems require iterating through all the elements of a data structure.
So arrays are good for this because successive data elements are present in sequential order, exhibiting
excellent memory locality. This property helps us to implement high-speed cache memory on modern
computer architectures.

1.4 Applications of Array


• Arrays are used to implement mathematical vectors and matrices, as well as other kinds of rectangular
tables.
• Many databases, small and large, consist of (or include) one-dimensional arrays whose elements are records.
• Arrays are used to implement other data structures like as stacks, queues, heaps, etc.

1.5 Indexing of the array

Figure 1.2: Memory Allocation of an Array

• In Figure ??, we have shown the memory allocation of an array arr of size 5.

2
• The array follows 0-based indexing approach. The base address of the array is 100th byte. This will be the
address of arr[0].
• Here, the size of int is 4 bytes therefore each element will take 4 bytes in the memory.

1.6 Basic Operations


Following are the basic operations supported by an array.

• Traverse: print all the array elements one by one.

• Insertion: Adds an element at the given index.


• Deletion: Deletes an element at the given index.
• Update: Updates an element at the given index.

• Search: Searches an element using the given index or by the value.


• Sorting: Sort the elements of array in ascending or descending order.

1.7 Default Values


In C, when an array is initialized with size, then it assigns defaults values to its elements in following order.

Data Type Default Value


bool false
char ‘\0’
int 0
float 0.0
double 0.0f

1.8 Disadvantages of using Arrays


• You can’t change the size i.e. once you have declared the array you can’t change its size because of the static
memory allocated to it.
• Insertion and deletion are difficult as the elements are stored in consecutive memory locations and the shifting
operation is costly too.

3
1.9 Types of Arrays
• Array can be single dimensional or multi-dimensional.

• The number of subscript determines the dimensions of arrays


• A one or single dimensional (1-D) array has one subscript. Two dimensional (2-D) array has two sub-
script and n-dimesional array has n-subscript.

1.10 One Dimensional (1-D) Array


• A one-dimensional array (or single dimension array) is a type of linear array.

• Accessing its elements involves a single subscript which can either represent a row or column index.
• Syntax for declaration of 1-D array in C:

– DataType ArrayName[Size];
– eg: int arr[5];
– Data type is the type of the elements of the array i.e. int, float, char etc;
– Array name is the valid C identifier.
– Size is the number of elements stored in array, it must be a positive integer.

Figure 1.3: Array Declaration

Figure 1.4: Array Declaration

• When the array is declared, the compiler allocates space in memory sufficient to hold all the elements of the
array, so the size of array should be known at the compile time.

Figure 1.5: Array Representation

4
1.10.1 1-D Array Declaration
1.10.1.1 Array declaration by specifying size
• Array declaration by specifying size:

int arr[10];

• We can also declare an array of user specified size

int n = 10;
int arr[n];

int arr[n];
int n = 10; // Invalid Declaration

int a[]; // Invalid Declaration

1.10.1.2 Array declaration by initializing elements


• Array declaration by initializing elements

int arr[] = {10, 20, 30, 40};

• Compiler creates an array of size 4.


• The above is same as

int arr[4] = {10, 20, 30, 40};

• The value of elements after this initialization was:

arr[0]:10, arr[1]:20, arr[2]:30, arr[3]:40,

• Another Method of initialization

int arr[4];
arr[0]=10, arr[1]=20, arr[2]=30, arr[3]=40;

1.10.1.3 Array declaration by specifying size and initializing elements


• Array declaration by specifying size and initializing elements

int arr[6] = {10, 20, 30, 40};

• Compiler creates an array of size 6, initializes first 4 elements as specified by user and rest two elements
as 0. Hence, if during the initialization the number of initializers are less than the size of array, then all the
remaining elements are assigned value zero.
• The above declaration is same as

int arr[] = {10, 20, 30, 40, 0, 0};

5
• Another method of assigning value

int arr[2];
arr[0] = 5;
arr[3 / 2] = 2; // this is same as arr[1] = 2

1.10.1.4 Some Important Points


• In C, it is not a compiler error to initialize an array with more elements than the specified size. For example,
the below program compiles fine and shows just Warning.

#include <stdio.h>
void main(){
// Array declaration by initializing it with more elements than specified size.
int arr[2] = {10, 20, 30, 40, 50};
}

• No Index Out of bound Checking: There is no index out of bounds checking in C/C++. For example, the
following program compiles fine but may produce unexpected output when run.

#include <stdio.h>
void main(){
int arr[2];
printf("%d", arr[3]);
printf("%d", arr[-2]);
}

• We can’t copy all the elements of array to another array by simply assigning it to the other array. For example:

int a[5] = {1, 2, 3, 4, 5};


int b[5];
b = a; //Error: Program did not compile

6
1.10.2 Accessing 1-D Array Elements

int a[5] = {1, 2, 3, 4, 5};


a[4]++; //Increment the value of a[4] by 1.
a[5] +=200; // Add 200 to a[5]

int a[5];
i = 2;
scanf("%d", &a[i]); //input value a[2]
printf("%d", &a[i]); //print value a[2]
printf("%d", &a[i++]); //print value a[2] and increment the value of i

1.10.2.1 Some Important Points

Length of an Array = (Upper Bound - Lower Bound) + 1

int a[5];
upper index or bound = 4
lower index or bound = 0
Length of an Array = (4 - 0) + 1 = 5

Size of an Array (in Bytes) = Length of an Array x Size of array base type

int a[5];
Length of an array = 5
size of base data type = 4 (int 4 bytes)
Size of an Array (in Bytes) = 5 x 4 = 20 bytes

Address of any element of a 1D array can be calculated by using the following formula:

Byte address of element A[i] = Base Address + Size (base data type) * ( i - First Index)

Example:

int a[5];
Base or starting address (BA) = 2000
Size(S) = 4 (int 4 bytes)
Address of a[5] = BA x S(i - 0) = 2000 x 4(5-0) = 2020

Example: In an array, A[-10 ..... +2 ], Base Address (BA) = 999, Size of base data type or an element = 2 bytes.
Find the address of A[-1].

Address of A[-1] = 999 + 2[(-1) - (-10)] = 999 + 18 = 1017

7
1.10.3 Traversal Operation on 1-D array

#include <stdio.h>
void main() {
int a[] = {1,3,5,7,8};
int n = 5,i;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("a[%d] = %d, ", i, a[i]);
}
printf("\n");
}

8
1.10.4 Insertion Operations on 1-D array
• Insert operation is to insert one or more data elements into an array. Based on the requirement, a new element
can be added at the beginning, end, or any given index of array.
• Following can be a situation with array insertion

– Insertion of all the elements of Array


– Insertion at the beginning of an Array
– Insertion at the end of an Array
– Insertion at the given index of an array

• Logic to insert element in array at specified position:

– Input size and elements in array. Store it in some variable say size and arr.
– Input new element and position to insert in array. Store it in some variable say num and pos.

– To insert new element in array, shift elements from the given insert position to one position right. Hence,
run a loop in descending order from size to pos to insert. The loop structure should look like for(i=size;
i>=pos; i–).
– Inside the loop copy previous element to current element by arr[i] = arr[i - 1];

– Finally, after performing shift operation. Copy the new element at its specified position i.e. arr[pos -
1] = num;

1.10.4.1 Inserting the Elements in Array

#include <stdio.h>
void main() {
int a[5];
int size = 5,i;
printf("Please enter %d elemnts of the array: \n",size);
for(i = 0; i<size; i++) {
scanf("%d",&a[i]);
}
}

9
1.10.4.2 Inserting the Element at the Specific Location of Array

#include <stdio.h>
#define MAX_SIZE 100

void main()
{
int arr[MAX_SIZE];
int i, size, num, pos;

/* Input size of the array */


printf("Enter size of the array : ");
scanf("%d", &size);

while (size < 1 || size > MAX_SIZE){


printf("Invalid size, Please re-enter: \n");
printf("Enter size of the array : ");
scanf("%d", &size);
}

/* Input elements in array */


printf("Enter elements in array : ");
for(i=0; i<size; i++){
scanf("%d", &arr[i]);
}

/* Input new element and position to insert */


printf("Enter element to insert : ");
scanf("%d", &num);
printf("Enter the element position : ");
scanf("%d", &pos);

/* If position of element is not valid */


while(pos > size+1 || pos <= 0){
printf("Invalid position! Please enter position between 1 to %d: ", size);
scanf("%d", &pos);
}
/* Print array before insert operation */
printf("Array elements before insertion : ");
for(i=0; i<size; i++){
printf("%d\t", arr[i]);
}
printf("\n");

/* Make room for new array element by shifting to right */


for(i=size; i>=pos; i--){
arr[i] = arr[i-1];
}

/* Insert new element at given position and increment size */


arr[pos-1] = num;
size++;

/* Print array after insert operation */


printf("Array elements after insertion : ");
for(i=0; i<size; i++){
printf("%d\t", arr[i]);
}
printf("\n");
}

10
1.10.4.3 Inserting the Element at the First Position of an Array
• Remove the code that is asking the position of insertion from the user.
• Remove the code checking for valid position.
• Replace arr[pos-1] = num with arr[0] = num;

1.10.4.4 Inserting the Element at the Last Position of an Array


• Remove the code that is asking the position of insertion from the user.
• Remove the code checking for valid position.
• Remove the code checking for swaping position.

• Replace arr[pos-1] = num with arr[size] = num;

11
1.10.5 Time Complexity for Array insertion
1.10.5.1 When maintaining given order of elements
• At the beginning: O(n)
• At the end: O(1)
• At the specified location: O(n)

1.10.5.2 When not maintaining given order of elements


• At the beginning: O(1)
• At the end: O(1)
• At the specified location: O(1)

12
1.10.6 Deletion Operation on 1-D array
• Deletion refers to removing an existing element from the array and re-organizing all elements of an array.
• Following can be a situation with array deletion:

– Deletion at the end of an Array


– Deletion at the beginning of an Array
– Deletion at the given index of an array

1.10.6.1 Deletion of the Element at the Specific Location of Array (while maintaining order)
Step by step descriptive logic to remove element from array.

• Move to the specified location which you want to remove in given array.
• Copy the next element to the current element of array. Which is you need to perform array[i] = array[i + 1].
• Repeat above steps till last element of array.
• Finally decrement the size of array by one.

#include <stdio.h>
#define MAX_SIZE 100

void main()
{
int arr[MAX_SIZE];
int i, size, pos;

/* Input size and element in array */


printf("Enter size of the array : ");
scanf("%d", &size);

while (size < 1 || size > MAX_SIZE){


printf("Invalid size, Please re-enter: \n");
printf("Enter size of the array : ");
scanf("%d", &size);
}

printf("Enter elements in array : ");


for(i=0; i<size; i++){
scanf("%d", &arr[i]);
}

/* Input element position to delete */


printf("Enter the element position to delete : ");
scanf("%d", &pos);

13
/* Invalid delete position */
while(pos <= 0 || pos > size){
printf("Invalid position! Please enter position between 1 to %d: ", size);
scanf("%d", &pos);
}

/* Print array before deletion */


printf("\nElements of array before delete are : ");
for(i=0; i<size; i++){
printf("%d\t", arr[i]);
}
printf("\n");

/* Copy next element value to current element */


for(i=pos-1; i<size-1; i++){
arr[i] = arr[i + 1];
}

/* Decrement array size by 1 */


size--;

/* Print array after deletion */


printf("\nElements of array after delete are : ");
for(i=0; i<size; i++){
printf("%d\t", arr[i]);
}
}

1.10.6.2 Deletion of the Element at the First Position of an Array


• Remove the code that is asking the position of insertion from the user.
• Remove the code checking for valid position.

• Start the for loop with i = 0 rather than i = pos-1;

1.10.6.3 Deleting the Element from the Last Position of an Array


• Remove the code that is asking the position of insertion from the user.
• Remove the code checking for valid position.

• Remove the code for swaping position.


• Add arr[size-1] = 0 before size–;

1.10.7 Time Complexity for Array Deletion


1.10.7.1 While maintaining given order
• At the beginning: O(n)
• At the end: O(1)
• At the specified location: O(n)

14
1.10.7.2 while not maintaining the given order
• At the beginning: O(1)
• At the end: O(1)
• At the specified location: O(1)

15
1.10.8 Updation Operation on 1-D array
• Update operation refers to updating an existing element from the array at a given index.

#include <stdio.h>

#define MAX_SIZE 100

void main()
{
int arr[MAX_SIZE];
int i, size, pos, item;

/* Input size and element in array */


printf("Enter size of the array : ");
scanf("%d", &size);

while (size < 1 || size > MAX_SIZE){


printf("Invalid size, Please re-enter: \n");
printf("Enter size of the array : ");
scanf("%d", &size);
}

printf("Enter elements in array : ");


for(i=0; i<size; i++){
scanf("%d", &arr[i]);
}

/* Input element position to update */


printf("Enter the element position to delete : ");
scanf("%d", &pos);

/* Invalid delete position */


while(pos <= 0 || pos > size){
printf("Invalid position! Please enter position between 1 to %d: ", size);
scanf("%d", &pos);
}

/* Input the element value to update */


printf("Enter the element value to update : ");
scanf("%d", &item);

/* Print array before updation */


printf("\nElements of array before update are : ");
for(i=0; i<size; i++){
printf("|%d|", arr[i]);
}
printf("\n");

/* Update the element to the position entered by the user */


arr[pos-1] = item;

/* Print array after updation */


printf("\nElements of array after update are : ");
for(i=0; i<size; i++){
printf("|%d|", arr[i]);
}
printf("\n");
}

16
1.10.9 Home Assignment of 1-D array
• Write a C program to copy all elements from an array to another array.
• Write a C program to find sum of all array elements.
• Write a C program to find maximum and minimum element in an integer array.

• Write a C program to find reverse of an array.


• Write a C program to put even and odd elements of array in two separate array.
• Write a C program to count frequency of each element in an array.
• Write a C program to delete all duplicate elements from an array.

1.10.10 Videos Lectures on 1-D array


• https://www.youtube.com/watch?v=AT14lCXuMKI&list=PLdo5W4Nhv31bbKJzrsKfMpo_grxuLl8LU

• https://www.youtube.com/watch?v=Bnjbun-hiBk&list=PLdo5W4Nhv31bbKJzrsKfMpo_grxuLl8LU&
index=2
• https://www.youtube.com/watch?v=CMbpZK_xqoc&list=PLdo5W4Nhv31bbKJzrsKfMpo_grxuLl8LU&
index=3

17
1.11 Multi-Dimensional Array
• In C/C++, we can define multidimensional arrays in simple words as array of arrays.

• Multi-Dimensional Array declaration:


data type arrayName[size1][size2]....[sizeN];
data type: Type of data to be stored in the array.
arrayName: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions
• Two dimensional array: int two[10][20];
• Three dimensional array: int three[10][20][30];

• Total number of elements that can be stored in a multidimensional array can be calculated by multiplying
the size of all the dimensions.
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

18
1.11.1 2-D Array
• Two-dimensional array is the simplest form of a multidimensional array.
dataType arrayName[x][y];
int x[10][20];

• A 2-D array is also known as a matrix.


• Elements in two-dimensional arrays are commonly referred by x[i][j] where ‘i’ is the row number and ‘j’ is
the column number.

Figure 1.6: a[3][3]

1.11.2 Initializing Two – Dimensional Arrays


There are two ways in which a Two-Dimensional array can be initialized.

• First Method: int x[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}


• Second Method: int x[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};

• This type of initialization make use of nested braces. Each set of inner braces represents one row. In the
above example there are total three rows so there are three sets of inner braces.
• In 2-D array, it is optional to specify the first dimension while initialization but the second dimension
should always be present.
int a[][3] = {{1, 10}, {2, 20, 200}, {3}, {4, 40, 400}};
Here, first dimension is taken 4 since there are 4 rows in initialization list.

19
• Compilation Error:
int a[4][] = {{1, 10}, {2, 20, 200}, {3}, {4, 40, 400}};
int a[][] = {{1, 10}, {2, 20, 200}, {3}, {4, 40, 400}};

1.11.3 Accessing Elements of Two-Dimensional Arrays


• Elements in Two-Dimensional arrays are accessed using the row indexes and column indexes.
int x[2][1];

1.11.4 Storing 2D array into Memory

 
1 2 3
4 5 6
7 8 9

20
1.11.4.1 Row Major ordering
In row major ordering, all the rows of the 2D array are stored into the memory contiguously. The 1st row of
the array is stored into the memory completely, then the 2nd row of the array is stored into the memory completely
and so on till the last row.

 
1 2 3 4 5 6 7 8 9
Address of an element a[i][j] of the array stored in row major order is calculated as:

Address of a[i][j] = BA + (C(i − Lr ) + ( j − Lc )) ∗ S


BA : Base Address or the address of the first element of the array a[0][0].
S : Size of the data type of array
Lr : Lower bound of Row
Lc : Lower bound of Column
Ur : Upper bound of Row
Uc : Upper bound of Column
C : Number of Column = (Uc − Lc ) + 1

Example: a[10...30, 55...75], base address of the array (BA) = 0, size of an element = 4 bytes. Find the
location of a[15][68].
Address of a[15][68] = 0 + (21(15 − 10) + (68 − 55)) ∗ 4
= ((21 ∗ 5) + 13) ∗ 4
= 472

Example: a[4...7, -1...3], base address of the array (BA) = 100, size of an element = 2 bytes. Find the
location of a[6][2].
Address of a[6][2] = 100 + (5(6 − 4) + (2 − (−1))) ∗ 2
= 100 + (5 ∗ 2 + 3) ∗ 2
= 126

21
1.11.4.2 Column Major ordering
According to the column major ordering, all the columns of the 2D array are stored into the memory contiguously.
The 1st column of the array is stored into the memory completely, then the 2nd column of the array is stored into
the memory completely and so on till the last column of the array.

 
1 4 7 2 5 8 3 6 9
Address of an element a[i][j] of the array stored in column major order is calculated as:

Address of a[i][j] = BA + ((i − Lr ) + R( j − Lc )) ∗ S


BA : Base or Starting Address of array
S : Size of the data type of array
Lr : Lower bound of Row (If not specified assume zero)
Lc : Lower bound of Column (If not specified assume zero)
Ur : Upper bound of Row
Uc : Upper bound of Column
R : Number of Row = Ur − Lr + 1

A[-5 ... 20][20 ... 70], BA = 1020, Size of element = 8 bytes. Find the location of a[0][30] in column
major implementation.
Address of a[0][30] = 1020 + ((0 − (5)) + 26(30 − 20)) ∗ 8
= 1020 + (5 + (26 ∗ 10)) ∗ 8
= 3140

A[-20 ... 20][10 ... 35], BA = 500, Size of element = 1 bytes. Find the location of a[0][30] in column
major implementation.
Address of a[0][30] = 500 + ((0 − (−20)) + 41(30 − 10)) ∗ 1
= 500 + (20 + 41 ∗ 20) ∗ 1
= 1340

22
1.11.5 Home Assignment of 2-D array
• Write a C program to addition of two matrix.
• Write a C program to multiplication of two matrix.
• Write a C program to transpose of a matrix.

1.11.6 Videos Lectures on 2-D array


• https://www.youtube.com/watch?v=KDQXUysHLL8&list=PLdo5W4Nhv31bbKJzrsKfMpo_grxuLl8LU&
index=5

23
1.12 Sparse Matrix and its representation using Array
• What is a matrix?

– A matrix can be defined as a two-dimensional array having ’m’ rows and ’n’ columns.
– A matrix with m rows and n columns is called m × n matrix.
– It is a set of numbers that are arranged in the horizontal or vertical lines of entries.

• What is a sparse matrix?


– Sparse matrices are those matrices that have the majority of their elements equal to zero.
– In other words, the sparse matrix can be defined as the matrix that has a greater number of zero elements
than the non-zero elements.
– Now, the question arises: we can also use the simple matrix to store the elements, then why is the sparse
matrix required?
• Why is a sparse matrix required if we can use the simple matrix to store elements?

• There are the following benefits of using the sparse matrix:


– Storage - We know that a sparse matrix contains lesser non-zero elements than zero, so less memory
can be used to store elements. It evaluates only the non-zero elements.
– Computing time: In the case of searching in sparse matrix, we need to traverse only the non-zero
elements rather than traversing all the sparse matrix elements. It saves computing time by logically
designing a data structure traversing non-zero elements.

1.12.1 Representation of Sparse Matrix


• The non-zero elements in the sparse matrix can be stored using triplets that are rows, columns, and values.
There are two ways to represent the sparse matrix that are listed as follows -
– Array representation
– Linked list representation

24
1.12.2 Array representation of the sparse matrix
• Example:  
0 0 3 0 4
0 0 5 7 0
 
0 0 0 0 0
0 2 6 0 0

• Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of
no use in most of the cases.
• So, instead of storing zeroes with non-zero elements, we only store non-zero elements.
• To avoid such wastage, we can store only non-zero elements. If we store only non-zero elements, it reduces
the traversal time and the storage space.

• This means storing non-zero elements with triples- (Row, Column, value).
• 2D array is used to represent a sparse matrix in which there are three rows named as
– Row: Index of row, where non-zero element is located
– Column: Index of column, where non-zero element is located
– Value: Value of the non zero element located at index – (row,column)

• Example: Let’s understand the array representation of sparse matrix with the help of the example given
below. Consider the sparse matrix:

• In the above figure, we can observe a 5x4 sparse matrix containing 7 non-zero elements and 13 zero elements.
• The above matrix occupies 5x4 = 20 memory space.

• Increasing the size of matrix will increase the wastage space.

25
• The tabular representation of the above matrix is given below:

• In the above structure, first column represents the rows, the second column represents the columns, and the
third column represents the non-zero value.
• The first row of the table represents the triplets. The first triplet represents that the value 4 is stored at 0th
row and 1st column. Similarly, the second triplet represents that the value 5 is stored at the 0th row and 3rd
column. In a similar manner, all triplets represent the stored location of the non-zero elements in the matrix.
• The size of the table depends upon the total number of non-zero elements in the given sparse matrix.
• Above table occupies 7 ∗ 3 = 21 memory space which is more than the space occupied by the sparse matrix.
So, what’s the benefit of using the sparse matrix?
• Consider the case if the matrix is 8 ∗ 8 and there are only 8 non-zero elements in the matrix, then the space
occupied by the sparse matrix would be 8 ∗ 8 = 64, whereas the space occupied by the table represented
using triplets would be 8 ∗ 3 = 24.
• Example:

• Time Complexity: O(NM), where N is the number of rows in the sparse matrix, and M is the number of
columns in the sparse matrix.

• Auxiliary Space: O(NM), where N is the number of rows in the sparse matrix, and M is the number of
columns in the sparse matrix.

26
// C program for Sparse Matrix Representation using Array

#include<stdio.h>
int main()
{
// Assume 4x5 sparse matrix
int sparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};

int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
size++;

/* number of columns in compactMatrix (size) must be equal to number of non - zero


elements in sparseMatrix*/

int compactMatrix[3][size];

// Making of new matrix


int k = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j];
k++;
}

for (int i=0; i<3; i++)


{
for (int j=0; j<size; j++)
printf("%d ", compactMatrix[i][j]);

printf("\n");
}
return 0;
}

27
1.13 Sample Question
1. Describe the traversal algorithm for a linear array.

2. Explain the memory representation of a sparse matrix.


3. Define the sparse matrix problem and provide a C function for handling sparse matrices. Solve the following
sparse matrix:
4. Suppose a company maintains a linear array YEAR(1920:1970) where YEAR[k] represents the number of
employees hired in year k. Write a module to identify and print the years in which no employees were hired.
5. Given a 2D array A[-100:100, -5:50], determine the address of element A[99,49] using base address 10
and assuming each element requires 4 bytes for storage. Perform calculations for both row-major and
column-major ordering.
6. Write a program to dynamically create and populate a two-dimensional array at runtime. Develop functions
to insert and delete data from any arbitrary location within an array.
7. "Consider multidimensional arrays P and Q declared as P(-2:2, 2:22) and Q(1:8, -5:5, -10:5) stored in
column-major order.
• i) Determine the length of each dimension for P and Q.
• ii) Calculate the total number of elements in P and Q.
• iii) Assuming base address (Q) = 400 and each element occupies 4 bytes, determine the effective indices
(E1, E2, E3) and address of the element Q[3,3,3]."

28

You might also like