Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

1.2 Array

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

ARRAY

Introduction to Arrays
An array is collection of items stored at contiguous memory
locations. The idea is to store multiple items of same type
together. This makes it easier to calculate the position of
each element by simply adding an offset to a base value,
i.e., the memory location of the first element of the array
(generally denoted by the name of the array).
For simplicity, we can think of an array a fleet of stairs
where on each step is placed a value (let’s say one of your
friends). Here, you can identify the location of any of your
friends by simply knowing the count of the step they are on.
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 1D array can be
calculated by the following equation,
Address of element a[k] = B+W*k
Here, B is the base address of the array, W is the size of each
element of the array, and the number of elements needed in the
array is k (i.e. index of element).
Example
For 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 visiting 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.
Traversing the data elements of an array A can include printing
every element, counting the total number of elements, or performing
any process on these elements. Since, array is a linear data structure
(because all its elements form a sequence), traversing its elements is
very simple and straightforward.
Algorithm for Array Traversal
Step 1: START = 0
Step 2: Repeat Step3 while (START<N)
Step 3: Read A [START]
           START = START + 1
Program for Array Traversal
#include<stdio.h>
#include<conio.h>
#define N 5
void main()
{
int a[N]={10,20,30,40,50};
void traverse(int *a);
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
SEEK Location 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.

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 delete an
element available at the K th position of LA.
1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set LA[J] = LA[J + 1]
5. Set J = J+1
6. Set N = N-1
7. Stop
Deleting the first element of the array

Deleting the specified element of the array


DO WE REALLY
DELETE AN
ELEMENT FROM AN
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 our Operating System tutorial series.
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
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
sequential 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
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.
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. We will discuss this in details in
the Binary Search.
It has a simple implementation.

What will be the Base for log ?


Algorithm
Binary Search is applied on the sorted array or list of large size. It's
time complexity of O(log n) makes it very fast as compared to other
sorting algorithms. The only limitation is that the array or list of
elements must be sorted for the binary search algorithm to work on it.
Following are the steps of implementation that we will be following:
1. Start with the middle element:
1. If the target value is equal to the middle element of the array, then return
the index of the middle element.
2. If not, then compare the middle element with the target value,
1. If the target value is greater than the number in the middle index, then pick the
elements to the right of the middle index, and start with Step 1.
2. If the target value is less than the number in the middle index, then pick the elements
to the left of the middle index, and start with Step 1.
2. When a match is found, return the index of the element matched.
3. If no match is found, then return -1
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. Start2. Set LA[K-1] = ITEM3. 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 O(1) O(1) O(1)

Insert O(n) O(n) O(n)

Delete O(n) O(n) O(n)

Search O(1) O(n) O(n)


Advantages and disadvantages of Arrays

Advantages
1. Reading an array element is simple and efficient. As
shown in the above table, the read time of array is O(1) in
both best and worst cases. 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 LinkedList, 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. The second or the rightmost
index of an array alters very fastly as compared to the first or
left-most index while accessing the elements of an array.
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 4 rows and 3 columns then
it can be stored in the memory in the following
manner:
8 6 5 4
2 1 9 7
3 6 4 2
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.
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 you 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.
Now to find the address of any element of the array based on the
given index number and given dimension size, given element size
(data type size) and given base address:
Suppose the array is of n-dimensions having the size of each
dimension as S1, S2, S3, ..., Sn and the element size is ES, Base
Address is BA and the index number of the element to find the
address is given as i1, i2, i3, . . . .in .Then the formula will be:
Address of A[i1][ i2][ i3]. . . .[ in] = BA + ES*[ i1*( S2* S3* S4 *. . ..*
Sn) + i2*( S3* S4* S5 *.. .. * Sn) + ... + in-2*( Sn-1*Sn) + in-1*Sn + in ]
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 'm' columns and 'n' 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

You might also like