Array is a linear data structure consisting of a collection of elements which are stored in contiguous physical memory locations and can be identified by an index
Typically, we may encounter 2 types of array, divided by dimension: one-dimensional and two-dimensional array
One dimensional (1D) array
Given A as a one-dimensional array which has 4 elements like the below image
Each element in the array can be accessed directly by A[0], A[1], A[2], and A[3] with the corresponding value 9, 2, 6 and 8
Traverse all elements in a 1D array
We can use one for-loop or while-loop to traverse all elements in a 1D array
public class Array1D {
void traversal(int[] A) {
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
}
public static void main(String[] args) {
int[] A = {9, 2, 6, 8};
new Array1D().traversal(A);
}
}
Output
9
2
6
8
Complexity
Time complexity: O(n) where n is the array size
Space complexity: O(1)
Two-dimensional (2D) array
Given A as a two-dimensional array which has 8 elements like the below image
Each element in the array can be accessed directly by A[0][0], A[0][1], A[0][2], A[0][3], A[1][0], A[1][1], A[1][2] and A[1][3] with the corresponding value 9, 2, 6, 8, 5, 7, 1 and 3
A 2D array can be seen as a table with rows and columns. The above array has 4 columns and 2 rows
Traverse all elements in a 2D array
To traverse all elements in a 2D array, we have to use two for-loop or while-loop
public class Array2D {
void traversal(int[][] A) {
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[0].length; j++) {
System.out.println(A[i][j]);
}
}
}
public static void main(String[] args) {
int[][] A = {{9, 2, 6, 8}, {5, 7, 1, 3}};
new Array2D().traversal(A);
}
}
Output
9
2
6
8
5
7
1
3
Complexity
Time complexity: O(n*m) where n is the number of columns and m is the number of rows
Space complexity: O(1)