Data Structures: Lecture1. Arrays
Data Structures: Lecture1. Arrays
Lecture1. Arrays
Prepared by Soraya Reyhan
Computer Science Faculty
Arrays
An array is a collection of items stored at contiguous memory locations. The idea is to
store multiple items of the same type together. Each element can be uniquely identified
by their index in the array.
Advantages of using arrays: Arrays allow random access of elements. This makes
accessing elements by position faster.
2
Arrays
Arrays are objects. Arrays may be assigned to variables of type Object. Any method of
the Object class may be invoked on an array.
An array object contains a sequence of variables. The variables are called the
components or elements of the array. If the component type is T, then the array itself has
type T[]. An array type variable holds a reference to the array object.
a.getClass() is the type of array a
An array of integers has type [I
An array of Strings has type [Ljava.lang.String;
3
Arrays
The length of an array is its number of components. An array’s length is set when the
array is created, and it cannot be changed. An array’s length can be accessed as a public
final instance variable.
a.length is the length of array a
4
2D arrays in Java
Java doesn’t have “real” 2D arrays, but array elements can themselves be arrays:
int x[][] denotes an array x of array components, each of which is an array of integer
components
We can define the above array like this:
x = new int[5][8];
and treat it as a regular 2D array
This is an array of 5 arrays
Each subarray is an array of 8 ints
5
Some Array Definitions
1 public class ArrayDefs {
2 public static void main(String[] args) {
3 float x[];
4 x = new float[100];
5 args = new String[10];
6 boolean[] isPrime = new boolean[1000];
7 int fib[] = {0, 1, 1, 2, 3, 5, 8, 13};
8 short[][][] b = new short[4][10][5];
9 double a[][] = {{1.1,2.2}, {3.3,4.4}, null, {5.5,6.6}, null};
10 a[4] = new double[66];
11 a[4][65] = 3.14;
12 Object[] objects = {x, args, isPrime, fib, b, a};
13 }
14 }
6
Duplicating an Array
15 public class DuplicatingArrays { 30 public static void print(int[] a) {
16 public static void main(String[] args) { 31 System.out.printf("{%d", a[0]);
17 int[] a = {22, 44, 66, 88}; 32 for (int i = 1; i < a.length; i++) {
18 print(a); 33 System.out.printf(", %d", a[i]);
19 int[] b = (int[])a.clone(); // duplicate a[] in b[] 34 }
20 print(b); 35 System.out.println("}");
21 String[] c = {"AB", "CD", "EF"}; 36 }
22 print(c); 37
String[] d = (String[])c.clone(); // duplicate c[] in d[] 38 public static void print(Object[] a) {
24 print(d); 39 System.out.printf("{%s", a[0]);
25 c[1] = "XYZ"; // change c[], but not d[] 40 for (int i = 1; i < a.length; i++) {
26 print(c); 41 System.out.printf(", %s", a[i]);
27 print(d); 42 }
28 } 43 System.out.println("}");
29 44 }
45 }
7
java.util.Arrays Class
import java.util.Arrays; 13 System.out.printf("Arrays.binarySearch(a, 45):
2 %d%n", k);
3 public class TestArrays { 14 int[] b = new int[8];
4 public static void main(String[] args) { 15 print(b);
5 int[] a = {44, 77, 55, 22, 99, 88, 33, 66}; 16 Arrays.fill(b, 55);
6 print(a); 17 print(b);
7 Arrays.sort(a); 18 System.out.println("Arrays.equals(a,b): " +
8 print(a); Arrays.equals(a,b));
9 int k = Arrays.binarySearch(a, 44); 19 }
10 System.out.printf("Arrays.binarySearch(a, 44): 20 }
%d%n", k);
11 System.out.printf("a[%d]: %d%n", k, a[k]);
12 k = Arrays.binarySearch(a, 45);
8
Jagged Array in Java
If we are creating odd number of columns in a 2D array, it is known as a jagged array. In
other words, it is an array of arrays with different number of columns.
//Java Program to illustrate the jagged array arr[i][j] = count++;
class TestJaggedArray{ //printing the data of a jagged array
public static void main(String[] args){ for (int i=0; i<arr.length; i++){
//declaring a 2D array with odd columns for (int j=0; j<arr[i].length; j++){
int arr[][] = new int[3][]; System.out.print(arr[i][j]+" ");
arr[0] = new int[3]; }
arr[1] = new int[4]; System.out.println();//new line
arr[2] = new int[2]; }
//initializing a jagged array }
int count = 0; }
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
9
Copying a Java Array
We can copy an array to another by the arraycopy() method of System class.
public static void arraycopy( Object src, int srcPos,Object dest, int destPos, int length )
//Java Program to copy a source array into a destination array in Java
class TestArrayCopyDemo {
public static void main(String[] args) {
//declaring a source array
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
//declaring a destination array
char[] copyTo = new char[7];
//copying array using System.arraycopy() method
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
//printing the destination array
System.out.println(String.valueOf(copyTo));
}
} 10
Search Operation in array
You can perform a search for an array element based on its value.
The sequential search (also called the linear search) is the simplest search algorithm. It
is also the least efficient. It simply examines each element sequentially, starting with the
first element, until it finds the key element or it reaches the end of the array.
The binary search is the standard algorithm for searching through a sorted sequence. It is
much more efficient than the sequential search, but it does require that the elements be in
order. It repeatedly divides the sequence in two, each time restricting the search to the
half that would contain the element.
We discussed this topic in Design & Analysis of Algorithms course last semester.
11
Inserting an element into an ordered array
In an unsorted array, the insert operation is faster as compared to sorted array
because we don’t have to care about the position at which the element to be placed.
Suppose we want to insert the value 8 into this sorted array (while keeping the
array sorted)
1 3 3 7 12 14 17 19 22 30
We can do this by shifting all the elements after the mark right by one location
Of course, we have to discard the 30 when we do this
1 3 3 7 8 12 14 17 19 22
Moving all those elements makes this a slow operation (linear in the size of the
array)
12
Inserting into an Ordered Array
1 void insert(int[] a, int n, int x) {
2 // preconditions: a[0] <= ... <= a[n-1], and n < a.length;
3 // postconditions: a[0] <= ... <= a[n], and x is among them;
4 int i = 0;
5 while (i < n && a[i] <= x) {
6 ++i;
7}
8 System.arraycopy(a, i, a, i+1, n-i); // copies a[i..n) into a[i+1..n+1)
9 a[i] = x;
10 }
13