Array and Algorithms
Array and Algorithms
INTRODUCTION
One of the simplest and most common type of data is the list. By definition, a list is an ordered set
consisting of a variable number of elements to which additions and deletions mat be made, if
applicable. A list which displays the relationship of physical adjacency is called a linear list.
A linear list is a finite sequence of simple data items or records. Each of the elements in a list
forming a sequence (except for the first and the last elements) has a single successor and a single
predecessor. Some examples of linear lists are:
Saturday, Sunday)
When the elements of a list are arranged in a sequential fashion, a table is obtained. If the
telephone directory of an enterprise is held in computer memory, it may be stored in a table similar
to the one in the figure below.
If we consider a linear list more abstractly, we say that it is either empty or it can be written as:
There are variety of operations that may be performed on linear lists. These include:
DEFINITION
The most common way of representing a linear list is through the use of an array. It is appropriate
that we begin our study of data structures with the array since the array is often the only means
provided in a programming language for structuring data. An array may be defined as an ordered
collection of data items of the same type referred to collectively by a single name (the name of the
array). Individual data items in an array are called elements. Array elements are ordered according
to subscripts (an integer from 1 to n); for this reason they are sometimes called subscripted
variables. An array elements is indicated by the array name followed by its subscripts, which
appear inside a pair of square brackets.
Dimensionality of an Array
The number of subscripts of an array determines its dimensionality. An array with only one
subscripts, for example Array1 [j], is called a one-dimensional array. In the same manner, an
array with two subscripts, as in Array1 [i,j], is called two-dimensional array. Arrays with more
than two subscripts are called multi-dimensional arrays.
ONE-DIMENSIONAL ARRAYS
We have defined one-dimensional arrays as an array with only one subscript. Therefore, if Array1 is
a one-dimensional array with 10 elements, these elements may be referenced as:
All operations which may be performed on linear lists may be also be done using arrays.
Retrieving the ith Element of a One-Dimensional Array
Retrieving the ith element of an array simply involves the specification of the array name along with
the subscript of the desired element. For example, let us assume that array Arr1 has 10 elements.
The following statement retrieves the 6th element of Arr1:
The following pseudocode illustrates the process of reading the elements of an array from left to
right. The algorithm Read_Arr accepts the following parameters as inputs:
Read_Arr (Arr1,N)
{
Set Ctr to 1
While (Ctr <= N)
{
Print Arr1[Ctr]
Increment Ctr
}
}
We will now try to simulate the algorithm Read_Arr by assuming that the array Arr1 contains the
following elements:
Arr1[1] Dasher
Arr1[2] Dancer
Arr1[3] Prancer
Arr1[4] Comet
Arr1[5] Cupid
Arr1[6] Donner
Arr1[7] Blitzen
Arr1[8] Vixen
Figure 2-3 One-Dimensional Array with 8 Elements
Ctr = 1
Summary of Output
Dasher
Dancer
Prancer
Comet
Cupid
Donner
Blitzen
Vixen
Storing a New Value into an Element of a One-Dimensional Array
Storing a value into an element of an array overwrites whatever value the element previously
contained. The process of assigning a value to an array element simply requires referencing the
element’s position and setting its value. Using an array Arr1 which has a size of 10, the following
statement sets the 4th element to “Apples”:
When storing values in an array, it is always important to note that the subscript used to specify the
element`s position should never exceed the size of the array. Therefore, if the size of an array is n:
The elements of an array cannot be “physically” deleted. This is because the size of an array, once
defined, always remains the same. Instead, array elements may be set to a specific value, for
example, blank, to signify deletion. The following statement “deletes” the 8 th element in an array
called Arr1 which has size of 10 elements:
Using an array called Arr1 with a size of N, the following pseudocode illustrates the procedure for
sorting an array in ascending order. This algorithm makes use of three other variables:
Let us assume that Arr1 is an array of size 4 containing the following elements:
Arr[1] Raphaelo
Arr[2] Michaelangelo
Arr[3] Leonardo
Arr[4] Donatello
Let us now sort the contents of Arr1 using the pseudocode Sort_Arr.
Ctr1 = 1
Outer While Loop: 1st Iteration
Ctr2 = 2
Arr[1] Michaelangelo
Arr[2] Raphaelo
Arr[3] Leonardo
Arr[4] Donatello
Arr[1] Leonardo
Arr[2] Raphaelo
Arr[3] Michaelangelo
Arr[4] Donatello
Arr[1] Donatello
Arr[2] Raphaelo
Arr[3] Michaelangelo
Arr[4] Leonardo
Ctr1 = 2
Outer While Loop: 2nd Iteration
Ctr2 = 3
Arr[1] Donatello
Arr[2] Michaelangelo
Arr[3] Raphaelo
Arr[4] Leonardo
Arr[1] Donatello
Arr[2] Leonardo
Arr[3] Raphaelo
Arr[4] Michaelangelo
Ctr1 = 3
Outer While Loop: 3rd Iteration
Ctr2 = 4
To illustrate the procedure for copying an array into another array, we will use the two arrays: Arr1
and Arr2. Arr1 will represent the source array; it has a size of N. Arr2 will represent the target array.
Since we are copying the entire Arr1 into Arr2, Arr2 also has a size of N. The algorithm Copy_Arr
uses a variable named Ctr as a subscript.
Copy_Arr (Arr1,N)
{
Set Ctr to 1
While (Ctr <= N)
{
Set Arr2[Ctr] to Arr1[Ctr]
Increment Ctr
}
}
To simulate the pseudocode Copy_Arr (), we will use the array in figure 2-3 where N = 8.
Ctr = 1
While Loop: 1st Iteration While Loop: 5th Iteration
Arr2[1] = “Dasher” Arr2[5] = “Cupid”
Ctr = 2 Ctr = 6
Summary of Output:
Arr[1] Dasher
Arr[2] Dancer
Arr[3] Prancer
Arr[4] Comet
Arr[5] Cupid
Arr[6] Donner
Arr[7] Blitzen
Arr[8] Vixen
Merging Two One-Dimensional Arrays
Given three arrays: Arr1, Arr2 and Arr3, where Arr1 and Arr2 are sorted in ascending order, we can
merge Arr1 and Arr2 into the array Arr3 such that the contents of Arr3 are also sorted in ascending
order: In order to perform this operation, Arr3 would have to be large enough to contain all
elements.
The algorithm Merge_Arr accepts as inputs the arrays Arr1 and Arr2 along with the following
information.
The algorithm also uses three variables, Ctr1, Ctr2, and Ctr3, as subscripts to the three arrays.
Merge_Arr (Arr1, Arr2, Arr3,N1, N2, N3)
{
Set Ctr1 to 1
Set Ctr2 to 1
Set Ctr3 to 1
While ((Ctr1 <= N1) OR (Ctr2 <= N2) or (Ctr3 <= N3))
{
If (Ctr1 > N1) then /* First Condition */
{
Copy_from_Arr2()
}
Else
{
Figure 2-7 Algorithm
If (Ctr2 > N2) thenFor Merging Two One-Dimensional
/* Second Arrays
Condition */
{
Copy_from_Arr1()
}
Let us now simulate the algorithm Merge_Arr by assuming the following elements:
Else
1. Arr1 is a one-dimensional
{ array of size 4 containing the following elements:
If (Arr1[Ctr1] < Arr2[Ctr2]) then /* Third Condition */
{ Arr1[1] Dopey
Copy_from_Arr1() Arr2[2] Grummpy
} Arr3[3] Happy
Else Arr4[4] Sleepy /* Fourth Condition */
{
Copy_from_Arr2()
Figure
} 2-8 One-Dimensional Array With 4 Elements
}
}
Increment Ctr3
2. Arr2 is one-dimensional array of size 3 containing the following elements:
}
}
Arr2[1] Bashful
Copy_from_Arr1() Arr2[2] Doc
{ Arr2[3] Sneezy
Set Arr3[Ctr3] to Arr1[Ctr1]
Increment Ctr1
} Figure 2-9 One-Dimensional Array With 3 Elements
Copy_from_Arr2()
3. Arr3 is an
{ array of size 7 containing blanks.
Set Arr3[Ctr3] to Arr2[Ctr2]
Increment Ctr2
Ctr1 =}1
Ctr2 = 1
Ctr3 = 1
Arr3[1] Bashful
Arr3[2] Doc
Arr3[3] Dopey
Arr3[4] Grumpy
Arr3[5] Happy
Arr3[6] Sleepy
Arr3[7] Sneezy
The pseudocode for spilitting an array into two or more smaller arrays is better explained
using an example. Let us assume that Arr1 is an array of size N1, where each element is a
record containing the following fields:
1. Student Name
2. Student Number
Let us further suppose that the field Student Number has the format:
The pseudocode N1) will divide Arr1 into the following three arrays:
Split_Arr()
Split_Arr (Arr1,
{
1. Arr90 An array which contain all records whose Student Number field has YY = 90
2. Arr91Set Ctr1An to array
1 which contain all records whose Student Number field has YY = 91
3. Arr92Set Ctr90 to 1
An array which contain all records whose Student Number field has YY = 92
Set Ctr91 to 1
After dividing Arr1 into Arr90,
Set Ctr92 to 1 Arr91, and Arr92, Split_Arr() will print the names of the students
under each newWhile
array(Ctr1
along<= withN1)
appropriate headings.
{
Switch (YY of Arr1.Studenum[Ctr1])
{
Case (“90”)
{
Set Arr90[Ctr90] to Arr1[Ctr1]
Increment Ctr90
}
Case (“91”)
{
Set Arr90[Ctr91] to Arr1[Ctr1]
Increment Ctr91
}
Default
{
Set Arr92[Ctr92] to Arr1[Ctr1]
Increment Ctr92
}
}
Increment Ctr1
}
If (Ctr90 > 1) then /*First IF Statement*/
{
Print_Arr90 (Arr90, Ctr90)
}
If (Ctr91 > 1) then /*Second IF Statement*/
{
Print_Arr91 (Arr91,Ctr91)
}
If (Ctr92 > 1) then /*Third IF Statement*/
{
Print_Arr92 (Arr92,Ctr92)
}
}
Print_Arr90 ()
{
Print “Students with Student Numbers beginning with `90`:”
Print “ “
Set l to 1
While (l < Ctr90)
{
Print Arr90.StudName[l]
Increment l
}
Print “ “
}
Print_Arr91 ()
{
Print “Students with Student Numbers beginning with `91`:”
Print “ “
Set l to 1
While (l < Ctr91)
{
Print Arr91.StudName[l]
Increment l
}
Print “ “
}
Print_Arr92 ()
{
Print “Students with Student Numbers beginning with `92`:”
Print “ “
Set l to 1
While (l < Ctr92)
{
Print Arr92.StudName[l]
Increment l
}
Print “ “
}
Ctr1 = 1
Ctr90 = 1
Ctr91 = 1
Ctr92 = 1
/*First IF Statement*/
/*Print_Arr90()*/
Print “Students with Student Numbers beginning with `90`:”
Print “ “
l=1
Print “ “
/*Second IF Statement*/
/*Print_Arr91()*/
Print “Students with Student Numbers beginning with `91`:”
Print “ “
l=1
While Loop: 1st Iteration
Print “Donald Duck”
l=2
While Loop: 2nd Iteration
Print “Daisy Duck”
l=3
Print “ “
/*Third IF Statement*/
/*Print_Arr92()*/
Print “Students with Student Numbers beginning with `92`:”
Print “ “
l=1
While Loop: 1st Iteration
Print “Mickey Mouse”
l=2
Print “ “
Summary of Data Printed
Hewey Duck
Dewey Duck
Lewey Duck
TWO-DIMENSIONAL ARRAYS
A two-dimensional array is an array with two subscripts. The first subscript is called row and the
second subscript is referred to as the column. Because of this property, two-dimensional arrays are
often called tables or matrices. To reference an element of two-dimensional array, both the row
number and column number of the desired element must be specified. For example, the statement
Arr1[2,3] accesses the element in the second row, third column of the two-dimensional array Arr1.
The figure below shows an example of a two-dimensional array called Arr1 containing 3 rows and 4
columns.
The following is a list of the basic that can be performed on two-dimensional arrays. In the list, m
represents the number of rows in the array and n the number of columns.
Merging and splitting may also be performed on two-dimensional arrays. However, these are no
longer basic operations because they require a close study of application for which they will be used.
Additionally, there is little difference between the pseudocodes of one-dimensional and two-
dimensional arrays for the first three operations, therefore, we will no longer elaborate on them.
With regard to copying an array, a number of changes will have to be done on the original code so
we will elaborate on this operation. We will also look into some applications of two-dimensional
arrays.
To illustrate the procedure for copying a two-dimensional array into another array, we will use the
two arrays: Arr1nand Arr2. Arr1 will be our source array having m. rows and n columns. Arr2 will
represent the target array. Since we are copying all elements in Arr1, Arr2 also has the size [m, n].
The algorithm Copy_2Dim accepts as input the source array, Arr1, along with its dimensions: m, and
n. additionally, it uses two variables, I and J, as subscripts.
Copy_2Dim (Arr1,m,n)
{
Set I to 1
While (I ≤ m)
{
Set J to 1
While (J ≤ n)
{
Set Arr2[I,J] to Arr1[I,J]
Increment J
}
Increment I
}
}
Figure 2-13 Algorithm For Copying A Two-Dimensional Array By Row
To simulate the pseudocode Copy_2Dim (), we will use the two-dimensional array, Arr1, which in
figure 2-12.
I=1
Outer While Loop: 1st Iteration
J=1
Inner
Inner While
While Loop:
Loop: 31st Iteration
rd
Arr2[1,3]
Arr2[1,1] =
= 31
JJ =
= 42
InnerWhile
Inner WhileLoop:
Loop:2nd
4thIteration
Iteration
Arr2[1,4] = 4
Arr2[1,2] = 2
JJ =
= 53
I=2
Outer While Loop: 2nd Iteration
J=1
Inner While Loop: 1st Iteration
Arr2[2,1] = 2
J=2
Inner While Loop: 2nd Iteration
Arr2[2,2] = 4
J=3
Inner While Loop: 3rd Iteration
Arr2[2,3] = 6
J=4
Inner While Loop: 4th Iteration
Arr2[2,4] = 8
J=5
I=3
Outer While Loop: 2nd Iteration
J=1
Inner While Loop: 1st Iteration
Arr2[3,1] = 3
J=2
Inner While Loop: 2nd Iteration
Arr2[3,2] = 6
J=3
In copying arrays, the number of loops equals the dimensionality of the array. In our example, Arr1
is a two-dimensional array, consequently procedure Copy_2Dim contains two While loops. If our
array had three dimensions then the pseudocode would have had three While loops. Additionally,
our algorithm copied Arr1 into Arr2 by row, meaning Arr1[1,1] was copied first then Arr1[1,2]
followed by Arr1[1,3], and so on. It is also possible to copy a two-dimensional array by column. The
following pseudocode shows how this is done. If you will notice the algorithm is basically similar to
Copy_2Dim.
Copy_2Dim_Col (Arr1,m,n)
{
Set J to 1
While (J ≤ n)
{
Set I to 1
While (I ≤ m)
{
Set Arr2[I,J] to Arr1[I,J]
Increment I
}
Increment J
}
}
By processing the arrays rows in the inner loop, our procedure effectively copies Arr1 into Arr2 by
column.
Matrices
The following sample applications of two-dimensional arrays make use of matrices. A matrix is a
mathematical object which arises in many physical problems. As computer scientists, we are
interested in studying ways to represent matrices so that the operations to be performed on them
can be carried out efficiently. A general matrix consists of m rows and n columns. The following
tables are examples of matrices.
The first matrix has five rows and three columns, the second, six rows and six columns. In general,
we write m x n (read m by n) to designate a matrix with m rows and n columns. Such a matrix has a
total of mn elements. Whenever m is equal to n, we call the matrix a square.
Magic Square
A magic square is an n x n matrix of the integers 1 to n2 such that the sum of every row, column
and diagonal is the same. For example, the figure below shows the magic square for a 3 x 3 matrix
where the common sum is 15.
Sum of Diagonals: 1) 6 + 5 + 4 = 15
2) 8 + 5 + 2 = 15
When n is odd, H. Coxeter has given a simple rule for generating a magic square:
“Start with 1 in the middle of the top row; then go up and left assigning numbers in
increasing order to empty squares; if you fall off the square imagine the same square as
tilting the plane and continue; if a square is occupied move down instead and continue.”
Using this rule, let us now study the pseudocode for creating an n x n magic square where n is odd
and n is greater than 1.
Magic (n)
{
Check_n()
Initialize_Square()
Set I to 1
Set J to (((n-1) / 2) + 1) /* Set J to the middle of the first row */
Set Square[I,J] to 1 /* Set middle of first row to 1 */
Set Next_Value to 2
Iniatialize_Square()
/* Sets all elements of Square to 0 */
{
Set I to 1
While (I ≤ n)
{
Set J to 1
While (J ≤ n)
{
Set Square[I,J] to 0
Increment J
}
Increment I
}
}
/* Check_n() */
/* Initialize_Square() */
I=1
Outer While Lopp: 1st Iteration
J=1
Inner While Loop: 1st Iteration
Square[1,1] = 0
J=2
Inner While Loop: 2ndIteration
Square[1,2] = 0
J=3
Inner While Loop: 3rdIteration
Square[1,3] = 0
J=4
I=2
Outer While Lopp: 2ndIteration
J=1
Inner While Loop: 1st Iteration
Square[2,1] = 0
J=2
Inner While Loop: 2ndIteration
Square[2,2] = 0
J=3
Inner While Loop: 3rdIteration
Square[2,3] = 0
J=4
I=3
Outer While Lopp: 3rdIteration
J=1
Inner While Loop: 1st Iteration
Square[3,1] = 0
J=2
Inner While Loop: 2ndIteration
Square[3,2] = 0
J=3
Inner While Loop: 3rdIteration
Square[3,3] = 0
J=4
I=4
I=1
J=2
Square[1,2] = 1
Contents of Square after Statements
Next_Value = 2
Main While Loop: 1st Iteration
/* First If */
Temp_I = 3
/* Second Else */
Temp_J = 1
/* Third Else */
Next_Value
I=3 =3
J= 1
Contents of Square after Statements
Square[3,1] = 2
Sparse Matrices
Let us assume that we have a 6 x 6 matrix called Arr1 which contains the following elements:
If we look at our matrix, we see that it has many zero (0) entries. Such a matrix is called sparse.
There is no precise definition of when a matrix is sparse and when it is not but it is a concept which
can be intuitively recognized. In the matrix Arr1, only 12 out of 36 elements are nonzero and that is
sparse! If we consider that each element of an array occupies a portion of computer memory, we
can deduce that a lot of valuable computer space is wasted by sparse matrices. One may think that
the space occupied by 36 elements is negligible. But what happens if Arr1 had 1000 rows and 1000
columns (1000 x 1000) and at the same time it was sparse! Having to store all one million elements
in the computer when only a small subset is needed is senseless and would greatly affect the
efficiency of the program processing them.
A sparse matrix would require us to consider an alternate form of representation that would store
only the nonzero elements. This comes about because in practice many of the matrices we want to
deal with are large life our 1000 x 1000 example, but at the same time they are sparse. In figure 2-
18, 12 out of 36 elements of Arr1 are nonzero. We can therefore represent Arr1 as the following
array which we will call ArrNew.
The elements [1,1] and [1,2] of ArrNew contain the number of rows and columns in the sparse
matrix Arr1. The location [1,3] contains the number of nonzero elements in Arr1. Hence in ArrNew:
Each succeeding row in ArrNew provides information about a nonzero element in Arr1. Column 1
contains the number of the row where the nonzero element is located;and column 2 contains the
number of the column where the nonzero element is located. Lastly, column 3 contains the value of
the nonzero element itself. For example, in ArrNew, row 5 contains the information
In assigning values to ArrNew, the nonzero elements of Arr1 are referenced first by row and then by
column. This means that the row in ArrNew describing the nonzero element at Arr1[3,3] is filled
before the row describing the nonzero element at Arr1[4,1]. Additionally, the row in ArrNew
describing the nonzero element at Arr1[5,2] is created before the row describing the nonzero
element at Arr1[5,4]. Essentially, a table representing a sparse matrix will always have 3 columns
and k + 1 rows, where k is equal to the number of nonzero elements in the matrix.
The following procedure creates the array ArrNew which will represent the nonzero elements in the
sparse matrix Arr1. The procedure requires the following information as input:
Sparse (Arr1,m,n)
{
Set Num to 0
Count_Nonzero()
Definen ArrNew with size [(Num+1) x 3]
Set ArrNew[1,1] to m
SetSet ArrNew[1,2]
ArrNew[1,3] to n
to Num
Set Row to 1
Set I to 2
While (Row ≤ m)
{
Set Col to 1
While (Col ≤ n)
{
If (Arr1[Row,Col] is NOT Zero) then
{
Set ArrNew[I,1] to Row
Set ArrNew[I,2] to Col
Set ArrNew[I,3] to Arr1[Row,Col]
Increment I
}
Increment Col
}
Increment Row
}
}
Count_Nonzero()
/* Determines the number of nonzero elements in Arr1 */
{
Set Row to 1
While (Row ≤ m)
{
Set Col to 1
While (Col ≤ n)
{
If (Arr1[Row,Col] is NOT zero) then
{
Increment Num
}
Increment Col
}
Figure 2-21 Algorithm For Representing Sparse Matrices
Let us analyze the pseudocode Sparse using the matrix in the figure below which we will call Arr1
Row = 2
Outer While Loop: 2ndIteration
Col = 1
Inner While Loop: 1st Iteration
Col = 2
Inner While Loop: 2ndIteration
/* IF Statement: Arr[2,2] not Zero */
Num = 2
Col = 3
Inner While Loop: 3rdIteration
Col = 4
Row = 3
Outer While Loop: 3rdIteration
Col = 1
Inner While Loop: 1st Iteration
Col = 2
Inner While Loop: 2ndIteration
Col = 3
rd
Contents of ArrNew after Iteration
Row = 2
Outer While Loop: 3rd Iteration
Col = 1
Inner While Loop: 1st Iteration
Col = 2
Inner While Loop: 2nd Iteration
Col = 3
Inner While Loop: 3rd Iteration
Col = 4
Row = 4
Outer While Loop: 4th Iteration
Col = 1
Inner While Loop: 1st Iteration
Col = 2
Inner While Loop: 2nd Iteration
/* IF Statement: Arr1[2,2] is NOT Zero */
ArrNew[4,1] = 4
ArrNew[4,2] = 2
ArrNew[4,3] = 8
I=5
Col = 3
Final Contents of ArrNew
Transpose
One of the operations that may be performed on matrices is to computer for the transpose of a
matrix. The transpose is a “copy” of a particular matrix wherein the elements in the [i,j] position are
transferred to the [j,i] position. In other words, we are interchanging the rows and the columns. The
elements in the diagonal will always remain in the same position since i = j. If the original matrix
has a dimension of m x n, the resulting transpose of the matrix will have a dimension of n x m. To
illustrate this concept, let us consider the figure below which represents a matrix called Arr1.
The pseudocode in figure 2-25 computes for the transpose of matrix. It accepts as input the
following information:
Transpose (Arr1,m,n)
{
Define Arr2 with size [n x m]
Set I to 1
While (I ≤ m)
{
Set J to 1
While (J ≤ n)
{
Set Arr2[J,I] to Arr1[I,J]
Increment J
}
Increment I
}
}
Let us now use the array Arr1 presented in figure 2-23 to simulate the algorithm.
REPRESENTATION OF ARRAYS
Arrays are usually represented as contiguous memory locations that are sequentially allocated. This
means that for an array with n elements, where each element is one memory word (2 bytes) long, n
consecutive words are allocated in memory. Since the size of an array is always fixed the amount of
memory required by an array is also fixed. The following figure illustrates how an array Arr1 with
sizen may be provided storage in memory. For the purpose of this discussion, let us assume that
each element in Arr1 is k words long.
Memory
Start Arr1[1]
Start denotes the location of this first word of the element Arr1[i]. The formula
Start + k (i – 1)
May be applied to determine the starting address of the ith element of Arr1. Consider the following
figure representing the memory allocation for array Arr2 which has a size of n and whose elements
are each 3 words long. Remember that each memory address corresponds to the location of one
word. Memory Address
1000
1001 Arr2[1] Start
1002
1003
1004 Arr2[2]
1005
Figure 2-27 Storage Allocation For Array Arr2 With n 3-Word Elements
Using the formula above, the starting address of element Arr2[2] may be computed as follows:
Similarly, calculating for the starting address of element Arr2[6], where 6 ≤ n, will result to:
A computer’s memory is typically a one-dimensional array. This means that two dimensional arrays
and multi-dimensional arrays must be stored in memory in one dimension. There are two ways to do
this:
Let us consider the row major representation of two-dimensional and multi-dimensional arrays. The
following figure illustrates how a 2 x 3 array called Arr1 would be allocated storage in a row major
fashion. Let us assume that each element of Arr1 is one word long.
Memory Address
2000
2001
2002 Arr1[1,1]
2003 Arr1[1,2]
2004 Arr1[1,3]
2005 Arr1[2,1]
2006 Arr1[2,2]
2007 Arr1[2,3]
2008
…
As can be seen in the figure, the elements of Arr1 are stored by row. This means that all elements
of row 1, from left to right, are allocated sequentially before any element of row 2. When using the
row major representation, the address of any element in the array may be computed via following
formula.
Start + k ( [ (i – n) n] + [j – 1])
Where:
For example, let assume that a 3 x 2 array called Arr1 whose elements are each one word long are
stored row major fashion as shown in the figure below:
Memory Address
1000
1001 Arr1[1,1] Start
1002 Arr1[1,2]
1003 Arr1[2,1]
1004 Arr1[2,2]
1005 Arr1[3,1]
1006 Arr1[3,2]
1007
…
Figure 2-29 Row Major Major Representation Of the 3 x 2
Array Arr1
Using the formula, let us compute for the address of the element Arr1[3,1]
Start + k ([ (i – 1) n] + [j – 1]) = 1001 + 1 ( [ (3 – 1) 2] + [1 – 1])
= 1001 + 1 ( [ (2) 2] + 0)
= 1001 + 1 (4)
= 1005
Let us do the same exercise assuming that each element of Arr1 is two (2) words long. The storage
allocation of the elements would appear something like the figure below.
Memory Address
1000
1001 Arr1[1,1] Start
1002
1003 Arr1[1,2]
1004
1005 Arr1[2,1]
1006
1007 Arr1[2,2]
1008
1009 Arr1[3,1]
1010
1011 Arr1[3,2]
…
Figure 2-30 Row Major Representation Of The 3 x 2 Array Arr1 Where Each Element = 2 Words
Computing for the address of element Arr1[2,2] using the same formula would result to:
When a two-dimensional and multi-dimensional array is stored column major, all elements in column
1 are allocated storage before any element in column 2. The following figure shows how the
elements of a 2 x 3 array called Arr1 is stored column major.
Memory
2000 Address
2001 Arr1[1,1] Start
2002 Arr1[2,1]
2003 Arr1[1,2]
2004 Arr1[2,2]
2005 Arr1[1,3]
2006 Arr1[2,3]
…
Figure 2-31 Column Major Representation Of the 2 x 3 Array Arr1
As with the row major representation, it is possible to compute for the address of any element in the
array. The formula to be applied when the array is stored as column major is as follows:
Start + k ( [ (j – 1) m] + [i – 1])
Where:
Let assume that there exists a 2 x 3 array called Arr1 where each element is three words long.
Figure 2-23 shows how Arr1 may be represented in memory as column major.
Memory Address
1000
1001 Arr1[1,1] Start
1002
1003
1004 Arr1[2,1]
1005
1006
1007 Arr1[1,2]
1008
1009
1010 Arr1[2,2]
1011
1012
1013 Arr1[1,3]
1014
1015
1016 Arr1[2,3]
…
Figure 2-32 Column Major Representation Of The 2 x 3 Array Arr1 Where Each Element = 3 Words
EXERCISES
1. Given a one-dimensional array with 50 elements, construct an algorithm that will locate the
smallest and largest elements in the array.
2. The median of set of integers is the value which divides the set exactly in half. Given a one-
dimensional array whose elements are sorted from lowest to highest, the median can be
determined by applying the following rules:
a) If the number of elements in the array is odd, the element in the middle of the array
is the median.
b) If the number of elements in the array is even, the median is computed as the
average of the two middle elements.
Construct an algorithm that will accept as input the array and the number of elements in
the array and output all the array’s elements along with median.
3. Given two arrays, A and B, each containing N elements, construct an algorithm that would
interchange all element of A and B
4. The array Class consists of the set of students in a class of 45. Each element in the array
contains three types of information: 1) the student Name, 2) the Gender of the student and,
3) the final Grade of the student. Each type of information may be accessed via the following
format:
Class Name[subscript] for the Student Name
Class Gender[subscript] for the Gender
(contains “M” for Male and “F” for Female)
Class Grafe[subscript] for the Final Grade
a) Create two (2) arrays named Male and Female. The array Male should contain a
sorted list of all male students in the class. Similarly, array Female will contain a
sorted list of all female students in the class. The arrays Male and Female should
contain only the student names.
b) Print the following information:
1. Average grade of all Male students
2. Average grade of all Female students
3. Average grade of the class
5. Given a one one-dimensional array with 100 4-word elements, compute for the address of
the following elements. Assume that the starting address of the array is 2300.
a) Arr[5]
b) Arr[72]
c) Arr[99]
8. Another kind of sparse matrix that arises often in numerical analysis is the tridiagonal matrix.
In this square matrix, all elements other than those on the major diagonal and on the
diagonals immediately above and below this one are zero.
Col 1 Col 2 Col 3 Col 4 Col 5 Col 6 Col 7 Col 8 Col 9 Col 10
Row 1 X X
Row 2 x X X
Row 3 x X X
Row 4 x X X
Row 5 x X X
Row 6 x X X
Row 7 x X X
Row 8 x X X
Row 9 x X X
Row 10 x x
Figure 2-33 Tridiagonal Matrix A
If the elements in the band formed by these diagonals are represented rowwise in an array
B, then A[1,1] will be stored at B[1], A[1,2] at B[2] and so on. If array B will have total of n
elements, create an algorithm that would determine the value of A[i,j] in B.
9. Using a 3 x 3, construct an algorithm that would allow two users to play the game tic-tac-
toe. Use the symbols “x” and “o” to represent the two values of the array.
10. Given a 25 x 50 array stored in memory in column major and where each element is 5 words
long, compute for the address of the following elements. Starting address of the array is
1500.
a) Arr[5,20]
b) Arr[19,43]
c) Arr[25,50]
Compute for the address of these elements if the array were stored in a row major fashion.