MCA Data Structures With Algorithms 02
MCA Data Structures With Algorithms 02
02
D
E
Arrays
V
R
E
S
Names of Sub-Units
E
Introduction to Arrays, Array Representation, Array Operations, Polynomials, Sparse Matrices.
R
Overview
T
This unit begins by explaining the meaning of arrays. Further, it discusses the basic terminology of
H
array representation. Further the unit explains the array operations and polynomials. Towards the
end, the unit discusses the sparse matrices.
IG
Learning Objectives
R
Learning Outcomes
aa https://www.kau.edu.sa/Files/0052053/Subjects/10_csphtp1_07pdf.pdf
aa https://www.geeksforgeeks.org/search-insert-and-delete-in-an-unsorted-array/
2.1 INTRODUCTION
Array is a vessel which carries a fixed quantity of data items which should be of identical kind or same
datatype. Most of the algorithms implemented by different Data structures use arrays. Arrays are
D
described by two basic terms, which acts as integral part of an array is given below:
E
zz Element: The constituent data items collectively stored in an array are known as its elements.
Index: The position of an element is assigned a numerical index, which recognises the element is
V
zz
referred as its index.
R
2.2 REPRESENTATION OF LINEAR ARRAYS IN MEMORY
E
There are various ways to declare the array in different programming languages. Lets consider the
array declaration as shown in Figure 1:
S
Elements 35 33 42 E
10 14 19 27 44 26 31
R
index 0 1 2 3 4 5 6 7 8 9
T
Size: 10
H
zz 0 marks as the starting position of the array. It is considered as the first element.
zz The size of the array is 10 which denote that it stores 10 elements.
R
zz Any element can be retrieved through its index. For instance, we can access the element 19 from its
index 5.
Y
An array function is generally well-defined as a function that works with an array. The array is a mutual
O
perception in computer programming, where several variables are assigned together with a common
name. Variables are specific items that enclose numbers, letters or other data.
C
2
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY
D
The array elements are:
LA[0] = 1
E
LA [1] = 3
LA [2] = 7
V
LA [3] = 9
LA [4] = 11
R
LA [5] = 13
E
2.3.2 Insertion Operation
S
This operation allows us to insert either single or multiple data items into an array. Depending on the
situation, a new element can be added at any position as specified by index of element in the array.
E
The following program illustrates the Insert operation, where a data item is inserted at the specified
R
location in the array. The following program implements the Insertion operation:
#include <stdio.h>
void main()
T
{
int LA[] = {3,5,7,9,11};
H
}
N = N + 1;
Y
while( j >= K)
{
P
LA[j+1] = LA[j];
j = j - 1;
O
}
LA[K] = item;
C
3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
D
LA [2] = 7
LA [3] = 11
E
LA [4] = 9
LA [5] = 11
V
2.3.3 Deletion Operation
R
The process of removing an existing element, from an array, then reassembling all the elements of the
E
array is termed as Deletion. Removes an element at the specified index from an array. Consider a linear
array Sample, with Max number of elements and Loc, is a positive integer where Loc<=Max. Following
S
algorithm depicts the process of deletion of an element present at the Locth position of sample:
zz Begin
zz Set TmpVar = Loc
E
R
zz Repeat steps 4 and 5 while TmpVar < Max
zz Set Sample[TmpVar] = Sample[TmpVar+ 1]
T
zz
zz Finish
IG
{
int LA[] = {3,5,7,9,12};
Y
int K = 3, N = 5;
int i, j;
P
}
j = K;
while( j < N)
{
LA[j-1] = LA[j];
j = j + 1;
4
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY
}
N = N -1;
printf("The array elements after deletion:n");
for(i = 0; i<N; i++)
{
printf("LA[%d] = %d n", i, LA[i]);
}
}
The running output of a Deletion operation is given below:
D
The original array elements are: nLA[0] = 3 nLA[1] = 5 nLA[2] = 7 nLA[3]
= 9 nLA[4] = 12 nThe array elements after deletion: nLA[0] = 3 nLA[1] = 5
E
nLA[2] = 9 nLA[3] = 12 n
V
2.3.4 Search Operation
R
Search Operation could be performed on an array based on either the value or index of the element. :
Looks for an element provided with respective index. Consider a linear array Sample with Max number
E
of elements and is a positive integer where Loc<=Max. Following algorithm helps to locate an element
using its value through sequential search is as follows:
S
zz Begin
zz Set TmpVar = 0
Repeat steps 4 and 5 while TmpVar < Max
E
R
zz
zz
int main()
{
int arr[10], Size, i, Search, Flag;
R
{
scanf("%d",&arr[i]);
O
}
printf("\n Please Enter the Search Element :9 ");
C
scanf("%d",&Search);
Flag = 0;
for(i = 0; i < Size; i++)
{
if(arr[i] == Search)
{
5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
Flag = 1;
break;
}
}
if(Flag == 1)
return 0;
}
The running output of Search operation is given below:
2, 4, 6, 7, 9, 11, 13, 15, 17
D
2.3.5 Update Operation
E
The process of modifying an existing element in an array at a specified index is referred to as updating.
V
It modifies an element in the specified index position. Consider a LinearArray Sample, with Max number
of elements and Loc,is a positive integer where Loc<=Max. Following algorithm shows the process of
R
updating an element present at the Loc th position of Array Sample is as follows:
Begin
E
zz
S
zz Finish
E
The following program implements the Update operation:
#include <stdio.h>
R
void main()
{
int LA[] = {2,9,7,11,16};
T
int i, j;
printf("The original array elements are:\n");
for(i = 0; i<N; i++)
IG
{
printf("LA[%d] = %d \n", i, LA[i]);
}
R
LA[K-1] = item;
printf("The array elements after updation:\n");
Y
}
C
6
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY
LA [0] = 2
LA [1] = 9
LA [2] = 11
LA [3] = 11
LA [4] = 16
D
dimensional array links each of its components with two indexes.
E
Multidimensional arrays are well-defined analogously. More precisely, an n dimension m1 x m2
... x mn array B is a group of m1, m2 , ..., mn data components in which each component identified
V
by a list of n integers such as K1, K2....., Kn called subscripts with the property that (1<=K1<=m.
1<=k2<=m2...........1<=Kn<=mn).
R
2.4.1 Size of Multidimensional Arrays
E
The Total elements of a multidimensional array can be obtained from the product of the dimensional
S
sizes of the array For example The array int [] [] x = new int [10] [20] can store a total of (10*20) = 200
elements.
It is the modest form of Multi-Dimensional Array. Two Dimensional Array, data is kept in row and column
wise. We can access the record using both the row index and column index. The basic declaration of two
H
A two dimensional array is the most elementary form of a multidimensional array. We view a two
dimensional array as a table of one dimensional array for comprehending in a better way.
R
zz
zz Data_type: refers to kind of data for storage which could be any valid C or C++data type
P
We can initialize the Two Dimensional Array in several ways. A Two-Dimensional array can be initialised
O
three components will be 2nd row, the next 3 components will be 3rd row, and the last 3 components
will be 4th row. Here we separated them into 3 because our column size is 3. For example : int
Employees[4][3] = { 10, 20, 30, 15, 25, 35, 22, 44, 66, 33, 55, 77 };
zz Second approach for two dimensional arrays: Here, we haven’t stated the row size and column size.
Though, the compiler is intelligent and sufficient to calculate the size by read-through the number
of components inside the row and column. For example: int Employees [ ][ ] = { {1 4, 22, 36}, {17, 28, 37},
{20, 47, 65}, {41, 50, 59} };
7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
zz Third approach of two dimensional arrays: Here, we acknowledged Employees array with row size
=2 and column size = 3, but we only allocated 1 column in the 1st row and 2 columns in the 2nd row.
In these circumstances, the residual values will assign to avoidance values (0 in this case).
For example:
int Employees [1][2] = { {3},
{8, 9 }
};
zz Fourth approach for two dimensional arrays: The above three methods of initializing two
D
dimensional array are decent to accumulate a small number of components into the array. What
if we want to accumulate 100 rows or 50 column values? It will be a frightening to add all of them
E
using any of the approaches stated above. To resolve this, we can use the for loop:
int rows, columns, Employees[100][50];
V
for (rows =0; rows < 100 ; rows++)
{
R
for (columns =0; columns < 50; columns++)
{
E
Employees [rows][columns] = rows + columns;
}
S
The following algorithm is for two-dimensional array is as follows:
#include <stdio.h>
#include <stdlib.h>
E
R
int main()
{
int X[3][4]={{2,3,4,5},{5,6,7,8},{2,4,8,9}};
T
int i,j;
H
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
IG
{
printf("%d ",X[i][j]);
}
R
printf("\n");
}
Y
return 0;
}
P
2 3 4 5
5 6 7 8
C
2 4 8 9
8
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY
Columns
D
Ar
ra
Rows
ys
Row 2 121 211 212 213 Array 2
E
311 312 313 Array 3
V
Row 3 131 221
R
231 321 322 323
E
331 332 333
S
E
Figure 2: Visualization of 3-D Array
R
The process of initializing the three-Dimensional arrays is similar to that of Two-dimensional arrays.
The variation lies in the fact that is as there is an increase in the number of dimensions, there is an
T
The variation is that three loops are required rather than two loops to work with the additional dimension
present in three dimensional arrays.
The following algorithm is for Three-dimensional array is as follows:
R
#include<iostream>
using namespace std;
Y
int main()
{
P
int i, j, k;
O
int threeDimArr[3][4][2] = {
{ {2, 3}, {5, 6}, {4, 2}, {5, 9} },
{ {7, 9}, {8, 9}, {6, 5}, {4, 3} },
C
9
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
D
The running output of a Three dimensional array is given below:
2 3
E
5 6
4 2
V
5 9
R
7 9
8 9
E
6 5
4 3
S
1 2 E
4 6
R
8 3
5 7
Similarly, arrays with multiple dimensions could be created following a similar approach. But we
T
must be cautious as the increase in the dimensions makes the arrays more complex to deal with.
The widely used multidimensional array is the two-dimensional array.
H
2.5 POLYNOMIAL
IG
A polynomial q(x) is a function with variable x taking the form (axn + bxn-1 + …. + jx+ k), where a, b, c
…., till k are real numbers and ‘n’ is a positive integer, which is known as the degree of the polynomial.
R
An important feature of the polynomial is that its individual term contains two components are:
Y
zz Coefficient
zz Exponent or Power
P
For example: 5x2 + 6x, 5 and 6 are referred as the coefficients of variable and 2, 1 are the exponents.
O
zz The sign of the individual coefficients and exponents are reserved inside the coefficient and the
power (exponent) itself.
zz The possibility of the presence of additional terms with equal exponent is one.
zz The memory assignment for the individual terms of the polynomial is done either in ascending or
descending order of their exponents.
10
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY
poly
Coefficient
4 3 6 2 10 1 6 0
D
E
Power
V
Figure 3: Insertion of Coefficient and Power
R
2.5.1 Polynomial Representation
E
A polynomial is an appearance that comprises more than two terms. A term is made up of coefficient
S
and exponent. An example of polynomial is a polynomial so, it may be represented by means of arrays
or linked lists.
E
The concept of polynomials can be implemented through the following data structures:
R
zz Arrays
zz Linked List
T
In the situations which involve evaluating multiple polynomial expressions and performing the arithmetic
operations like addition and multiplication on them, we need a path to represent those polynomials. The
IG
simplest way is to represent a polynomial with degree ‘n’ and reserve all the coefficients of n+1 terms of
the polynomial is by storing them in an Array. So each element of the array will now have two values:
Coefficient
R
zz
zz Exponent
Y
#include <bits/stdc++.h>
using namespace std;
O
11
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
}
return productPolynomial;
}
void printPolynomial(int polynomial[], int n) {
for (int i = n - 1; i >= 0; i--) {
cout << polynomial[i];
if (i != 0) {
cout << "x^" << i;
cout << " + ";
}
D
}
cout << endl;
E
}
V
int main() {
int X[] = {5, 6, 7, 8};
R
int Y[] = {8, 7, 6, 5};
int m = 4;
E
int n = 4;
cout << "First polynomial: ";
S
printPolynomial(X, m);
cout << "Second polynomial: ";
printPolynomial(Y, n); E
int *productPolynomial = multiplyTwoPolynomials(X, Y, m, n);
R
cout << "Product polynomial: ";
printPolynomial(productPolynomial, m + n - 1);
return 0;
T
}
H
is collection of different terms where each of them holds a coefficient and an exponent.
P
The following algorithm represents the multiplication of polynomials using linked list is as follows:
#include<bits/stdc++.h>
O
int coefficient;
int pow;
struct Node *next;
};
void create_node(int X, int Y, struct Node **temp){
struct Node *r, *z;
z = *temp;
if(z == NULL){
12
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY
D
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
E
r->next = NULL;
V
}
}
R
void polyadd(struct Node *p1, struct Node *p2, struct Node *result){
while(p1->next && p2->next){
E
if(p1->pow > p2->pow){
result->pow = p1->pow;
S
result->coefficient = p1->coefficient;
p1 = p1->next;
}
else if(p1->pow < p2->pow){
E
R
result->pow = p2->pow;
result->coefficient = p2->coefficient;
p2 = p2->next;
T
} else {
result->pow = p1->pow;
H
result->coefficient = p1->coefficient+p2->coefficient;
p1 = p1->next;
IG
p2 = p2->next;
}
result->next = (struct Node *)malloc(sizeof(struct Node));
R
result = result->next;
result->next = NULL;
Y
}
while(p1->next || p2->next){
P
if(p1->next){
result->pow = p1->pow;
O
result->coefficient = p1->coefficient;
p1 = p1->next;
C
}
if(p2->next){
result->pow = p2->pow;
result->coefficient = p2->coefficient;
p2 = p2->next;
}
result->next = (struct Node *)malloc(sizeof(struct Node));
result = result->next;
13
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
result->next = NULL;
}
}
void printpoly(struct Node *node){
while(node->next != NULL){
printf("%dx^%d", node->coefficient, node->pow);
node = node->next;
if(node->next != NULL)
printf(" + ");
}
D
}
int main(){
E
struct Node *p1 = NULL, *p2 = NULL, *result = NULL;
V
create_node(14,8,&p1);
create_node(22,7,&p1);
R
create_node(67,9,&p1);
create_node(41,4,&p2);
E
create_node(19,2,&p2);
printf("polynomial 1: ");
S
printpoly(p1);
printf("\npolynomial 2: ");
printpoly(p2); E
result = (struct Node *)malloc(sizeof(struct Node));
R
polyadd(p1, p2, result);
printf("\npolynomial after adding p1 and p2 : ");
printpoly(result);
T
return 0;
}
H
The running output of the addition of Polynomials using linked list is given below:
IG
We define a Matrix as a two-dimensional array with ‘m’ rows and ‘n’ columns forming an m*n matrix.
Sparse matrices are the matrices in which the majority of the elements are zero's. Alternatively, a
P
sparse matrix is defined as the matrix which has a larger number of zero's than nonzero elements. A
fair question arises if a simple matrix could be used for different purposes; then why we should go for
O
the sparse matrix? Following benefits makes a sparse matrix more relevant:
Storage: a sparse matrix needs minimal memory storage, than the normal matrices. It considers
C
zz
only the non-zero elements for any calculation.
zz Computing time: Searching a sparse matrix, requires to traversal of the non-zero elements alone,
instead visiting other elements, which save computing time as we use a logically designed data
structure for moving across non-zero elements.
If we use two dimensional arrays for representing a sparse matrix, it leads to the wastage of precious
memory spaces. The zero's of the matrices need not be stored. We store the non-zero elements alone.
Such storage mechanism reduces the traversal time and the memory space.
14
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY
D
zz
zz Linked lists
E
2.6.2 Representation of Sparse Matrix using Arrays
V
Sparse matrix is a matrix which comprises very insufficient non-zero components. When a sparse
R
matrix is characterized with a 2-dimensional array, we excess a lot of space to describe that matrix. For
example, consider a matrix of size 100 X 100 comprising only 10 non-zero components. In this matrix,
E
only 10 spaces are occupied with non-zero values and remaining spaces of the matrix are occupied with
zero. A Sparse matrix can be represented using a two dimensional array, which has three rows, namely:
S
zz Row: refers to the index of the row where a non-zero element is found.
zz
zz
E
Column: refers to the index of the column which has a non-zero element.
Value: refers to the value of the non-zero element found at the index (row, column).
R
An example of Sparse matrix portraying through array representation is shown in Figure 4:
T
0 1 2 3
Sparse matrix 0 0 4 0 5
H
1 0 0 3 6
2 0 0 2 0
IG
3 2 3 0 0
4 0 0 0 0
R
The above sparse matrix, has 13 zeroes and 7 non-zero elements. The memory space of 5*4=20 elements
is occupied by the sparse matrix. The increase in the size of the sparse matrix leads to memory wastage.
O
We can represent the above sparse matrix in a tabular format as displayed below:
C
15
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
D
contains of four fields while, in array representation there are three fields, i.e., row, column, and value.
We can use the data structure linked lists to represent the sparse matrices.
E
Following are the data fields of a node in the linked list:
V
zz Row: Refers to the index of the row where there is a non-zero element.
zz Column: Refers to the index of column where a non-zero element is found.
R
zz Value: Refers to the value of the non-zero element which present at the index (row, column).
E
zz Next node: Holds the address of the next node.
S
An example of Sparse matrix portraying through linked list representation is shown in Figure 5:
The above image displays how a sparse matrix is represented by linked list. The first field of the node
denotes the row index, second field indicates the i column index, third field denotes the value and fourth
IG
2.7 CONCLUSION
R
Conclusion
zz Array is a vessel which carries a fixed quantity of data items which should be of identical kind or
Y
zz
zz A multidimensional array connects each component in the array with numerous indexes.
O
zz An array operation is generally well-defined as a operation that works with an array. The array is a
mutual perception in computer programming.
C
zz Polynomials seem in many areas of mathematics and science. For example, they are used to form
polynomial equations, which convert a comprehensive range of problems.
2.8 GLOSSARY
16
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY
D
1. Which of these best describes an array?
E
a. Arrays is not a data structure
b. Arrays are immutable once initialised
V
c. Data structure which exhibits hierarchical behaviour
R
d. Container of object of same types
2. How do you initialize an array in C?
E
a. int a[4] = (8,9,10,11);
S
b. int a(4) = {8,9,10,11};
c. int a[4] = {8,9,10,11};
d. int arr(4) = (8,9,10,11);
E
R
3. How do you instantiate array in Java?
a. int r[] = new int(5);
T
b. int r[];
H
b. int d[[]];
c. int[][]d;
Y
d. int[[]] d;
P
{
int []d = {6,7,8,9,10};
System.out.println (d [2]);
System.out.println (d [4]);
}
}
}
17
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
a. 8 and 10
b. 7 and 10
c. 8 and 9
d. 6 and 9
6. What is the output of the following Java code?
public class array
{
public static void main (String args[])
D
{
int y[] = {11,12,13,14,15};
E
System.out.println(y[5]);
}
V
}
a. Invalid input exception
R
b. 5
E
c. Array Index Out of Bounds Exception
S
d. 4
7. When does the Array Index Out of Bounds Exception occur?
E
a. Run time
R
b. Compile time
c. No error occurs
T
a. Binary trees
IG
b. Spatial locality
c. Scheduling of processes
R
d. Caching
9. Which of the following concepts make wide use of arrays?
Y
a. Spatial locality
P
b. scheduling of processes
c. Caching
O
d. Binary trees
C
18
UNIT 02: Arrays JGI JAIN
DEEMED-TO-BE UNIVERSITY
D
4. A multidimensional array connects each component in the array with numerous indexes. Generally,
multidimensional array is the two-dimensional array, also recognised as a table or matrix. Determine
E
the functions of Multidimensional array.
V
5. We define a Matrix as a two-dimensional array with ‘m’ rows and ‘n’ columns forming an m*n matrix.
Elaborate the Sparse matrix.
R
E
2.10 ANSWERS AND HINTS FOR SELF-ASSESSMENT QUESTIONS
S
A. Answers to Multiple Choice Questions
Q. No.
E Answer
R
1. d. container of object of same types
2. c. int a[4] = {8,9,10,11};
T
4. c. int[][]d;
5. a. 8 and 10
IG
6. c. ArrayIndexOutOfBoundsException
7. a. run time
R
1. Array is a vessel which carries a fixed quantity of data items which should be of identical kind
or same datatype. Most of the algorithms implemented by different Data structures use arrays.
C
Arrays are described by two basic terms, which acts as integral part of an array. Refer to Section
Introduction
2. There are various ways to declare the array in different programming languages. Let’s consider the
array declaration in C. Refer to Section Representation of Linear Array in Memory
3. An array function is generally well-defined as a function that works with an array. The array is a
mutual perception in computer programming, where several variables are assigned together with
19
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
a common name. Variables are specific items that enclose numbers, letters or other data. Refer to
Section Function of Arrays
4. A multidimensional array connects each component in the array with numerous indexes. Generally,
multidimensional array is the two-dimensional array, also recognized as a table or matrix. Refer to
Section Multidimensional Arrays
5. We define a Matrix as a two-dimensional array with ‘m’ rows and ‘n’ columns forming an m*n matrix.
Sparse matrices are the matrices in which the majority of the elements are zeroes.
Alternatively, a sparse matrix is defined as the matrix which has a larger number of zeroes than
D
nonzero elements. Refer to Section Sparse Matrix
E
@ 2.11 POST-UNIT READING MATERIAL
V
zz https://www.kau.edu.sa/Files/0052053/Subjects/10_csphtp1_07pdf.pdf
R
zz https://www.cs.bham.ac.uk/~jxb/DSA/dsa.pdf
E
2.12 TOPICS FOR DISCUSSION FORUMS
S
zz Discuss with your friends and classmates about the concept of Array and its representation .Also;
E
discuss some interesting mathematical problems of polynomials and sparse matrices.
R
T
H
IG
R
Y
P
O
C
20