DSA2 Arrays (061808)
DSA2 Arrays (061808)
DSA2 Arrays (061808)
Algorithms (Arrays)
2
First, a look at primitive
data types
The primitive or built-in variable types in Java are shown below:
3
Questions
4
Introducing Arrays
Arrays are a very useful data structure provided by Java and other
programming languages.
– An array is a variable compose of a finite, ordered set of homogeneous
elements, i.e. elements of the same data type
– Individual elements of this sequence can be uniformly
referenced/updated/ etc. since it consumes a consecutive set of
memory locations
– is a set of pairs - index and a value 0
– forms 1
2
• one-dimensional array
3
• n-dimensional array
4
5
Question:
Based on the definition above, how can arrays address the limitations
of using primitive data types ?
5
Creating Arrays
• Arrays in Java are handled as objects (hence allocated
on heap)
• 2 data types
– base type or component type
– index type
• All data types (primitive and user-defined objects) can
be put into arrays
• To create an array, use the new keyword
• Java has special syntax for array type declaration:
int[] a = new int[5];
– int[] indicates a is array of integer variables
– int[5] indicates a will have 5 elements
• Each cells in the array are assigned default values (0 /
null / etc.) when array created
6
Array Indexing
• Java provides a special syntax for uniformly accessing cells in an
array
– Assume previous declaration of a:
• int[] a = new int[5];
– This in effect creates five int variables “named”:
• a[0] a[1] a[2] a[3] a[4]
– To modify contents of cell #2 to 6:
• a[2] = 6;
• This access mechanism is called array indexing
• 2 basic operations
– extraction and storing
• In Java, the same as with C and C++, array cells are indexed
beginning at 0 and going up to n-1 (n is number of cells)
• Beware of index numbers that exceed the array structure.
• Also, beware of starting the indexing at 0!
7
Example
8
Cell Index numbers
0 1 2 3 4
9
Handling arrays using
loops
Loops Are Useful for Processing Arrays
10
Examples of handling
arrays
int i;
int[] arr1 = new int[5];
arr1[2] = 6;
for (i=0; i<5; i++)
{
arr1[i] = i * 10;
}
11
Exercise Questions
• 2-dimensional arrays:
A[i][j] = α + [(i) * (UB2) + (j)] * esize
where: UB2 = upper bound of the 2nd dimension.
14
• 3-dimensional arrays:
A[i][j][k] = α + [(i) * (UB2) *(UB3) + (j)*(UB3)
+ (k)] * esize
where: UB2 = upper bound of the 2nd dimension;
UB3 = upper bound of the 3rd dimension
esize = element size in bytes
15
Examples
16
Examples
17
Examples
18