Syllabus
Arrays: Definition,Single and Multidimensional Arrays,
Representation of Arrays: Row Major Order, and Column Major
Order, Derivation of Index Formulae for 1-D,2-D,3-D and n-D
Array Application of arrays, Sparse Matrices and their
representations.
3.
Introduction to Arrays
The simplest and linear type of data structure is a linear (or 1D)
array.
One way is to have linear relationship between elements by means
of sequential (contiguous) memory locations.
An array is collection of items stored at contiguous memory
locations. The idea is to store multiple items of same type
(homogenous) together.
It easier to calculate the location of each element by simply adding
an offset to a base value, i.e., the memory location of the first
element of the array.
Remember: “Location of next index depends on the data type
we use”.
4.
Arrays can bedeclared in various ways in different languages. For
illustration, let's take C array declaration.
As per the above illustration, following are the important points to be considered.
1. Index starts with 0.
2.Array length is 10 which means it can store 10 elements.
3. Each element can be accessed via its index. For ex, we can fetch an element at index 6 as
27.
5.
Calculation of address
The address of any particular element in the 1-D array can be
calculated by the following equation:
Address of element a[k] = Base address +W*E
Here, W is the size of each element of the array, and E is the
effective index (E=k-LB) of element we need in the array.
Example:
We wish to find the address of a 6th element of the one dimensional
array ‘a[10]’, whose base address is 1000.The size of each element
in this example is 4 byte. So, the calculation based on this can be
performed in the following way.
Address of element a[6] = 1000+4*6
= 1000+24
= 1024
6.
Basic Operations
Following arethe basic operations supported by an array.
Traversal − Process all the array elements one by one.
Insertion − Adds an element at the given index.
Deletion − Deletes an element at the given index.
Search − Search an element using the given index or by the
value.
Update − Updates an element at the given index.
7.
Traversal of Array
The method of processing each element in the array exactly
once for a specific purpose is known as Traversal. In array Traversal
starts from first element in the array and ends at the last element of
the array.
For ex. printing every element, counting the total number of
elements, or performing any process on these elements.
Time complexity of traversal algorithm is O(n) in all cases.
Algorithm for ArrayTraversal
Step 1: START = 0
Step 2: Repeat Step-3 while (START<N)
Step 3: Read A[START]
START = START + 1
8.
Program for ArrayTraversal
#include<stdio.h>
#define N 5
void traverse(int *A);
int main()
{
int A[N]={10,20,30,40,50};
traverse(A);
}
void traverse(int *A)
{
int START=0;
while(START<N)
{
printf("%dn“,A[START]);
START=START+1;
}
}
9.
Insertion in anArray
Following can be a situation with array insertion:
Insertion at the beginning of an array
Insertion at the given index of an array
Insertion after/before the given index of an array
10.
Insertion at theBeginning of an Array
When the insertion happens at the beginning, it causes all the existing
data items to shift one step towards right.
We assume A is an array with N elements. The maximum numbers of
elements it can store is defined by MAX.We shall first check if an array
has any empty space to store any element and then we proceed with the
insertion process.The time complexity is O(n).
Algorithm
1. Begin
2. IF N == MAX
return
3. ELSE N = N + 1
a. For all Elements in A Move to next adjacent location
b.A[FIRST] = New Element
4. End
12.
Insertion at thegiven index of an array
In this scenario, we are given the exact location (index) of an array where a new data
element (value) needs to be inserted. First we shall check if the array is full, if it is
not, then we shall move all data elements from that location to one step towards
right.This will make room for a new data element.
We assume A is an array with N elements.The maximum numbers of elements it can
store is defined by MAX.
Algorithm
1. Begin
2. IF N == MAX
return
3. ELSE N = N + 1
a. Input index
b. ForAll Elements from A[index] to A[N], Move to next adjacent location
c.A[index] = New Element
4. End
14.
Insertion after thegiven index of an array
In this scenario we are given a location (index) of an array after which a new
data element (value) has to be inserted. Only the seek process varies, the rest of
the activities are the same as in the previous example.
We assume A is an array with N elements.The maximum numbers of elements it
can store is defined by MAX.
Algorithm
1. Begin
2. IF N = MAX
return
3. ELSE
N = N + 1
a. Input index
b. For All Elements from A[index + 1] to A[N] Move to next adjacent location
c.A[index + 1] = New Element
3. End
15.
The time complexityof insertion algorithm is:
Best case: Ω(1)
Worst Case: O(n)
Average Case: θ(n)
16.
Deletion in Array
Deletion refers to removing an existing element from the array and
re-organizing all elements of an array.
Deleting the first element of the array
Deleting the specified element of the array
17.
The time complexityof deletion algorithm is:
Best case: Ω(1)
Worst Case: O(n)
Average Case: θ(n)
18.
Searching in Array
Not even a single day pass, when we do not have to search for
something in our day to day life, car keys, books, pen, mobile
charger and what not. Same is the life of a computer, there is so
much data stored in it, that whenever a user asks for some data,
computer has to search it's memory to look for the data and make
it available to the user. And the computer has it's own techniques
to search through it's memory fast.
What if you have to write a program to search a given number in
an array? How will you do it?
Well, to search an element in a given array, there are two popular
algorithms available:
Linear Search
Binary Search
19.
Linear Search
Linearsearch is a very basic and simple search algorithm. In Linear
search, we search an element or value in a given array by traversing
the array from the starting, till the desired element or value is
found.
It compares the element to be searched with all the elements
present in the array and when the element
is matched successfully, it returns the index of the element in the
array, else it return -1.
Linear Search is applied on unsorted or unordered lists, when
there are fewer elements in a list.
20.
Algorithm
Consider LAis a linear array with N elements and K is a positive
integer such that K<=N. Following is the algorithm to find an
element with a value of ITEM using Linear search.
1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF LA[J] is equal ITEM then GOTO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
7. Stop
21.
Features of LinearSearch Algorithm
It is used for unsorted, unordered and small list of elements.
It has a very simple implementation.
The time complexity of linear search algorithm is:
Best case: Ω(1)
Worst Case: O(n)
Average Case: θ(n)
The time is linearly dependent on the number of elements, which is not
bad, but not that good too.
22.
Binary Search
BinarySearch is useful when there are large numbers of elements
in an array and they are sorted. So a necessary condition for
Binary search to work is that the list/array should be sorted.
Features of Binary Search
It is great to search through large sorted arrays.
It has a simple implementation.
The time complexity of Binary search algorithm is:
Best case: Ω(1)
Worst Case: O(log2 n)
Average Case: θ(log2 n)
25.
Updating an Array
Update operation refers to updating an existing element from the
array at a given index.The time complexity will be O(1).
Algorithm
Consider LA is a linear array with N elements and K is a positive
integer such that K<N. Following is the algorithm to update an
element available at the Kth
position of LA.
1. Start
2. Set LA[K-1] = ITEM
3. Stop
26.
Time complexity ofArray Operations
Lets take a look at the time complexity of various operations on
arrays.
Operation Best Case Worst Case Average Case
Read Ω(1) O(1) ϴ(1)
Insert Ω(1) O(n) ϴ(n)
Delete Ω(1) O(n) ϴ(n)
Linear Search Ω(1) O(n) ϴ(n)
Binary Search Ω(1) O(log n) ϴ(log n)
27.
ISRO 2018
Which ofthe following operations is not O(1) for an array of sorted
data.You may assume that array elements are distinct.
Find the ith largest element
Delete an element
Find the ith smallest element
All of the above
Delete an element
28.
GATE-CS-2015 (Set 2)
An unordered array contains n distinct elements. The number of
comparisons to find an element in this list that is neither maximum nor
minimum is:
Θ(1)
Θ(nlogn)
Θ(n)
Θ(logn)
Θ(1) We only need to consider any 3 elements and compare them. Using
3 comparisons, we can find that the middle element. So the number of
comparisons is constants, that makes time complexity as (1).
Θ
29.
UGC NET CS2016 July – III
Let A[1...n] be an array of n distinct numbers. If i < j and A[i] >
A[j], then the pair (i, j) is called an inversion of A. What is the
expected number of inversions in any permutation on n
elements ?
n(n-1)/2
n(n-1)/4
n(n+1)/4
2n[logn]
n(n-1)/4
30.
GATE CS 2005
A program P reads in 500 integers in the range
[0..100] representing the scores of 500 students. It then prints
the frequency of each score above 50. What would be the best
way for P to store the frequencies?
An array of 50 numbers
An array of 100 numbers
An array of 500 numbers
A dynamically allocated array of 550 numbers
An array of 50 numbers
31.
Advantages and disadvantagesof Arrays
Advantages
1. Reading an array element is simple and efficient.This is because
any element can be access directly using indexes.
2.Array is a foundation for other data structures. For example other
data structures such as Linked List, Stack, Queue etc. are
implemented using array.
3. All the elements of an array can be accessed using a single name
(array name) along with the index, which is readable, user-
friendly and efficient rather than storing those elements in
different-2 variables.
4. All the elements in array are stored at contiguous memory
locations.
32.
Disadvantages
1.While using array,we must need to make the decision of the size
of the array in the beginning (static memory allocation), so if
we are not aware how many elements we are going to store in
array, it would make the task difficult.
2. The size of the array is fixed so if at later point, if we need to
store more elements in it then it can’t be done. On the other
hand, if we store less number of elements than the declared size,
the remaining allocated memory is wasted.
3. Insertion and deletion operations required O(n) shifting of
elements.
33.
Two dimensional (2D)arrays
An array of arrays is known as 2D array.The two dimensional (2D)
array is also known as matrix.A matrix can be represented as a
table of rows and columns.
34.
A two-dimensionalarray is stored in the form of the row-column
matrix, where the first index designates the row and second index
shows the column.
These matrices are stored in the memory as given below.
Row-Major order Implementation
Column-Major order Implementation
35.
Row-Major order Implementation
In Row-Major Implementation of the arrays, the arrays are
stored in the memory in terms of the row design, i.e. first the
first row of the array is stored in the memory then second and so
on. Suppose we have an array named arr having 3 rows and 4
columns then it can be stored in the memory in the following
manner:
36.
Column-Major Implementation
InColumn-Major Implementation of the arrays, the arrays
are stored in the memory in the term of the column design, i.e. the
first column of the array is stored in the memory then the second
and so on.
38.
UGC NET CS2014 Dec - II
Consider a two dimensional array A[20][10]. Assume 4 words per
memory cell, the base address of array A is 100, elements are
stored in row-major order and first element is A[0][0].What is the
address ofA[11][5] ?
560
460
570
575
560
39.
GATE-CS-2014-(Set-3)
LetA be asquare matrix of size n x n.What is the expected output of the following program:
C = 100
for i = 1 to n do
for j = 1 to n do
{
Temp = A[i][j] + C
A[i][j] =A[j][i]
A[j][i] =Temp - C
}
for i = 1 to n do
for j = 1 to n do
Output(A[i][j]);
The matrixA itself
Transpose of matrixA
Adding 100 to the upper diagonal elements and subtracting 100 from diagonal elements ofA
None of the above
The matrix A itself
40.
Multidimensional Array
Ann-dimensional matrix can be of any dimension. In 1-D array the elements
are linearly arranged and can be addressed as a[0], a[1], .. .
In 2-D array elements have row and column indexes and can be represented as
a[0][0], a[0][1] etc. and they are stored row-wise/column-wise in the memory,
because the memory is linear.
A 3-D array is collection of many 2D matrix and can be accessed by 3 index
numbers.
Suppose thearray is of N-dimensions having the size of each
dimension as L1, L2, L3, ..., Ln
where Li=UB-LB+1
for a given subscript Ki, the effective index Ei of Li is the no. of
indices preceding Ki
where Ei=Ki-LB
The element size is w, Base Address is BA and the index number of
the element to find the address is given as K1, K2, K3, . . . .Kn .Then
the formula will be:
In column-major order
BA+w[(((…(ENLN-1+EN-1)LN-2)+…+E3)L2+E2)L1+E1]
In row-major order
BA+w[(…((E1L2+E2)L3+E3)L4+…+EN-1)LN+EN]
45.
AKTU Question
Supposea three dimensional array A is declared using A[1:10, -5:5, -10:5)
(i) Find the length of each dimension and the number of elements inA
(ii) Explain Row major order and Column Major Order in detail with explanation
formula expression.
(iii) Calculate the address of element A[7,3,4] if base address is 2000 and each element is
taking 2 bytes in memory. [AKTU-2021][10 Marks]
Suppose multi dimensional arrays P and Q are declared as P(-2:12, 4:22) and
Q(1:9, -5:15, -3:8) stored in column major order.
(i) Find the length of each dimensions of P and Q.
(ii) Find the number of elements in P and Q.
(iii) Assuming base address (Q) =400, W=4, find the effective indices E1, E2 and E3 and
address of element Q[3,3, 3]. [AKTU-2018][10 Marks]
46.
Solutions
(i)The lengthof each dimension and the total number of elements in array A,
declared asA[1:10, -5:5, -10:5), are calculated as follows:
Length of Dimension 1 (D1):
Upper bound - Lower bound + 1 = 10 - 1 + 1 = 10
Length of Dimension 2 (D2):
Upper bound - Lower bound + 1 = 5 - (-5) + 1 = 11
Length of Dimension 3 (D3):
Upper bound - Lower bound + 1 = 5 - (-10) + 1 = 16
The total number of elements inA is the product of the lengths of all
dimensions: 10 * 11 * 16 = 1760 elements.
(ii) Row-Major Order and Column-Major Order are two common methods
for storing multi-dimensional arrays in linear memory.
47.
Row-Major Order(RMO):
In RMO, elements of an array are stored row by row. The elements
of the first row are stored consecutively, followed by the elements of
the second row, and so on. For a 3D array A[D1][D2][D3], the
formula for the address ofA[i, j, k] is:
Code
Address(A[i, j, k]) = BaseAddress + ( (i - L1) * D2 * D3 + (j - L2) *
D3 + (k - L3) ) * ElementSize
where L1, L2, L3 are the lower bounds of the respective dimensions.
Column-Major Order (CMO):
In CMO, elements of an array are stored column by column. The
elements of the first column are stored consecutively, followed by the
elements of the second column, and so on. For a 3D arrayA[D1][D2]
[D3], the formula for the address ofA[i, j, k] is:
48.
Code
Address(A[i, j, k])= BaseAddress + ( (k - L3) * D1 * D2 + (j - L2) * D1 + (i - L1)
) * ElementSize
(iii)To calculate the address of element A in Row-Major Order, given Base Address
= 2000, Element Size = 2 bytes, and the array bounds A[1:10, -5:5, -10:5):
Lower bounds: L1 = 1, L2 = -5, L3 = -10
Dimensions: D1 = 10, D2 = 11, D3 = 16
Using the Row-Major Order formula:
Code
Address(A[7,3,4]) = 2000 + ( (7 - 1) * 11 * 16 + (3 - (-5)) * 16 + (4 - (-10)) ) * 2
Address(A[7,3,4]) = 2000 + ( (6) * 11 * 16 + (8) * 16 + (14) ) * 2
Address(A[7,3,4]) = 2000 + ( 1056 + 128 + 14 ) * 2
Address(A[7,3,4]) = 2000 + ( 1198 ) * 2
Address(A[7,3,4]) = 2000 + 2396
Address(A[7,3,4]) = 4396
The address of element A is 4396.
49.
Applications of Array
Array stores data elements of the same data type.
Arrays help to maintain large data under a single variable name.This
avoids the confusion of using multiple variables.
Arrays can be used for sorting data elements. Different sorting
techniques like the Bubble sort, Insertion sort, Selection sort, etc
use arrays to store and sort elements easily.
Arrays can be used for performing matrix operations.
Many databases, small and large, consist of one-dimensional and
two-dimensional arrays whose elements are records.
Arrays can be used for CPU scheduling.
Arrays are also used to implement other data structures like Stacks,
Queues, Heaps, Hash tables, etc.
50.
Sparse Matrix
Ifa matrix contains more number of ZERO values than NON-
ZERO values. Such matrix is known as sparse matrix.
Sparse matrix is a matrix which contains very few non-
zero elements.
When a sparse matrix is represented with a 2-dimensional array, we
waste a lot of space to represent that matrix.
Why to use Sparse Matrix instead of simple matrix ?
Storage: There are lesser non-zero elements than zeros and thus
lesser memory can be used to store only those elements.
Computing time: Computing time can be saved by logically
designing a data structure traversing only non-zero elements.
51.
Sparse Matrix Representations
Asparse matrix can be represented by usingTWO representations,
those are as follows...
Triplet Representation (Array Representation)
Linked Representation
52.
Triplet Representation
Inthis representation, we consider only non-zero values along with
their row and column index values. In this representation, the
0th
row stores the total number of rows, columns and the
number of non-zero values in the sparse matrix.
For example, consider a matrix of size 5 X 6 containing 6 number
of non-zero values.This matrix can be represented as shown in the
image:
53.
Linked Representation
In linkedrepresentation, we use a linked list data structure to
represent a sparse matrix. In linked list, each node has four
fields.These four fields are defined 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)
Next node: Address of the next node
54.
Triangular Matrix
There aretwo types of triangular matrices:
Upper triangular matrix
Lower triangular matrix.
Triangular matrices have the same number of rows as they have
columns; that is, they have n rows and n columns.
S11 S12 S13
0 S22 S23
0 0 S33
S11 0 0
S21 S22 0
S31 S32 S33
55.
Representation of lowertriangular matrix in 1-D array
Total no. of non-zero elements in the matrix:
1+2+3+……….+n = n(n+1)/2
To find the position ofA[i][j] in 1-D array:
No. of elements above the ith
row:
1+2+3+………+(i-1) = i(i-1)/2
No. of elements before jth
column in ith
row:
= (j-1)
So, position of a[i][j] in 1-D array is:
= i(i-1)/2 + (j-1) + 1
= i(i-1)/2 + j
56.
Tri-diagonal Matrix
Representation oftri-diagonal matrix in 1-D array
Total non-zero elements = (n-1) + n + (n-1)
= (3n-2) where n is the dimension of matrix.
Index of (i,j) = [3*(i-2)+2] + [j-i+2]
= 2*i + j - 2