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

1.2 Array

The document discusses arrays including their definition, representation, indexing formulas for 1D, 2D, 3D and nD arrays, applications of arrays, sparse matrices and their representations. It also discusses operations on arrays like traversal, insertion, deletion, search and update. It provides algorithms and time complexity analysis for various array operations.

Uploaded by

Vivek Pandey
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

1.2 Array

The document discusses arrays including their definition, representation, indexing formulas for 1D, 2D, 3D and nD arrays, applications of arrays, sparse matrices and their representations. It also discusses operations on arrays like traversal, insertion, deletion, search and update. It provides algorithms and time complexity analysis for various array operations.

Uploaded by

Vivek Pandey
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

ARRAY

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.
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”.
Arrays can be declared 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.
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
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.
Search − Searches an element using the given index or by
the value.
Update − Updates an element at the given index.
Traversal of Array
The method of processing each element in the array exactly
once is known as Traversal. In array Traversal starts from
first element in the array and ends at the last element of the
array.
Traversing an array means accessing each and every element
of the array for a specific purpose. 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 Array Traversal
Step 1: START = 0
Step 2: Repeat Step-3 while (START<N)
Step 3: Read A[START]
START = START + 1
Program for Array Traversal
#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("%d\n“, A[START]);
START=START+1;
}
}
Insertion in an Array
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
Insertion at the Beginning 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
Insertion at the given 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. For All Elements from A[index] to A[N], Move to next adjacent
location
c. A[index] = New Element
4. End
Insertion after the given 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
The time complexity of insertion algorithm is:
Best case: Ω(1)
Worst Case: O(n)
Average Case: θ(n)
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


The time complexity of deletion algorithm is:
Best case: Ω(1)
Worst Case: O(n)
Average Case: θ(n)
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
Linear Search
Linear search 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.
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 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
Features of Linear Search 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.
Binary Search
Binary Search 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)
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
Time complexity of Array 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)


ISRO 2018
Which of the 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
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).
UGC NET CS 2016 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
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


Advantages and disadvantages of 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.
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.
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.
A two-dimensional array 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
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:
Column-Major Implementation
In Column-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.
UGC NET CS 2014 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 of A[11][5] ?
560
460
570
575

560
GATE-CS-2014-(Set-3)
Let A be a square 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 matrix A itself


 Transpose of matrix A
 Adding 100 to the upper diagonal elements and subtracting 100 from diagonal elements of A
 None of the above

 The matrix A itself


Multidimensional Array
 An n-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.
Representation in RMO
Representation in CMO
Address Calculation
Suppose the array 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]
AKTU Question
 Suppose a 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 in A
(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]
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.
Sparse Matrix
If a 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.
Sparse Matrix Representations
A sparse matrix can be represented by using TWO
representations, those are as follows...
Triplet Representation (Array Representation)
Linked Representation
Triplet Representation
In this 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:
Linked Representation
In linked representation, 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
Triangular Matrix
There are two 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 S11 0 0

0 S22 S23 S21 S22 0

0 0 S33 S31 S32 S33


Representation of lower triangular 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 of A[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
Tri-diagonal Matrix

Representation of tri-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

You might also like