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

Lecture 1.7 - Array Traversing Insert Delete Presentation

The document discusses various array data structures including linear arrays, multidimensional arrays, and sparse matrices. It provides details on how arrays are represented in memory, including the use of indexes and base addresses to calculate element locations. Algorithms for traversing, inserting, deleting and accessing elements of arrays are presented. Representations of two-dimensional and multidimensional arrays in memory are described.

Uploaded by

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

Lecture 1.7 - Array Traversing Insert Delete Presentation

The document discusses various array data structures including linear arrays, multidimensional arrays, and sparse matrices. It provides details on how arrays are represented in memory, including the use of indexes and base addresses to calculate element locations. Algorithms for traversing, inserting, deleting and accessing elements of arrays are presented. Representations of two-dimensional and multidimensional arrays in memory are described.

Uploaded by

Raghav Agarwal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

APEX INSTITUTE OF TECHNOLOGY

DEPARTMENT: CSE

Bachelor of Engineering (Computer Science & Engineering)


DATA STRUCTURES CST-231
Prepared by: Dr. Rajiv Kumar- E8509

ARRAY IN DATA STRUCTURE DISCOVER . LEARN . EMPOWER


09/06/2021
Agenda

• Introduces:
• Linear array and it’s representation in main memory.
• Operations of a linear array
• Multidimensional array
• 2-dimensional array representation in a memory
• Pointer
• Pointer Arrays
• Records
• Parallel Arrays

09/06/2021
Contents
• Introduction
• Linear Array
• Linear Array Representations in Memory
• Traversing, Insert, and Delete Algorithms
• Multidimensional Array
• 2-D Array
• Representations in Memory
• Inconsistency Matrix Algorithms

09/06/2021
Arrays
• Arrays: - Linear DS Homogeneous (same type) data elements.
Index   Data
     
1   100
2   200
3   300 Index 1 2 3 4 5 6 7
4   400
5   500 Data 100 200 300 400 500 600 700
6   600
7   700

09/06/2021
Arrays

• Easy to traverse
• Easy to search & sort
• Used to store relatively permanent collections of data.

• Types of arrays:-
• Linear arrays
• Two dimensional arrays
• Multidimensional arrays

09/06/2021
Representation of Linear array
• LOC(LA[K]) = address of the element LA[K] of the array LA

• LOC(LA[K])=Base(LA)+w(K-lower bound)

• where w is the number of words per memory cell for the array
LA.

09/06/2021
Representation of Array in a Memory
The process to determine the address in a memory:
a) First address – base address.
b) Relative address to base address through index function.
Example: char X[100];
Let char uses 1 location storage.If the base address is 1200 then the next
element is in 1201.Index Function is written as:
Loc (X[i]) = Loc(X[0]) + i , i is subscript and LB = 0

1200 1201 1202 1203…………..

X[0] X[1] X[2]


09/06/2021
Representation of Array in a Memory
 In general, index function:
Loc (X[i]) = Loc(X[LB]) + w*(i-LB);

where w is length of memory location required.


For real number: 4 byte, integer: 2 byte and character: 1 byte.
 Example:
If LB = 5, Loc(X[LB]) = 1200, and w = 4, find Loc(X[8]) ?

Loc(X[8])= Loc(X[5]) + 4*(8 – 5)


= 1212
09/06/2021
Traversing Algorithm
Here A is a linear array with lower bound LB and upper bound UB.
This algorithm traverses A applying an operation PROCESS to each element
of A.

1. [Initialize counter] Set K = LB.


2. Repeat steps 3 and 4 while K ≤ UB.
3. [Visit element] Apply PROCESS to A[K].
4. [Increase counter] Set K = K + 1.
[End of step 2 loop]
5. Exit
09/06/2021
Insertion Algorithm
INSERT (A, N, K, ITEM)
Here A is a linear array with N elements and K is a positive integer such
that K ≤ N.
This algorithm inserts an element ITEM into the Kth position in A.
1. [Initialize counter] Set J = N.
2. Repeat steps 3 and 4 while J ≥ K.
3. [Move Jth element downward] Set A[J + 1 ] = A[J]
[Decrease counter] Set J = J – 1
[End of step 2 loop]
4. [Insert element] Set A[K] == ITEM
5. [Reset N] Set N = N + 1
6. Exit
09/06/2021
Deletion in an Array
Deletion is removing an existing element from the array and re-
organizing all elements of an array.
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 Kth 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
09/06/2021
Advantages:

1. It is used to represent multiple data items of same type by using only

single name.

2. It can be used to implement other data structures like linked lists,

stacks, queues, trees, graphs etc.

3. 2D arrays are used to represent matrices.

09/06/2021
Disadvantages
1. We must know in advance that how many elements are to be stored
in array.
2. Array is static structure. It means that array is of fixed size. The
memory which is allocated to array can not be increased or reduced.
3. Since array is of fixed size, if we allocate more memory than
requirement then the memory space will be wasted. And if we
allocate less memory than requirement, then it will create problem.

4. The elements of array are stored in consecutive memory locations.


So insertions and deletions are very difficult and time consuming.

09/06/2021
Two-Dimensional Arrays

• A two-dimensional m ᵡ n array A is a collection of m.n data elements


such that each element is specified by a pair of integers, called
subscripts, with the property that
1 ≤ J ≤ m& 1≤K≤n

It is also called matrices/matrix arrays in mathematics, tables in


business applications.

09/06/2021
Example
• Suppose each student in a class of 25 students is given 4 tests. Assuming
the students are numbered from 1 to 25, the test scores can be assigned to
a 25 ᵡ 4 matrix array SCORE as in table. Thus SCORE[K,L] contains the
Kth student’s score on the Lth test. In particular, the second row of the
array, Contains the four test scores of the second student.
SCORE[2,1], SCORE[2,2], SCORE[2,3], SCORE[2,4]
Student Test 1 Test 2 Test 3 Test 4
1 84 73 78 88
2 56 58 78 67
3 56 77 45 67
: : : : :
25 76 78 80 45

09/06/2021
Formula to calculate the Two-D Arrays

• Length = UB – LB +1

If integer NUM (2:5, -3:1), then find the length of 1st & 2nd dimensions.
Length of 1st dimension = 5 – 2 + 1 = 4
Length of 1st dimension = 1 – (-3) + 1 = 5
Number contains 4 * 5 = 20 elements.

09/06/2021
Representation of 2-D Arrays

Divided into two parts: -


• Column-major order (Column by Column)
• Row-major order (Row by Row)

09/06/2021
Computing of 2-D Arrays
• Column-major order:-
• LOC(A[J,K]) = Base(A) + w[M(K – 1) + (J – 1)]
• Row-major order: -
• LOC(A[J,K]) = Base(A) + w[N(J – 1) + (K – 1)]
eg:- Consider the 25 * 4 matrix array SCORE in previous example.
Suppose Base(SCORE) = 200 & there are w = 4 words per memory cell.
Furthermore, suppose the PL stores 2-D arrays using row-major order. Then the
address of SCORE[12,3], the third test of the 12th student, follows:
LOC(SCORE[12,3]) = 200 + 4 [4(12 – 1) + (3 – 1)]
= 200 + 4[46] = 384

09/06/2021
Multidimensional Arrays

• Li = UB – LB + 1

for a given subscript Ki, the effective index Ei of Li is the number of


indices preceding Ki in the index set, & Ei can be calculated from
Ei = Ki – LB Base (C) + w[(…((E1L2 + E2)L3 + E3)L4 +….+EN-1 )LN
+ EN

09/06/2021
How to Calculate Multidimensional Arrays
• Suppose a 3-D array MAZE is declared using MAZE(2:8, -4:1, 6:10). Then the lengths of the 3-D of
the MAZE are, respectively,
L1 = 8 – 2 + 1 = 7, L2 = 1 – (-4) + 1 = 6, L3 = 10 – 6 + 1 = 5
Accordingly, MAZE contains L1 . L2 . L3 = 7 * 6 * 5 = 210 elements
suppose the PL stores MAZE in memory in row-major order & suppose Base(MAZE) = 200 & there are
w = 4 words per memory cell.
eg: - The address of MAZE[5, -1, 8]:-
E1 = 5 – 2 = 3 E2 = -1 – (-4) = 3 E3 = 8 – 6 = 2
E1 L2 = 3 * 6 = 18
E1 L2 + E2 = 18 + 6 = 21
(E1 L2 + E2)L3 = 21 * 5 = 105
(E1 L2 + E2)L3 + E3 = 105 + 2 = 107
Therefore, LOC(MAZE[5, -1, 8] = 200 + 4(107) = 628

09/06/2021
Sparse matrix
Matrix with relatively a high proportion of zero entries are called sparse
matrix. Two general types of n-square sparse matrices are there which
occur in various applications are mention in figure below(It is
sometimes customary to omit blocks of zeros in a matrix as shown in
figure below)

09/06/2021
Triangular and Tridiagonal matrix
• Triangular matrix:
• This is the matrix where all the entries above the main diagonal
are zero or equivalently where non-zero entries can only occur
on or below the main diagonal is called a (lower)
• Tridiagonal matrix:
• This is the matrix where non-zero entries can only occur on the
diagonal or on elements immediately above or below the diagonal
is called a Tridiagonal matrix.
• The natural method of representing matrices in memory as two-
dimensional arrays may not be suitable for sparse matrices i.e. one
may save space by storing only those entries which may be non-
zero.
09/06/2021
Records: Record Structures
• Collections of data organized into: -
• Field, records, & files
• Record: - collection of related data items, each of which is
called a field/attribute
• File: - collections of similar records.
• Each data items itself may be a group item composed of sub-
items; those items which are indecomposable are called
elementary items/atoms/scalars.
• The names given to the various data items  identifiers.
Record

• Collection of non-homogeneous data; i.e., the data items in a record


may have different data items.
• The data items in a record are indexed by attribute names, so there
may not be a natural ordering of its elements.
Record Structures
eg:- Employee record
1 Employee
2 Social sec no
2 Name
3 Last
3 First
3 Middle
2 Address
3 Street
3 Area
4 City
4 State
4 ZIP
2 Age
2 Salary
2 Dependents
Pointer Arrays
Pointer
• Let DATA be any array. A variable P is called a pointer if P “points” to
an element in DATA.
• An array PTR is called a pointer array if each element of PTR is a
pointer.
• Used to facilitate the processing of the information in DATA.
• Arrays whose rows – columns begin with different numbers of data
elements & end with unused storage locations  jagged
Arrays of Pointers

• Normally, we’re used to Arrays containing ints, doubles, etc


• We can also make arrays of Pointers.
• This is most commonly seen with Arrays of C-Style strings.
Array of Pointers
const char* suit =
{“Clubs”,”Diamonds”,”Hearts”,”Spades”)

• This basically says “each element is of type pointer to char”


Memory Management Functions

Memory management functions handle the allocation and de-


allocation of dynamic memory. These functions form an abstraction
layer above the standard C memory management functions calloc,
malloc, free, and realloc.
Memory Allocation Functions

• malloc: Allocates requested number of bytes and returns a pointer to the first
byte of the allocated space.
• calloc: Allocates space for an array of elements, initializes them to zero and
then returns a pointer to the memory.
• free : Frees previously allocated space.
• realloc: Modifies the size of previously allocated space.
Dynamic allocation of two-dimensional arrays

int **array;
int i,j,10;
array = malloc(10*sizeof(int*));
for(i=0;i<10;i++)
for(j=0;j<10;j++)
array[i][j] = i*j;

While the first layer of array is allocated,


the second layer is not. Each array[i]
needs to be allocated to be used as an
array. Therefore, add a malloc statement
inside the loop
Dynamic Memory Management

• C/C++ provides a set of operators, called dynamic memory


management operators, to allocate & de-allocate memory at
execution time, i.e. dynamically.
• The memory allocated dynamically, must be de-allocated before your
program finishes its execution.
• Dynamic Memory Allocation
• Memory space required can be specified at the time of execution.
• C supports allocating and freeing memory dynamically using
library routines.
New Operator

• Allocates the memory & always returns a pointer to an appropriate


type.
• Syntax: -
type * new type [size in integer];
Example: -
int *intPtr;
intPtr = new int [100];
Cont’d
• It permits the initialization of memory locations during allocation.
• Syntax: -
type *ptrVar = new type (IntialValue);

Example: - int *intPtr = new int (100);

This statement allocates memory for an integer number & initializes it


with value 100. The address of the memory allocated memory is
assigned to pointer variable intPtr.
Delete Operator

• A counterpart of new operator & it de-allocates memory allocated by


the new operator back to the free poll of memory.

• Syntax: -
delete ptrVar;
Pointers
int *intPtr; Create a pointer

intPtr = new int; Allocate memory

*intPtr = 6837; Set value at given address

*intPtr 6837
intPtr 0x0050

delete intPtr; Deallocate memory

int otherVal = 5; Change intPtr to point to


intPtr = &otherVal; a new location

*intPtr 5 otherVal
intPtr 0x0054 &otherVal
REFERENCES

• Lipschutz, Seymour, “Data Structures”, Schaum's Outline Series, Tata McGraw Hill.
• Goodrich, Michael T., Tamassia, Roberto, and Mount, David M., “Data Structures and Algorithms in C++”, Wiley Student
Edition.
• Gilberg/Forouzan,” Data Structure with C ,Cengage Learning.
• Augenstein,Moshe J , Tanenbaum, Aaron M, “Data Structures using C and C++”, Prentice Hall of India
• https://www.tutorialspoint.com/data_structures_algorithms/algorithms_basics.htm
• https://www.cs.utexas.edu/users/djimenez/utsa/cs1723/lecturehtml

09/06/2021

You might also like