DSA - Arrays-1
DSA - Arrays-1
Strictly for internal circulation (within KIIT) and reference only. Not for outside circulation without permission
2 Arrays 2
Arrays, Two-Dimensional Array, Address
Calculation, Dynamically Allocated Arrays,
Abstract Data Types, Polynomials, Matrix Addition
and Multiplications, Sparse Matrix
Arrays
Array is a container which can hold fix number of items and these items should be of
same type. Following are important terms to understand the concepts of Array. Arrays
are of one-dimensional or multi-dimensional (i.e. 2 or more than 2)
Element − Each item stored in an array.
Index − Each location of an element in an array has a numerical index which is used
to identify the element.
One-Dimensional array is also called as linear array and stores the data in a single row or column.
Array of an element of an array say “A[i]” is calculated using the following formula:
Address of A [i] = BA + w * ( i – LB )
Where,
BA = Base Address
w = Storage Size of one element stored in the array (in byte)
i = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)
Example
Problem: Given the base address of an array B[1300…..1900] as 1020 and size of each
element is 2 bytes in the memory. Find the address of B[1700].
Solution:
The given values are: B = 1020, LB = 1300, W = 2, I = 1700
Address of A [i] = BA + w * ( i – LB )
= 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800 = 1820
Note : C supports row major order and Fortran supports column major order
School of Computer Engineering
Row major & Column order Address Calculation
7
Row-Major Order: The address of a location in Row Major System is calculated as:
Address of A [i][j] = BA + w * [ n * ( i – Lr ) + ( j – Lc ) ]
Column-Major Order: The address of a location in Column Major System is
calculated as:
Address of A [i][j] = BA + w * [( i – Lr ) + m * ( j – Lc )]
Where:
BA = Base Address
i = Row subscript of element whose address is to be found
j = Column subscript of element whose address is to be found
w = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
m = Number of row of the given matrix
n = Number of column of the given matrix
Important: Usually number of rows and columns of a matrix are given (like A[20][30] or
A[40][60] ) but if it is given as A[Lr- – – – – Ur, Lc- – – – – Uc]. In this case number of rows
and columns are calculated using the following methods:
Column-Major :
The given values are: BA = 1500, w = 1 byte, i = 15, j = 20, Lr = -15, Lc = 15, m = 26
Address of A [ i ][ j ] = BA + w * [( i – Lr ) + m * ( j – Lc )]
= 1500 + 1* [26 * (15 – (-15))) + (20 – 15)]
= 1500 + 1 * [30 + 26 * 5] = 1500 + 1 * [160] = 1660
Row-Major:
The given values are: B = 1500, W = 1 byte, i = 15, j = 20, Lr = -15, Lc = 15, N = 26
Address of A [ i ][ j ] = BA + w * [ n * ( i – Lr ) + ( j – Lc ) ]
= 1500 + 1* [26 * (15 – (-15))) + (20 – 15)]
= 1500 + 1 * [26 * 30 + 5] = 1500 + 1 * [780 + 5] = 1500 + 785 = 2285
The exact size of array is unknown until the compile time i.e. time when a compiler compiles code
written in a programming language into a executable form. The size of array you have declared
initially can be sometimes insufficient and sometimes more than required.
What?
The process of allocating memory during program execution is called dynamic memory allocation. It
also allows a program to obtain more memory space, while running or to release space when no
space is required.
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;
An abstract data type (ADT) is a mathematical model for data types where a data
type is defined by its behavior (semantics) from the point of view of a user of the
data, specifically in terms of possible values, possible operations on data of this
type, and the behavior of these operations. When considering Array ADT we are
more concerned with the operations that can be performed on array.
Insertion Deletion
Insert operation is to insert one or more data elements Deletion refers to removing an existing element from
into an array. Based on the requirement, new element the array and re-organizing all elements of an array.
can be added at the beginning or end or any given
position of array. Consider LA is a linear array with N elements and K is
a positive integer such that K<=N. Below is the
Let LA is a Linear Array (unordered) with N elements and algorithm to delete an element available at the Kth
K is a positive integer such that K<=N. Below is the position of LA. Procedure - DELETE(LA, N, K)
algorithm where ITEM is inserted into the Kth position of
LA. Procedure – INSERT(LA, N, K, ITEM) 1. Start
2. Set J = K
1. Start
3. Repeat step 4 while J < N
2. Set J=N
4. Set LA[J] = LA[J+1] /* Move the element upward*/
3. Set N = N+1 /* Increase the array length by 1*/
5. Set N = N-1 /* Reduce the array length by 1 */
4. Repeat steps 5 and 6 while J >= K
6. Stop
5. Set LA[J+1] = LA[J] /* Move the element downward*/
6. Set J = J-1 /* Decrease counter*/
7. Set LA[K] = ITEM
8. Stop
Search Updation
You can perform a search for array element Update operation refers to updating an existing
based on its value or position. element from the array at a given position.
Consider LA is a linear array with N elements. Consider LA is a linear array with N elements
Below is the algorithm to find an element with a and K is a positive integer such that K<=N.
value of ITEM using sequential search. Below is the algorithm to update an ITEM
Procedure - SEARCH(LA, N, ITEM) available at the Kth position of LA. Procedure -
UPDATE(LA, N, K, ITEM)
1. Start
2. Set J=1 and LOC = 0 1. Start
3. Repeat steps 4 and 5 while J < N
2. Set LA[K] = ITEM
4. IF (LA[J] = ITEM) THEN LOC = J AND GOTO STEP 6
3. Stop
5. Set J = J +1
6. IF (LOC > 0) PRINT J, ITEM ELSE PRINT ‘Item not
found’
7. Stop
Traversal Sorting
Traversal operation refers to printing the Sorting operation refers to arranging the elements
contents of each element or to count the number either in ascending or descending way.
of elements with a given property
Consider LA is a linear array with N elements. Below
Consider LA is a linear array with N elements. is the Bubble Sort algorithm to sort the elements
in ascending order. Procedure - SORT(LA, N)
Below is the algorithm to print each element.
Procedure - TRAVERSE(LA, N)
1. Start
2. Set I = 0
1. Start 3. Set J = 0
2. Set J=1 4. Repeat steps 5,6,7 and 8 while I < N
3. Repeat steps 4 and 5 while J < N 5. J = I + 1
4. PRINT LA[J] 6. Repeat steps 7 and 8 while j <N
5. Set J = J +1 7. IF LA[I] is > LA[J] THEN
8. Set TEMP = LA[I]; LA[I] = LA[J]; LA[J] = TEMP;
6. Stop
9. Stop
Merging Reversing
Merging refers to combining two sorted arrays Reversing refers to reversing the elements in the
into one sorted array. It involves 2 steps – array by swapping the elements. Swapping should
Sorting the arrays that are to be merged be done only half times of the array size
Adding the sorted elements of both arrays to
a new array in sorted order Consider LA is a linear array with N elements.
Write the algorithm to reverse the elements and
print each element of LA
LA1 is a linear array with N elements, LA2 is a
liner array with M elements and LA3 is a liner
1. Start
array with M+N elements. Write the algorithm
/* Assignment 2 */
to sort LA1 & LA2 and merge LA1 & LA2 into 2. Stop
LA3 & sort LA3 and print each element of LA3
1. Start
/* Assignment1 */
2. Stop
Assignment 3 Assignment 4
LA is a linear array with N elements. Write the LA is a linear array with N elements. Write the
algorithm to finds the largest number and algorithm to copy the elements from LA to a
counts the occurrence of the largest number new array LB
1. Start 1. Start
/* Assignment 3 steps */ /* Assignment 4 steps*/
2. Stop 2. Stop
Assignment 5 Assignment 6
LA is a linear array with N elements. Write the LA is a linear sorted array with N elements.
algorithm to transpose the array Write the algorithm to insert ITEM to the array
1. Start 1. Start
/* Assignment 5 steps */ /* Assignment 6 steps */
2. Stop 2. Stop
Polynomial is an expression constructed from one or more variables and constants, using only the
operations of addition, subtraction, multiplication, and constant positive whole number exponents.
A term is made up of coefficient and exponent.
Examples –
Polynomial with single variable P(X) = 4X3 + 6X2+7X+9 (4,6,7 are coefficient & 3,2 are exponent)
Polynomial with 2 variables P(X, Y) = X3 - 2XY +1 (2 is coefficient & 3 is exponent)
Definition–
Polynomial with single variable P(X) =
A polynomial thus may be represented using arrays. Array representation assumes that the exponents of the
given expression are arranged from 0 to the highest value (degree), which is represented by the subscript of the
array beginning with 0. The coefficients of the respective exponent are placed at an appropriate index in the
array. Considering single variable polynomial expression, array representation is
Consider LA is a linear array with N elements and LB is a linear array with M elements.
Below is the algorithm for polynomial addition
1. Start
2. Set j= maximum of M or N
3. Create a sum array LSum[] of size J
4. IF (N is Greater Than or Equal to M) Then
Copy LA[] to LSum[]
else
Copy LB[] to LSum[]
5. IF (N is Greater Than M) then
Traverse array LB[] and LSum[i] = LSum[i] + LB[i]
else
Traverse array LA[] and LSum[i] = LSum[i] + LA[i] while i < j
6. PRINT LSum
7. Stop
Given two polynomials represented by two arrays, below is the illustration of the
multiplication of the given two polynomials.
Example :
Input: A[] = {5, 0, 10, 6} and B[] = {1, 2, 4}
Output: prod[] = {5, 10, 30, 26, 52, 24}
The first input array represents "5 + 0x1 + 10x2 + 6x3"
The second array represents "1 + 2x1 + 4x2"
And output is "5 + 10x1 + 30x2 + 26x3 + 52x4 + 24x5”
5 0 10 6 Coefficents 1 2 4 0 Coefficents
A B
0 1 2 3 Exponents 0 2 2 3 Exponents
AXB
5 10 30 26 52 24 Coefficents
Prod
0 2 2 3 4 5 Exponents
Algorithm:
prod[0.. m+n-1] Multiply (A[0..m-1], B[0..n-1])
1. Start
2. Create a product array prod[] of size m+n-1.
3. Initialize all entries in prod[] as 0.
4. Travers array A[] and do following for every element A[i]
Traverse array B[] and do following for every element B[j]
prod[i+j] = prod[i+j] + A[i] * B[j]
5. return prod[]
6. Stop
Class Exercise
Suppose A and B are two matrices and their order are respectively m x n and p x q. i, j and k are counters. And C to
store result.
Step 1: Start.
Step 2: Read: m, n, p and q
Step 3: Read: Inputs for Matrices A[1:m, 1:n] and B[1:p, 1:q].
Step 4: If n ≠ p then:
Print: Multiplication is not possible.
Else:
Repeat for i := 1 to m by 1:
Repeat for j := 1 to q by 1:
C[i, j] := 0 [Initializing]
Repeat k := 1 to n by 1
C[i, j] := C[i, j] + A[i, k] x B[k, j]
[End of for loop]
[End of for loop]
[End of for loop]
[End of If structure]
Step 5: Print: C[1:m, 1:q]
Step 6: Stop
Assignment 7 Assignment 8
Write an algorithm to add the originial sparse Write an algorithm to multiply two sparse
matrix with the transpose of the same matrix. matrices.
1. Start 1. Start
/* Assignment 7 steps */ /* Assignment 8 steps*/
2. Stop 2. Stop
Assignment 9 Assignment 10
9.1. Design an efficient data structure to store Design an algorithm to convert a lower
data for lower and upper triangular matrix. triangular matrix to upper triangular matrix.
1. Start
9.2. Design an efficient data structure to store /* Assignment 10 steps */
data for tri-diagonal matrix. 2. Stop
11. Write an algorithm that takes as input the size of the array and the elements
in the array and a particular index and prints the element at that index.
12. Write down the algorithm to sort elements by their frequency.
13. Write down the algorithm to add two polynomials of single variable.
14. Write down the algorithm to multiply two polynomials of two variables.
15. A program P reads in 500 random integers in the range [0..100] presenting
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?
16. Write down the algorithm to delete all the vowels in a character array.
17. Write down the algorithm to print all the elements below the minor diagonal
in a 2-D array.
18. Write an algorithm to find a triplet that sum to a given value
19. Given an array arr, write an algorithm to find the maximum j – i such that
arr[j] > arr[i]
20. Write an algorithm to replace every element in the array with the next
greatest element present in the same array.
School of Computer Engineering
33
8. Given an unsorted array, Write down the algorithm to find the minimum difference
between any pair in given array.
Input : {1, 5, 3, 19, 18, 25};
Output : 1 as Minimum difference is between 18 and 19
9. Given an array of integers, Write down the algorithm to count number of sub-arrays
(of size more than one) that are strictly increasing.
Input: arr[] = {1, 2, 3, 4}
Output: 6 as there are 6 sub-arrays {1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {2, 3}, {2, 3, 4} and {3,
4}
10. Given an array of integers. All numbers occur twice except one number which occurs
once. Write down the algorithm to find the number in O(n) time & constant extra
space.
Input: ar[] = {7, 3, 5, 4, 5, 3, 4};
Output: 7
11. Given a 2D array of size m X n, containing either 1 or 0. As we traverse through,
where ever we encounter 0, we need to convert the whole corresponding row and
column to 0, where the original value may or may not be 0. Devise an algorithm to
solve the problem minimizing the time and space complexity.
School of Computer Engineering
Supplementary Reading
36
https://www.tutorialspoint.com/data_structures_algorithms/array_data_str
ucture.htm
http://www.geeksforgeeks.org/array-data-structure/
https://www.hackerrank.com/domains/data-structures/arrays
http://javarevisited.blogspot.in/2015/06/top-20-array-interview-
questions-and-answers.html#axzz4myAupUvT
https://www.youtube.com/playlist?list=PLqM7alHXFySEQDk2MDfbwEdjd2
svVJH9p
What is Array?
Array is a collection of variables of same data type that share a common
name.
Array is an ordered set which consist of fixed number of elements.
Array is an example of linier data structure.
In array memory is allocated sequentially so it is also known as
sequential list.
1-D Array address calculation
Address of A[i] = BA + w * (i) where BA is the base address, w is the word
length and i is the index
Row-Major order: Row-Major Order is a method of representing multi
dimension array in sequential memory. In this method elements of an array
are arranged sequentially row by row. Thus elements of first row occupies
first set of memory locations reserved for the array, elements of second row
occupies the next set of memory and so on.
Address of A [ i ][ j ] = BA + w * [ n * ( i – Lr ) + ( j – Lc ) ]
School of Computer Engineering
FAQ
38
Ragged 2 D Arrays:
char *font[] = {
(char []) {65,8,12,1,0,0x18, 0x3C, 0x66, 0xC3, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF},
(char []) {39,2,3,4,9,0xC0,0xC0, 0xC0},
(char []) {46,2,2,4,0,0xC0,0xC0}};