Chapter3 Lecture4 Array
Chapter3 Lecture4 Array
Chapter3 Lecture4 Array
1
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double[] myList = new double[10];
myList reference
myList[0] 5.6
myList[1] 4.5
Array reference myList[2] 3.3
variable
myList[3] 13.2
myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34
myList[7] 45.45
myList[8] 99.993
myList[9] 11123
2
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;
3
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
4
Declaring and Creating in One
Step
• datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];
5
The Length of an Array
Once an array is created, its size is fixed. It cannot be
changed. You can find its size using
arrayRefVar.length
For example,
myList.length returns 10
6
Default Values
When an array is created, its elements are
assigned the default value of
7
Indexed Variables
The array elements are accessed through the index.
The array indices are 0-based, i.e., it starts from 0 to
arrayRefVar.length-1. In the example, myList holds ten
double values and the indices are from 0 to 9.
arrayRefVar[index];
8
Using Indexed Variables
After an array is created, an indexed variable can
be used in the same way as a regular variable.
For example, the following code adds the value
in myList[0] and myList[1] to myList[2].
9
Array Initializers
10
Declaring, creating, initializing Using the
Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
11
Out of Bounds
Errors
• It is a dangerous mistake to attempt to index into an array a
using a number outside the range from 0 to myList.length
minus 1.
• Such a reference is said to be out of bounds.
• If an array index is out of bounds, the run-time Java
environment signals an error condition.
• The name of this condition is the
ArrayIndexOutOfBoundsException
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 12
rights reserved. 0132130807
CAUTION
Using the shorthand notation, you have to declare,
create, and initialize the array all in one statement.
Splitting it would cause a syntax error. For example, the
following is wrong:
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
13
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values
14
animation
Trace Program with Arrays
i becomes 1
values[i] = i + values[i-1]; 1 0
} 2 0
0
values[0] = values[1] + values[4];
3
4 0
}
}
15
Trace Program with Arrays
i (=1) is less than 5
} 2 0
} 4 0
16
Trace Program with Arrays
After this line is executed, value[1] is 1
} 3 0
}
}
17
Trace Program with Arrays
After i++, i becomes 2
} 2 0
0
values[0] = values[1] + values[4];
3
4 0
}
}
18
Trace Program with Arrays
i (= 2) is less than 5
public class Test {
public static void main(String[]
args) {
int[] values = new int[5]; After the first iteration
} 2 0
values[0] = values[1] + 3 0
values[4]; 4 0
}
}
19
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)
} 3 0
}
}
20
Trace Program with Arrays
After this, i becomes 3.
} 3 0
}
}
21
Trace Program with Arrays
i (=3) is still less than 5.
} 3 0
}
}
22
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)
} 3 6
}
}
23
Trace Program with Arrays
After this, i becomes 4
} 3 6
}
}
24
Trace Program with Arrays
i (=4) is still less than 5
} 3 6
}
}
25
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)
} 3 6
}
}
26
Trace Program with Arrays
After i++, i becomes 5
values[0] = values[1] + 2 3
values[4]; 3 6
} 4 10
}
27
Trace Program with Arrays
i ( =5) < 5 is false. Exit the loop
3 6
4 10
28
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)
29
Processing Arrays
See the examples in the text.
1. (Initializing arrays with input values)
2. (Initializing arrays with random values)
3. (Printing arrays)
4. (Summing all elements)
5. (Finding the largest element)
6. (Finding the smallest index of the largest element)
7. (Random shuffling)
8. (Shifting elements)
30
Initializing arrays with input values
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();
31
Initializing arrays with random values
32
Printing arrays
33
Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
34
Finding the largest element
35
Copying Arrays
Often, in a program, you need to duplicate an array or a part of an
array. In such cases you could attempt to use the assignment
statement (=), as follows:
list2 = list1;
Before the assignment After the assignment
list2 = list1; list2 = list1;
list1 list1
Contents Contents
of list1 of list1
list2 list2
Contents Contents
of list2 of list2
Garbage
36
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[sourceArray.length];
37
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);
Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);
38
Sorting Arrays
39
Selection Sort
Selection sort finds the largest number in the list and places it last. It then finds
the largest number remaining and places it next to last, and so on until the list
contains only a single number. Figure 6.17 shows how to sort the list {2, 9, 5, 4,
8, 1, 6} using selection sort.
sw a p
T h e n u m b er 2 is n o w in th e
S elec t 4 (th e sm a lles t) a n d s w a p it 1 2 5 4 8 9 6 c o rrec t p o sitio n an d thu s n o
w ith 5 (th e firs t) in th e rem a in in g lo n g er n e ed s to b e c o n s id ered .
list
T h e n u m b er 6 is n o w in th e
5 is th e sm a llest an d in th e righ t 1 2 4 5 8 9 6 c o rrec t p o sitio n an d thu s n o
p o s itio n . N o sw a p is n ec es sa ry lo n g er n e ed s to b e c o n s id ered .
sw a p
T h e n u m b er 5 is n o w in th e
S elec t 6 (th e sm a lles t) a n d s w a p it 1 2 4 5 8 9 6 c o rrec t p o sitio n an d thu s n o
w ith 8 (th e first) in th e rem a in in g lo n g er n e ed s to b e c o n s id ered .
list sw a p
T h e n u m b er 6 is n o w in th e
S elec t 8 (th e sm a lles t) a n d s w a p it 1 2 4 5 6 9 8 c o rrec t p o sitio n an d thu s n o
w ith 9 (th e first) in th e rem a in in g lo n g er n e ed s to b e c o n s id ered .
list
T h e n u m b er 8 is n o w in th e
S in c e th ere is o n ly o n e elem en t 1 2 4 5 6 8 9 c o rrec t p o sitio n an d th u s n o
rem a in in g in th e list, so rt is lo n g er n e ed s to b e c o n sid ered .
c o m p leted
40
From Idea to Solution
for (int i = 0; i < list.length; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
...
42
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
43
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
44
Wrap it in a Method
/** The method for sorting the numbers */
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
Invoke it selectionSort(yourList)
45
Insertion Sort
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted
The insertion sort Step 1: Initially, the sorted sublist contains the 2 9 5 4 8 1 6
algorithm sorts a list first element in the list. Insert 9 to the sublist.
of values by
Step2: The sorted sublist is {2, 9}. Insert 5 to the
repeatedly inserting sublist.
2 9 5 4 8 1 6
an unsorted element
into a sorted sublist Step 3: The sorted sublist is {2, 5, 9}. Insert 4 to 2 5 9 4 8 1 6
the sublist.
until the whole list
is sorted. Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8 2 4 5 9 8 1 6
to the sublist.
46
animation Insertion
Sort
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted
2 9 5 4 8 1 6
2 9 5 4 8 1 6
2 5 9 4 8 1 6
2 4 5 9 8 1 6
2 4 5 8 9 1 6
1 2 4 5 8 9 6
1 2 4 5 6 8 9
47
How to Insert?
The insertion sort algorithm sorts a list of values by repeatedly inserting
an unsorted element into a sorted sublist until the whole list is sorted.
list[0]
list[0] list[1]
InsertSort
49
The Arrays.sort Method
Since sorting is frequently used in programming, Java provides several
overloaded sort methods for sorting an array of int, double, char, short,
long, and float in the java.util.Arrays class. For example, the following
code sorts an array of numbers and an array of characters.
50