0% found this document useful (0 votes)
25 views39 pages

DS - Lecture 03 - Arrays

Arrays

Uploaded by

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

DS - Lecture 03 - Arrays

Arrays

Uploaded by

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

DATA STRUCTURES

(CS3401)

Dr. Somaraju Suvvari,


Asst. Prof, Dept. of CSE, NIT Patna.
[email protected];
[email protected];

Dr Somaraju Suvvari NITP -- CS3401 1


The Course

DATA STRUCTURES

Dr Somaraju Suvvari
2
NITP -- CS3401
ARRAYS

Dr Somaraju Suvvari
3
NITP -- CS3401
UNIT II: Arrays

1-D arrays, multi-dimensional arrays, operating on arrays, Dynamic memory


allocation, Storage – Column major order and Row major order, Address
calculation of 1-D, 2-D, different form of matrix, Sparse Matrix. Linked lists –
singly, doubly and circularly linked lists, operations on linked lists.

Dr Somaraju Suvvari
4
NITP -- CS3401
Why do we use Arrays?
• Consider the following situations

• To store the marks secured by students of a class in a particular subject.

Ex: 72, 85, 67, 59, 88, 0, 50, …

• To store the marks of students in all the subjects of a semester.

• To store the names of the patients in a hospital management system.

• To store the distances from a location to another locations.

• In all the above situations, we need a structure to store all these similar values under
the same name

Dr Somaraju Suvvari
5
NITP -- CS3401
Arrays
• Array is a structure which fulfils all these requirements – It is a collection of
homogeneous (of same data type) data items stored in consecutive memory locations
and addressed by a common identifier.

Example - int marks [80].

Here - int is a data type

- marks is an identifier name

- 80 is the size of the array (it must be integer constant ).

Dr Somaraju Suvvari
6
NITP -- CS3401
Arrays
• Array is a structure which fulfils all these requirements – It is a collection of homogeneous (of same
data type) data items stored in consecutive memory locations and addressed by a common identifier.

• There are two variations in arrays – One dimensional arrays (1-D) and multidimensional arrays.

• 1-D arrays store one row of elements(store marks of a student in n subjects) and multidimensional
arrays store two or more rows of elements (store n students marks in m subjects, each row store one
student marks).

• 1-D array Example - int marks [80]. // 1-D declaration

Here - int is a data type

- marks is an identifier name

- 80 is the size of the array (it must be integer constant ).

Dr Somaraju Suvvari
7
NITP -- CS3401
Arrays
• 2-D (multidimensional) array Example - int marks [2][3]. // 2-D declaration

Here - int is a data type

- marks is an identifier name

- 2 is the number of rows and 3 is the number of elements in each row.

Dr Somaraju Suvvari
8
NITP -- CS3401
1-D Array Declaration

// array of 10 uninitialized integers

• int myList[10]; // an array myLIST of size 10


• By the above declaration, myList has no values initialized for its elements.

• Such an array contains garbage values initially.

• It creates contiguous memory locations.


myList 0 1 2 3 4 5 6 7 8 9

7042 -- -- -- -- -- -- -- -- -- --
2020 7042 7046 7050 7054 7058 7062 7066 7070 7074 7078

Dr Somaraju Suvvari
9
NITP -- CS3401
Contiguous Memory Allocation

• int a, b, c; // Memory allocation is not contiguous

a -- b -- c --
3042 4202 4206

int marks[10]; // always it is contiguous memory allocation

• Hence, faster access of data


marks 0 1 2 3 4 5 6 7 8 9
7042 -- -- -- -- -- -- -- -- -- --
2028 7042 7046 7050 7054 7058 7062 7066 7070 7074 7078

Dr Somaraju Suvvari
10
NITP -- CS3401
How to access individual elements of the Array?
• Each data items or element of the array can be referred using a subscript or an
index to its relative position.

• Note – In C the index of the array always goes from 0 to n - 1, where the size of
the array is n.

• For example a declaration marks[10] identifies the elements marks[0], marks[1],


…. , marks[9].

Note: With the declaration marks [10], there is no data elements which can be
referred to as marks[10].

Example – marks [5] refers to the 6th element of the array marks.
Dr Somaraju Suvvari
11
NITP -- CS3401
Array Initialization

• Initialization can be done in several ways.


• Consider the following declaration
int a[4]; // an integer array of size 4.
• Both declaration and initialization in single step.
• Ex. int a[4] = {1, 2, 3, 4};
• Or by accessing a particular location
• Ex. a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4;
• Or by the user
• Ex. scanf(“%d”, &a[index]); ; // where index is a value in {0,1,2,3}.

Dr Somaraju Suvvari
12
NITP -- CS3401
Array Element Manipulations
• Consider
int a[10], i = 7, j = 2, k = 4;
a[0] = 1;
a[i] = 5;
a[j] = a[i] + 3;
a[j+1] = a[i] + a[0];
a[a[j]] = 12;
scanf(“%d”, &a[k]);// where the next input value is 3

0 1 2 3 4 5 6 7 8 9
a 1 -- 8 6 3 -- -- 5 12 --
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

Dr Somaraju Suvvari
13
NITP -- CS3401
2-D Array Declaration

// array of 10 uninitialized integers

• int myList[3][3]; // an array myLIST of size 3 X 3


• It creates contiguous memory locations.

myList 0 1 2 3 4 5 6 7 8
7042 -- -- -- -- -- -- -- -- --
1024 7042 7046 7050 7054 7058 7062 7066 7070 7074

Dr Somaraju Suvvari 14
NITP -- CS3401
How to access individual elements of the 2-D Array?

• Elements in Two-Dimensional arrays are accessed using the row indexes and
column indexes.

• Example:
• a = x[2][1]; // Access the element present in third row and second column.

Dr Somaraju Suvvari
15
NITP -- CS3401
How to initialize 2-D elements ?
• Initialization can be done in several ways.
• Consider a declaration
int a[2][2]; // an integer array of size 2 X 2.
• Both declaration and initialization in single step.
• int a[2][2] = {1, 2, 3, 4};
• int a[2][2] = {{1, 2}, { 3, 4}};
• int a[][2] = {{1, 2}, { 3, 4}};
• int a[][2] = {1, 2, 3, 4};
• Or by accessing a particular location
• Ex. a[0][0] = 1; a[0][1] = 2; a[1][0] = 3; a[1][1] = 4;
• Or by the user
• Ex. scanf(“%d”, &a[i][j]); ; // where i is 0 or 1 and j is 0 or 1.
Dr Somaraju Suvvari
16
NITP -- CS3401
Algorithm for Displaying Integer Array elements in
reverse order

• Algorithm:
int a[10] ; // declare an array of size 10

• Starting with i from 1 to n // read the values into a

• Read the number into a[i]

• Starting with i from n to 1 // output the values into a

• Output a[i]

Dr Somaraju Suvvari
17
NITP -- CS3401
Algorithm for converting the given decimal number into binary
Algorithm -
• int b[10] ; //declare array a of size 10 to store the digits of binary number
• Input n // read the decimal number
• Let m = n, i = 1;
• while n is greater than or equal to 0
• b[i] = n % 2;
• i = i + 1 ; n = n/2;
// Display the remainders in reverse order. Why ?
• i = i – 1;
• while i is greater than or equal to 1
• output a[i]; i = i – 1;

Dr Somaraju Suvvari 18
NITP -- CS3401
Computation of decimal to binary
• Consider a decimal number n = 23.
• The binary representation of 23 is 10111
i=0, n=23 => b[0] = n % 2 = 1 => n = n/2
i=1, n = 11 => b[1] = n % 2 = 1 => n = n/2
i=2, n = 5 => b[2] = n % 2 = 1 => n = n/2
i=3, n = 2 => b[3] = n % 2 = 0 => n = n/2
i=4, n = 1 => b[4] = n % 2 = 1 => n = n/2
i=5, n = 0
• As the computation results in reverse order of bits.
• Need to print the binary values from last to first
Dr Somaraju Suvvari 19
NITP -- CS3401
Merging of two sorted lists
Consider two sorted lists a[] and b[] containing m and n elements in ascending order
respectively.
To merge the two lists into another list c[] in ascending order.
Constraints:
• It is not known whether m < n or m =n or m > n.
• There could be some duplicate elements in a[] or b[] or by considering both.
Process:
In each of the m+n steps, compare one element of a[] and one element of b[] and
copy smaller one into c[].

Dr Somaraju Suvvari
20
NITP -- CS3401
Merging of two sorted lists
Algorithm:
Let a[], b[] contain m and n sorted integers.
Initialize i, j, k, (indices of a, b and c) to 0.
while i < m && j < n // both lists are non-empty
if a[i] < b[j], copy a[i] to c[k], increment i and k
else copy b[j] to c[k], increment j and k
// b is exhausted. Remaining Elements of a[] are to be copied.
while i < m
Copy a[i] to c[k], increment i and k
// b is exhausted. Remaining Elements of a[] are to be copied.
while j < n
Copy b[j] to c[k], increment j and k

Dr Somaraju Suvvari
21
NITP -- CS3401
Column major order and Row major order

In computing, row-major order and column-major order describe


methods for storing multidimensional arrays in linear memory
Row-major order
• In row-major storage, a multidimensional array in linear memory is accessed such that
rows are stored one after the other.

• It is the approach used by the C programming language as well as many other languages,
with the notable exceptions of Fortran and MATLAB.

• When using row-major order, the difference between addresses of array cells in increasing
rows is larger than addresses of cells in increasing columns.
Dr Somaraju Suvvari
22
NITP -- CS3401
Row major order
• For example,

• int A[3][4] = { {8,6,5,4}, {2,1,9,7}, {3, 6, 4, 2}};

• We would find the array laid-out in linear memory as: 8 6 5 4 2 1 9 7 3 6 4 2

Dr Somaraju Suvvari
23
NITP -- CS3401
Column major order
Column - major order:

Column-major order is a similar method of flattening arrays onto linear memory, but
the columns are listed in sequence.

• For example, consider this 3×4 array:

• int A[3][4] = {{8, 6, 5, 4}, {2, 1, 9, 7}, {3, 6, 4, 2}};

Dr Somaraju Suvvari
24
NITP -- CS3401
Address calculation in 1-D
• The address calculation of 1-D array is calculated in the following manner:
• Address of A [ K ] = B + W * ( K – LB ) // LB = 0
• Where,
• B = Base address
• W = Storage size of one element stored in the array (in byte)
• K = Subscript of element whose address is to be found.
• LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)
Consider the following example:
myList 0 1 2 3 4 5 6 7 8 9
int mylist[10];
7042 -- -- -- -- -- -- -- -- -- --

2028 7042 7046 7050 7054 7058 7062 7066 7070 7074 7078
Mylist[3] = 7042 + 4 * (3-0) = 7042+12 = 7054

Dr Somaraju Suvvari
25
NITP -- CS3401
Address calculation in 2-D
• In row major skip the i-Lr rows and move to the j-Lc position

• In row-major: a[i][j] = (B + W * (n * (i -Lr) + j - Lc) )

• In Column-major a[i][j] = (B + W * (m * (j - Lc) + i - Lr))

• Where,
• B = base address
• W = storage size of one element stored in the array (in byte).
• i and j are the row subscript and column subscript of the element whose address is to be found.
• m is the number of rows and n is the number of columns.
• Lr is the start row index of matrix
• Lc is the start column index of matrix

Dr Somaraju Suvvari
26
NITP -- CS3401
Example for Address calculation in 2-D (index starts with zero)
Consider the following row-major storage:

int myList[4][3] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}}

myList 0 1 2 3 4 5 6 7 8 9 10 11

7042 1 2 3 4 5 6 7 8 9 10 11 12
1024 7042 7046 7050 7054 7058 7062 7066 7070 7074 7078 7082 7086

Dr Somaraju Suvvari
27
NITP -- CS3401
Address calculation in 2-D (Example)
For example the address of element 6 i.e., myList[1][2] is
1. Skip the first row
myList 0 1 2 3 4 5 6 7 8 9 10 11

7042 1 2 3 4 5 6 7 8 9 10 11 12
1024 7042 7046 7050 7054 7058 7062 7066 7070 7074 7078 7082 7086

2. Move to the specific element in the present row


myList 0 1 2 3 4 5 6 7 8 9 10 11

7042 1 2 3 4 5 6 7 8 9 10 11 12
1024 7042 7046 7050 7054 7058 7062 7066 7070 7074 7078 7082 7086

&a[1][2] = 7042 + (4* ( 3 * (1-0) + (2-0)) = 7042 + 4 * 5 = 7062.

Dr Somaraju Suvvari
28
NITP -- CS3401
Address calculation in 3-D
• To find the address of a[i][j][k] in row major 3-D array (for example consider the array a[p][m][n])
• Skip the i-Lr blocks
• In ith block skip j-Lc rows
• In jth row of ith block move to k-Lk position

• In row-major: a[i][j][k] = (B + W * (i * m * n + (n * (j - Lr)) + k - Lc) )

• Where,
• B = base address
• W = storage size of one element stored in the array (in byte).
• j and k are the row subscript and column subscript of the element whose address is to be found.
• m is the number of rows, n is the number of columns and p is the number of such [m][n] 2-D arrays.
• Lr is the start row index of matrix
• Lc is the start column index of matrix

• Note: You workout on examples.


Dr Somaraju Suvvari
29
NITP -- CS3401
Dynamic Memory Allocation
• There are situations where we don’t know the size of the data structure, For example if
you want to store the marks of a student in a class, the class size is not fixed every year, it
changes year to year.

• Dynamic Memory Allocation can be defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.

• In C programming this can be achieved using the following functions:


• malloc()
• calloc()
• realloc()
• free()
Dr Somaraju Suvvari
30
NITP -- CS3401
Dynamic Memory Allocation
malloc() - “malloc” or “memory allocation” method in C is used to dynamically allocate a
single large block of memory with the specified size.

It returns a pointer of type void which can be cast into a pointer of any form.

It initializes each block with default garbage value.

Syntax
p = (cast- type *) malloc (size)

Example:

int *p = (int *)malloc(sizeof(int) * 10));

The above allocated a block of size equivalent to 10*sizeof(int);


Dr Somaraju Suvvari
31
NITP -- CS3401
Dynamic Memory Allocation
calloc() - “calloc” or “contiguous allocation” method in C is used to dynamically
allocate the specified number of blocks of memory of the specified type.

It initializes each block with a default value ‘0’.

Syntax

p = (cast- type *) calloc (n, size of element).

Example:

int *p = (int *)calloc(10, sizeof(int)));

The above allocates 10 blocks and size of each block is sizeof(int);


Dr Somaraju Suvvari
32
NITP -- CS3401
Dynamic Memory Allocation
• realloc() – “realloc” or “re-allocation” method in C is used to dynamically
change the memory allocation of a previously allocated memory.

• In other words, if the memory previously allocated with the help of malloc or
calloc is insufficient, realloc can be used to dynamically re-allocate memory.

• Re-allocation of memory maintains the already present value and new blocks will
be initialized with default garbage value.

• p = realloc(p, new-size);

Dr Somaraju Suvvari
33
NITP -- CS3401
Dynamic Memory Allocation
• free() - “free” method in C is used to dynamically de-allocate the memory.

• The memory allocated using functions malloc() and calloc() is not de-allocated on
their own.

• Hence the free() method is used, whenever the dynamic memory allocation takes
place. It helps to reduce wastage of memory by freeing it.

Syntax
free(p);

Dr Somaraju Suvvari
34
NITP -- CS3401
Sparse Matrix & Dense 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 otherwise it is dense matrix.

• 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.

Dr Somaraju Suvvari
35
NITP -- CS3401
Sparse Matrix & Dense Matrix
• Sparse Matrix Representations – To save the storage and to access the elements
efficiently we use the following TWO representations:

1. Triplet Representation (Array Representation)

2. Linked Representation (will be discussed later)

Dr Somaraju Suvvari
36
NITP -- CS3401
Sparse Matrix & Dense Matrix
• Triplet List Representation (Array 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.

Dr Somaraju Suvvari
37
NITP -- CS3401
Triplet Representation
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 following image...

Dr Somaraju Suvvari
38
NITP -- CS3401
Thank You

Dr Somaraju Suvvari NITP --


39
CS3401

You might also like