Arrays Week3

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

WEEK 3

DATA STRUCTURES
AND ALGORITHMS

ARRAYS
DEFINITION OF AN ARRAY
 An array is a list of contiguous memory cells that store data of the same
type.
 An array is a finite, ordered collection of homogeneous data elements.
 The idea is to store multiple items of the same type together.
 It 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)
 Array data structure is usually finite and ordered in nature in the sense that it
stores only a known number of data items as per its size in ordered memory
cells.
BASIC TERMINOLOGIES OF ARRAYS

 Element: This refers to any data or item stored in an array.

 Size: The size of an array refers to the total number of elements that
can be stored in an array.
 Name: Every array must have a name. In the case of the figure in the
next slide, the array is called ages.
 Type: Type refers to the kind of data stored in an array. The data type
can be an integer, decimal, or textual (string or character).
BASIC TERMINOLOGIES OF ARRAYS
 Cell: A single memory location of an array is called a cell. The total number
of cells of an array is equal to the size of the array.
 Index: An array index is a positive integer that uniquely identifies a cell of
an array. Indexing of arrays usually starts from zero (0) to the size of the
array minus one (1) in
 Pointer: A memory location where data is stored.
CHARACTERISTICS OF ARRAYS
 Homogeneity: All elements in an array are of the same data type.
 Fixed Size: the size of an array is fixed and must be specified at the time of
declaration. This is static location.
 Contiguous Memory Allocation: Elements are stored in contiguous memory
locations which facilitates quick access to elements.
 Random Access: Elements can be accessed randomly using indices. The first
element has an index of 0.
STRUCTURE OF AN ARRAY
ARRAY REPRESENTATION
 The representation of an array can be defined by its
declaration.
 A declaration means allocating memory for an array of a
given size.

 Arrays can be declared in various ways in different languages.


CONT’D
 The index starts with 0.
 The array length is 10 which means it can store 10 elements.
 Each element can be accessed via its index. For example, we can
fetch an element at index 4 as 18.
OPERATIONS ON ARRAYS
 The basic operations that can be performed on arrays are:
 Traverse: traversing means visiting each element in the array and printing
them one by one.
 Search: To check whether a particular element exists in the array.
 Insertion: involves adding a new element to the array.
 Deletion: deleting an element involves removing an element from the
array.
 Sorting: sorting algorithms arrange array elements in a specific order
(e.g., Ascending or descending)
OPERATIONS ON ARRAYS
Update: Updates an element at the given index.
Reversing of elements: reversing changes the order
of elements in the array.
Merging: merging combines two sorted arrays into
a single sorted array.
CODE IMPLEMENTATION OF
ARRAYS
Declaration of an Array
Int arr[5]; // declaring an array of size 5
 Initializing an Array
Int arr[5] = {1, 2, 3, 4, 5}; //
declaration and initialization
TRAVERSAL OPERATION
 Traversing an array refers to
visiting all the elements of the
array and processing (printing)
them.
 Traversal starts from the first
element (index 0) of the array and
processes each element in steps
one up to the last item.
C++ CODE IMPLEMENTATION OF ARRAYS
Traverse an Array
#Include <iostream> using namespace std;
void traversearray (int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " "; } cout << endl;
}
int main( ) {
int arr[5] = {1, 2, 3, 4, 5};
traversearray(arr, 5);
return 0; }
INSERTION OPERATION
• An element can be added to an array
only if it is not full.
• An element can be added to the
beginning, end, or at a given index
of the array per the requirements of
the array.
• To insert an item at a given location
(index): Move all elements a step
forward starting from the last
element of the array to the location
to insert the new item as represented
in the figure in the next slide.
INSERTION OPERATION
C++ CODE IMPLEMENTATION OF ARRAYS
 Insertion in an Array
// Function to insert an element at a given position
Void insertelement (int arr[], int
size, int element, int position) {
For (int i = size - 1; i >= position -
1; i--) {
arr[i + 1] = arr[i]; } arr[position -
1] = element; }
DELETION OPERATION
 To delete an item at a given
index or location,
 Simply move all elements a
step backward starting from the
index just after the index of the
item to be deleted to the last
element in the array.
 As the elements move, they
override other elements
originally at various indices.
Figure in the next slide
illustrates the delete operation.
DELETION OPERATION
CODE IMPLEMENTATION OF ARRAYS
Deletion from an Array
// Function to delete an element from a given
position
void deleteelement (int arr[], int
size, int position) {
for (int i = position - 1; i < size -
1; i++)
{
arr[i] = arr[i + 1]; } }
SEARCH OPERATION
• This operation checks the
existence of an item in an array.
• The operation returns or prints
the element and/or its location
(index) in the array.
• To search for an item using a
sequential search requires
visiting every element and
comparing it with the search
item starting from the first index.
C ++ CODE IMPLEMENTATION OF ARRAYS
Searching in an Array
// Function to search for an element in the array
Int searchelement (int arr[], int size, int
element) {
for (int i = 0; i < size; i++) {
if (arr[i] == element) {
return i;
} }
return -1; }
C++ CODE IMPLEMENTATION OF ARRAYS
 UPDATING AN ELEMENT IN AN
ARRAY
// Function to update an element at a given
position
void updateelement(int arr[], int
position, int element) {
arr[position] = element;
}
SORTING OPERATION
• This operation orders elements
in ascending or descending
order.
• Elements can be sorted by
comparing elements next to
each other and swapping them
to follow a required order
starting from the first element.
• This process must be repeated
until the elements are
completely sorted.
MERGE OPERATION
• The merge operation combines
two or more arrays to form a
single array.
• To merge two arrays, a new
array is created with a size equal
to the sum of the size of both
arrays.
• Elements are then retrieved
sequentially from the two arrays
and inserted into the new array.
MULTIDIMENSIONAL ARRAYS
A multidimensional array is an array that contains
other arrays as its elements. In other words, it's an array of
arrays.
This allows you to represent data in multiple dimensions,
such as rows and columns, similar to a table or a grid.
• In a two-dimensional array, each element is identified by
two indices: one for the row and one for the column.
• In a three-dimensional array, each element is identified
by three indices, and so on for higher-dimensional arrays.
MULTIDIMENSIONAL ARRAY CONT’D
2-dimensional arrays 3-dimensional arrays
CODE EXAMPLE OF MULTIDIMENSIONAL ARRAYS
2-dimensional arrays 3-dimensional arrays
#Include <iostream> #Include <iostream>
Using namespace std; Using namespace std;
Int main() { Int main() {
// declaration and initialization of // declaration and initialization of a 3d
a 2D array array
Int my2darray[3][4] = { {1, 2, 3, 4},{5, Int my3darray[2][3][4] = { {{1, 2, 3, 4},
6, 7, 8},{9, 10, 11, 12} }; {5, 6, 7, 8},{9, 10, 11, 12}}, { {13, 14,
15, 16}, {17, 18, 19, 20}, {21, 22, 23,
// accessing and printing elements 24} } };
Cout << "2D array:\n"; // Accessing and printing elements
For (int i = 0; i < 3; ++i) { Cout << "3D array:\n";
for (int j = 0; j < 4; ++j) { For (int i = 0; i < 2; ++i) {for (int j =
Cout << my2darray[i][j] << " "; 0; j < 3; ++j) {
} cout << endl; for (int k = 0; k < 4; ++k) { cout <<
my3darray[i][j][k] << " ";
} Return 0;}
ADVANTAGES MULTIDIMENSIONAL ARRAYS
 Using multidimensional arrays provides an organized way to represent
complex data relationships.
 Organizing related data into a multidimensional array allows for efficient
storage and quick retrieval of specific data points using indices.
 Using multiple indices such as row and column makes it easier to locate
specific elements in multidimensional arrays.
 In mathematical and scientific applications, matrices are useful for
performing operations like matrix multiplication common in linear algebra
and computer graphics.
 Multidimensional arrays are adaptable, making them suitable for various
applications, including image processing, game development, and
scientific simulations.
AND ADDRESS
CALCULATION
Sequential allocation is a method of assigning memory
continuously or sequentially.
Every process or program is loaded into a block of
memory next to each other.
This makes it easy to implement and requires minimal
effort.
However, it can cause fragmentation issues, which means
that unused memory can be found within a block or
scattered throughout the system.
TYPES OF SEQUENTIAL
SINGLE CONTINUOUS MULTIPLE CONTINUOUS
ALLOCATION ALLOCATION
ALLOCATION
Each process is loaded Each process is divided into
into a single contiguous multiple contiguous blocks,
block of memory. which may not necessarily be
Simple and easy to adjacent.
implement. Helps reduce fragmentation
Prone to fragmentation to some extent.
issues Requires more complex
memory management.
CALCULATING ADDRESS LOCATION
1 DIMENSIONAL ARRAY
ADDRESS OF THE Kth ELEMENT= B + W * (K - LB)
 Base Address = B (104)
 Lower Bound =LB (0) 2

 Memory Required to store 1 element = W(2) 9


5
 Let K(index)= 3 and the corresponding
4
element is 4 6
 A [K] = 104 + 2 *(3-0)
 A [K] = 104 + 2 * 3
 A [K] = 104 + 6
 A [K] =110
 The corresponding element at address location 110 is 4.
CALCULATING ADDRESS LOCATION
TRIAL QUESTIONS
1. Consider the linear array A[16:30]. If the base address is
100 and the space required to store an element is 4 words,
Then what is the address of A[27]?
2. Consider the Linear Array A[-5:30]. If the base address is
150 and the space required to store each element is 2
words, what is the address of A[15]?
3. Consider the Linear Array A[200:250]. If the base address
is 200 and the space required to store each element is 2
words, what is the address of A[215] and A[241]?
CALCULATING ADDRESS LOCATION

2 DIMENSIONAL ARRAYS
Row major storage
Address of A[i][j] = B + W * [ N * (i-Lr) + (j-Lc)]
Column major storage
Address of A[i][j] = B + W * [ (i-Lr) + M * (j-Lc)]
 B = Base Address
 Lr =Lower bound of row
 Lc = Lower bound of column
 M = number of rows in the matrix
 N = number of columns in the matrix
 i = Row subscript of the element whose address is to be found
 j = Column subscript of the element whose address is to be found
CALCULATING ADDRESS LOCATION
Row major storage
Address of A[i][j] = B + W * [ N
* (i-Lr) + (j-Lc)]
A[2][1] = 104 + 2 [ 4 * (2 -0) +
(1-0) ]
= 104 + 2 [ 4 * 2 + 1]
= 104 + 2 [8 + 1]
= 104 + 2(9)
= 104 + 18
= 122
CALCULATING ADDRESS LOCATION
Row major storage
Address of A[i][j] = B + W * [ (i-Lr) +
M * (j-Lc)]
A[2][2] = 104 + 2 [ 4 * (2 -0) + (2-0) ]
= 104 + 2 [ 4 * 2 + 2]
= 104 + 2 [8 + 2]
= 104 + 2(10)
= 104 + 20
= 124
APPLICATION OF ARRAYS
 Matrix Manipulation: Arrays are efficient in representing and
manipulating matrices, which is essential in various fields like
graphics, scientific computing, and linear algebra. We will cover
operations such as matrix addition, multiplication, and transposition
using arrays.
 Strings as an array of characters: strings in many programming
languages are represented as arrays of characters.
 String Manipulation: Beyond simple concatenation, arrays are
integral in more complex string manipulations, including substring
extraction, reversal, and searching.
 Pattern Matching: arrays play a crucial role in pattern-matching
algorithms, where we search for a specific pattern within a larger set
of data
LIMITATIONS OF ARRAYS

1. Fixed size: the size of the array is static. One cannot


change the size once it is declared.
2. Memory waste: if the array is not fully utilized, the
remaining memory allocated to the array is wasted.
3. Memory overflow: if more elements are added than
the allocated size, it leads to memory overflow.

You might also like