0% found this document useful (0 votes)
21 views49 pages

1.2 Array

Uploaded by

ucem pavan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views49 pages

1.2 Array

Uploaded by

ucem pavan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

ARRAY

Introduction to Arrays
The simplest type of data structure is a linear (or 1-Dimensional)
array.
One way is to have linear relationship between elements by
means of sequential memory locations and other way is to
have a linear relationship between elements by means of links
(relationship of adjacency is maintained by link).
An array is collection of items stored at contiguous memory
locations. The idea is to store multiple items of same type
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.
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)
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*k
Here, W is the size of each element of the array, and k is the
index 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
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
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.
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 downward. Here, we design and implement
an algorithm to insert an element at the beginning of an array.
 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.
Algorithm
1. Begin
2. IF N == MAX
return
3. ELSE N = N + 1
For all Elements in A Move to next adjacent location
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 downward. 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
SEEK Location index
For All Elements from A[index] to A[N]
Move to next adjacent location
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
Input index
For All Elements from A[index + 1] to A[N]
Move to next adjacent location
A[index + 1] = New Element
3. End
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


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, which you can
learn more about in Operating System.
 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 and unordered small list of elements.
It has a time complexity of O(n), which means the time is
linearly dependent on the number of elements, which is not
bad, but not that good too.
It has a very simple implementation.
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 time complexity of O(log n) which is a very good
time complexity.
It has a simple implementation.
Updating an Array
Update operation refers to updating an existing element
from the array at a given index.
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
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]
Advantages and disadvantages of Arrays
Advantages
1. Reading an array element is simple and efficient. This is
because any element can be instantly read using indexes
(base address calculation behind the scene) without
traversing the whole array.
2. Array is a foundation of 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.
Disadvantages
1. While using array, we must need to make the decision of
the size of the array in the beginning, 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.
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
GATE-CS-2014-(Set-3)
Let A be a square matrix of size n x n. Consider the following program. What is the expected
output?
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
Multidimensional Array
An n-dimensional matrix can be of any dimension. Adding
a dimension is adding one more index number (to access
the element). In 1-D array the elements are linearly
arranged and can be addressed as a[0], a[1], .. .
In 2-D array elements are logically in the form of matrix
having row and column index and can be represented as
a[0][0], a[0][1] etc. and they are stored row wise in the
memory, because the memory is linear.
Now a 3-D array is nothing but a logical structure which can
be accessed by 3 index numbers. If the array is of size 3 in
all the dimensions (int a[3][3][3] then it is stored in the
memory in the following order:
a[0][0][0], a[0][0][1], a[0][0][2], a[0][1][0], a[0][1][1], a[0]
[1][2], a[0][2][0], a[0][2][1], a[0][2][2], a[1][0][0], a[1][0]
[1] and so on.
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]
Applications of Array
Apart from being widely used in programming, arrays have
additional applications as well:
Used in mathematical problems like matrices etc.
They are used in implementation of other data structures like
linked lists, stack, queue etc.
Database records are usually implemented as arrays.
Used in lookup tables by computer.
It effectively executes memory addressing logic wherein
indices act as addresses to the one dimensional array of
memory.
Sparse Matrix
 In computer programming, a matrix can be defined with a 2-dimensional array. Any
array with ‘n' columns and ‘m' rows represent a m X n matrix. There may be a
situation in which 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. For example, consider a matrix of size 100 X 100
containing only 10 non-zero elements. In this matrix, only 10 spaces are filled with
non-zero values and remaining spaces of the matrix are filled with zero. That means,
totally we allocate 100 X 100 X 2 = 20000 bytes of space to store this integer matrix.
And to access these 10 non-zero elements we have to make scanning for 10000
times. To make it simple we use the following sparse matrix representation.

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,
total number of columns and the total 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